From 2012bd49a8baefeb148afbbad1a9556abe0ec007 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 07:58:50 -0400 Subject: [PATCH 001/111] feat(task-list): explicit priority ordering and cross-list move Adds opt-in priority order to both backends with `move`, `reorder`, and `all({ order })` plus `TaskList.moveBetweenLists`. Markdown-dir encodes order via a numeric filename prefix; yaml-file relies on insertion order in the YAML map. Records `created` for `order: 'created'`. --- .../plans/task-list-ordering-and-gh-issues.md | 325 ++++++++++++++++ .../src/backends/conformance.test.ts | 171 ++++++++- .../src/backends/markdown-dir.test.ts | 12 +- .../task-list/src/backends/markdown-dir.ts | 348 +++++++++++++++--- packages/task-list/src/backends/utils.ts | 29 +- packages/task-list/src/backends/yaml-file.ts | 210 ++++++++++- packages/task-list/src/index.ts | 4 + packages/task-list/src/types.ts | 40 ++ 8 files changed, 1066 insertions(+), 73 deletions(-) create mode 100644 docs/plans/task-list-ordering-and-gh-issues.md diff --git a/docs/plans/task-list-ordering-and-gh-issues.md b/docs/plans/task-list-ordering-and-gh-issues.md new file mode 100644 index 0000000000..b422682eb5 --- /dev/null +++ b/docs/plans/task-list-ordering-and-gh-issues.md @@ -0,0 +1,325 @@ +--- +$schema: https://poe-platform.github.io/poe-code/schemas/plans/feature.schema.json +kind: feature +version: 1 +status: + state: draft +--- + +# task-list: ordering + gh-issues backend + +Two adjacent features for [packages/task-list/](packages/task-list/): + +1. Explicit task ordering — backlog/Kanban-style "what's next" semantics with a small, pluggable API. +2. A third backend: `gh-issues`, backed by a GitHub repo + GitHub Project (v2). Same `TaskList` shape, real issues underneath. + +The README currently calls these "backends"; the user calls them "providers". This plan keeps the codebase term **backend** and notes the alias once. No rename. + +## 1. What we're building + +### 1a. Ordering + +Today, `Tasks.all()` returns tasks sorted alphabetically by `qualifiedId` ([backends/utils.ts:23-25](packages/task-list/src/backends/utils.ts#L23-L25)). There is no notion of "first task to work on next" — the consumer has to impose its own order. We add an **opt-in, per-list** order with a small API that both backends implement uniformly. + +Out of scope: + +- Cross-list global ordering. Order is scoped to one list. +- Sub-tasks, dependency DAGs, due-date sort. (Use `metadata` + your own sort if you need it.) +- Re-deriving order from state. State and order are independent axes. + +### 1b. `gh-issues` backend + +A new backend selected by `type: "gh-issues"` that maps the `TaskList`/`Tasks`/`Task` shapes onto a single GitHub repo + a single GitHub Project (v2). Lists map to the project's **Status field values** (because that's where ordering and "what's next" already live in GH Projects). State machine maps onto issue open/closed + project status. + +Out of scope for v1: + +- Multi-repo or multi-project per backend instance. One repo + one project per `openTaskList` call. +- Creating the repo or project. They must already exist; we only read/write items inside them. +- GitHub Apps. v1 uses a token (env var) read from a single source. +- Webhooks / live sync. All reads hit the API on demand. + +## 2. Terminology note + +`@poe-code/task-list` ships with two backends today (`markdown-dir`, `yaml-file`). `gh-issues` is a third **backend**, selected by the same `type` discriminant in `OpenTaskListOptions`. We won't introduce the word "provider" in this package — it already means something else across poe-code (auth providers in `src/providers/`). + +## 3. Ordering — API surface + +### 3a. Methods on `Tasks` + +Order is the only view. `all()` and `get()` keep their names; their **default return order changes** to priority order, and `all()` accepts an optional `order` discriminator for callers that need something else. Two new mutators: + +```ts +interface ListFilter { + state?: string; + includeArchived?: boolean; + order?: "priority" | "alphabetical" | "created"; // default: "priority" +} + +interface Tasks { + // ...existing... + all(filter?: ListFilter): Promise; // signature unchanged, default sort changed + + /** Move a task to a position relative to another task or to an end. */ + move(id: string, anchor: MoveAnchor): Promise; + + /** Replace the entire ordering for this list. ids must be the exact set + * of currently active (non-archived) tasks; throws on missing/extra ids. */ + reorder(ids: readonly string[]): Promise; +} + +type MoveAnchor = + | { before: string } + | { after: string } + | { position: "top" | "bottom" }; +``` + +Why these two mutators: + +- `move(id, anchor)` covers "drag this above that" / "send to end" — the 90% case in any UI. +- `reorder(ids[])` covers bulk drag-drop / list-replacement. One write, no per-step renames. + +Why no `swap(a, b)` or `setPosition(id, n)`: + +- `swap` is `reorder([…])` with two indices flipped — trivial in the caller. +- `setPosition(id, n)` invites off-by-one bugs and races (`n` becomes wrong if anyone else inserted). `before`/`after` is content-addressed and stable under concurrent edits. + +### 3a-bis. Default sort is priority; opt out via `order` + +Current: `all()` returns tasks sorted alphabetically by `qualifiedId` ([backends/utils.ts:23-25](packages/task-list/src/backends/utils.ts#L23-L25)). New default: priority order. Callers who needed alphabetical pass `{ order: "alphabetical" }` explicitly. + +Supported `order` values: + +- `"priority"` (default): the order materialized in the backend (filename prefix for `markdown-dir`, YAML key order for `yaml-file`, project view order for `gh-issues`). +- `"alphabetical"`: by `qualifiedId`. The current default sort, now opt-in. +- `"created"`: by creation time, oldest first. Requires backends to track it. `markdown-dir` writes a `created` ISO timestamp into frontmatter on `create()`; `yaml-file` writes a `created` field on the task record; `gh-issues` reads `createdAt` from the issue. Existing tasks without a `created` field sort to the tail in `readdir` / map-key order. + +`allTasks()` (top-level) gets the same `order` option. Lists are iterated in alphabetical list-name order regardless; `order` controls within-list sort only. + +This is a **breaking default-sort change**. Acceptable because (a) the package is internal and pre-1.0, (b) "everything is ordered" is the simpler mental model, and (c) the alphabetical opt-out is one extra option literal. + +### 3b. Semantics + +- **Archived tasks are unordered.** `move`, `reorder`, and `ordered` ignore archived tasks. Archive is terminal anyway. +- **Newly created tasks append to the end.** `create()` adds the new id to the tail of the order. No new option on `TaskCreate`. +- **Deleted/archived tasks drop out of the order.** `delete()` and `fire(_, "archive")` remove the id from the order list. +- **`reorder` is set-equality strict.** It throws if the input is missing any active id or contains an unknown one. (Use `move` for incremental edits.) +- **No persistence of "after-archive" order.** If you unarchive (custom state machine), the task lands at the tail. + +### 3c. Errors + +Add to the existing error class set in [src/types.ts](packages/task-list/src/types.ts): + +```ts +class OrderMismatchError extends Error { /* missing or extra ids in reorder() */ } +class AnchorNotFoundError extends Error { /* anchor id missing in move() */ } +``` + +`InvalidTransitionError` is reserved for state-machine events; ordering errors are a separate axis. + +## 4. Ordering — storage layout + +The two existing backends store tasks differently, so order has to land in two different places. Both should be visible to a human reading the file. + +### 4a. `markdown-dir` — filename priority prefix + +Filenames carry the order. Priority is visible the moment you `ls` the list directory. + +```text +tasks/ + planning/ + 01-ship-readme.md + 02-review-release.md + 03-cut-beta.md + archive/ + old-thing.md ← archived files have no prefix +``` + +Format: `-.md` where `` is a zero-padded decimal integer. Padding width is per-list and grows automatically: a list with up to 99 active tasks pads to 2; once it crosses 100, a single rebalance writes 3-digit prefixes for everything in that list. Width is purely cosmetic (used for `ls` ordering) — the parser reads the integer regardless of pad. + +#### Id parsing + +Id = filename with `.md` stripped, then with the leading `^\d+-` prefix stripped. Examples: + +- `01-ship-readme.md` → id `ship-readme` +- `ship-readme.md` (no prefix) → id `ship-readme` (back-compat) +- `2025-budget.md` (id starts with digits) → id `2025-budget` ← see ambiguity note below + +Ambiguity: a hand-created file like `2025-budget.md` parses as id `budget` with order `2025`, which is wrong. Resolution: **the order prefix is only recognized when the integer is ≤ the current list's max width + 1 digit**, AND the rest of the filename is a valid `validateTaskId` value. Anything that fails either check is treated as a no-prefix file. We document this in the package README. Users with id collisions across the prefix boundary should rename. + +#### Mutations + +- `create({ id })` writes `-.md` where `` is `(max-existing-order) + 1`. New tasks land at the tail. +- `move(id, { before: x })` renames `id`'s file to one less than `x`'s order, then cascade-shifts neighbors as needed to keep the integer sequence non-overlapping. Worst case: rename every file from the move target to the old position. We accept that — it's the cost of "priority lives in the filename". +- `move(id, { position: "top" })` → cascade-shift everyone else down by one, place `id` at `01`. Same worst case. +- `reorder(ids[])` writes the entire list once: rename each file to `-.md`. One pass, no incremental cascade. Prefer this for bulk moves. +- `fire(id, "archive")` strips the prefix on the rename into `archive/`. Archived files have no order. +- Files with no prefix on read → treated as priority `Infinity` (tail). On the next mutation that touches the list, they get materialized with a real prefix. + +#### Locking + +Reorder operations need to lock the whole list, not just one task. The existing per-task-file lock pattern in [markdown-dir.ts:448-461](packages/task-list/src/backends/markdown-dir.ts#L448-L461) doesn't cover this. We add a list-level lock at `/.order.lock` (a hidden lock file, not an order manifest — just the lock). `move` / `reorder` / `create` / `delete` / archiving `fire` all take it. The single-task `update` and non-archiving `fire` keep the per-task lock. + +#### Rejected alternatives + +| Option | Why not | +| --- | --- | +| Per-list `.order` YAML manifest | Priority isn't visible in `ls`. The user wants visibility — that's the whole point. | +| Frontmatter `order: ` | Same visibility problem. Plus fractional drift. | +| Sparse numbering (`010, 020, 030`) | Saves renames at first, fills up, then needs the same rebalance anyway. Tight numbering is simpler and the renames are git's problem, not ours. | + +### 4b. `yaml-file` — rely on YAML key order + +The `yaml-file` backend already stores tasks as a YAML map under `lists.` and the `yaml` library preserves insertion order. We commit to that as the priority order: + +- `create()` appends a new key at the end of the list map (already the default). +- `move` / `reorder` reorders the YAMLMap.items array directly, then writes. +- `all()` with default `{ order: "priority" }` returns tasks in the map's current key order. +- `all({ order: "alphabetical" })` runs the existing `sortTasks` path. + +No new field, no schema change. The change to [yaml-file.ts:425](packages/task-list/src/backends/yaml-file.ts#L425) is to branch on `filter?.order` rather than always calling `sortTasks`. + +### 4c. State machine and ordering + +State and order are independent. `fire("archive")` removes from the order list as part of the existing archive write. No state machine changes. `defaultStateMachine` stays as-is. + +## 5. `gh-issues` backend + +The backend is a thin wrapper over a single (repo, project) pair: one project's items shown as one list of tasks, with the project's Status field supplying the state machine. No list selection, no Status-as-list — just open the project and operate on it. + +### 5a. Configuration + +```ts +const taskList = await openTaskList({ + type: "gh-issues", + repo: "owner/name", + project: { owner: "owner", number: 12 }, // GH Project (v2); both fields required + // auth is optional — defaults to whatever `gh auth token` returns. See 5d. +}); +``` + +`repo` and `project` are required. `OpenTaskListOptions` becomes a discriminated union over `type`: + +```ts +type OpenTaskListOptions = + | OpenMarkdownDirOptions + | OpenYamlFileOptions + | OpenGhIssuesOptions; + +interface OpenGhIssuesOptions { + type: "gh-issues"; + repo: string; // "owner/name" + project: { owner: string; number: number }; + defaults?: TaskDefaults; + auth?: { token: string }; // optional; see 5d + fetch?: typeof fetch; // injectable for tests +} +``` + +`OpenGhIssuesOptions` deliberately excludes `path`, `create`, `lockStaleMs`, `lockRetries`, `fs`, and `stateMachine` — none apply. The state machine is fetched from the project (5c), not configured. + +### 5b. Mapping + +| `task-list` concept | GitHub mapping | +| --- | --- | +| backend instance | one repo + one project | +| `lists()` | returns a single name: `/` (the project itself). `taskList.list(name)` accepts only that name. | +| `id` | Issue number as a string (`"482"`). | +| `name` | Issue title. | +| `description` | Issue body. | +| `state` | The current value of the project's Status field for this item. See 5c. | +| `metadata` | `{ url, labels: string[], assignees: string[], milestone: string \| null, projectItemId: string }`. | +| priority order | The project view's row order, read via the GraphQL `items` connection. | +| `created` | Issue `createdAt` (ISO 8601). Used for `order: "created"`. | + +The earlier "Status as list" framing is dropped. Status is now the **state axis**, and the backend has only one list. This collapses the model: a GH Project is "a list of tasks with a state", and that's exactly what `Tasks` already is. + +`taskList.lists()` always returns `[/]`. `taskList.list("anything-else")` throws `Error("gh-issues backend has a single list /")`. `moveBetweenLists` is unsupported (only one list); it throws the same error. + +### 5c. State machine — fetched and dynamic + +At `openTaskList` time, the backend issues a GraphQL query for the project's Status field and its options. The state machine is **derived** from those options: + +- `states` = the Status field's option names, in the project's display order. +- `initial` = the first option (typically `"Backlog"` or whatever the project owner put first). +- `events` = one event per state: `event name = state name`, `from: "*"`, `to: `. Any state can transition to any other state. No guards. + +Result: `tasks.fire(id, "in-progress")` updates the issue's Status to `"in-progress"` (the option must exist on the project; otherwise the call is a no-op at the type level since the event doesn't exist). + +If the project has no `Status` field, `openTaskList` throws with a clear message: `` "Project `/` has no Status field; gh-issues requires one." `` Adding the field is a one-time setup in the GH UI; we do not mutate project schema. + +The state machine is **frozen at open time**. If the project owner adds, removes, or renames Status options mid-session, the backend keeps using the version it fetched on open. Re-open the backend to pick up changes. Documented in the package README. + +`stateMachine` in `OpenTaskListOptions` is not accepted for `gh-issues` — there's no override path. The project's Status field is the source of truth. + +#### Updating the project's Status options + +The plan reads "fetch the possible states if possible, and update them" two ways. We pick one and move: + +- We **fetch** Status options at open and use them as `states`. +- We **update** an item's Status (i.e., fire transitions) — that is the write side. +- We do **not** update the Status options themselves (adding new options, renaming them). That's project-schema mutation; the project owner does it in the GH UI. Doing it from a task-list call would surprise teammates and is a big enough surface that it deserves its own command if anyone wants it. + +If you want to add a new state, add the option in GH first, then re-open the backend. + +### 5d. Auth + +The backend defers to the `gh` CLI's configured auth — same setup the user already has working from the terminal. No new login flow, no new env var, no separate config. + +Resolution order: + +1. If `auth: { token }` is passed explicitly, use it. (Escape hatch for tests / CI without `gh` installed.) +2. Otherwise, shell out to `gh auth token` once at backend open and cache the result for the session. +3. If `gh` is not installed or returns a non-zero exit, throw with a clear message: install `gh`, run `gh auth login`, or pass `auth: { token }`. + +GraphQL endpoint follows `gh`'s convention: `GH_HOST` env var if set, else `https://api.github.com`. We do not parse `~/.config/gh/hosts.yml` directly; `gh auth token` already accounts for the active host. + +Out of scope: OAuth flows, GitHub App auth, multi-host failover. The user has a working `gh` setup, we use it. + +### 5e. Operation mapping + +| `Tasks` method | GH mutation | +| --- | --- | +| `create({ id?, name, description })` | `createIssue` in repo, then `addProjectV2ItemById` to put it in the project, then `updateProjectV2ItemFieldValue` to set Status to `initial`. `id` is ignored on create — the GH-assigned issue number becomes the id. (The `TaskCreate.id` field becomes optional for this backend; documented.) | +| `update(id, patch)` | `updateIssue` for title/body. Metadata edits are no-ops at v1 — labels/assignees are read-only here; future work. | +| `fire(id, event)` | `updateProjectV2ItemFieldValue` setting Status to `event` (event name == target state name). | +| `delete(id)` | `deleteProjectV2Item` (removes from project; issue stays in repo, not closed). | +| `move(id, anchor)` | `updateProjectV2ItemPosition` to place the item before/after the anchor's project item. `top`/`bottom` use `null` / project end. | +| `reorder(ids)` | n positional updates in order. No batch mutation in the GraphQL API; we accept the n round-trips. | +| `all({ order })` | `priority` = project view row order; `alphabetical` = client-side sort by id; `created` = `createdAt`. | + +Issue `state` (open/closed) is **not** part of the task-list state machine. Closing or reopening an issue is out of scope here; users do it in the GH UI. If they close an issue, it stays in the project at its current Status until removed. + +### 5f. Reads, writes, caching + +- All reads hit the GraphQL API; no caching in v1. (If this gets slow we add `@poe-code/cached-resource` later — there's already a package for it.) +- Writes are: create issue, edit title/body, add/remove project item, set Status field value, reorder project item. All via GraphQL. +- Lock options (`lockStaleMs`, `lockRetries`) don't apply. Concurrent writes are arbitrated by GitHub. +- Per `feedback_no_corner_cutting`: if a GraphQL response is malformed, throw a `MalformedTaskError` with the surfaced field, don't paper over it. + +### 5g. Tests + +The backend skips the conformance suite (no live API in unit tests). It gets its own colocated tests in [packages/task-list/src/backends/gh-issues.test.ts](packages/task-list/src/backends/gh-issues.test.ts) using an injectable `fetch` mock that returns recorded GraphQL responses (one fixture per test). Snapshot the **outgoing** GraphQL queries+variables to lock the wire shape; assert on the resulting `Task` shape from the response. The `gh auth token` shell-out is bypassed by passing `auth: { token: "test-token" }` in tests. + +`@poe-code/process-runner` already exposes a process abstraction for shelling out — wire `gh auth token` through it (per `feedback_extend_not_duplicate`). No `child_process.spawn` in this package. + +## 6. Conformance tests + +[backends/conformance.test.ts](packages/task-list/src/backends/conformance.test.ts) already runs the same suite against both existing backends. Extend it with: + +- Ordering: `move(before/after/top/bottom)`, `reorder` set-equality, `all()` default = priority after archive/delete/create, `all({ order: "alphabetical" })` round-trip. +- `markdown-dir`-only: filename prefix migration (no-prefix file is treated as tail; first mutation materializes a real prefix), padding-width rebalance at the 99→100 boundary, archive strips the prefix. +- The `gh-issues` backend skips the conformance run by default (no live API in unit tests). It gets its own snapshot-style tests against a recorded GraphQL fixture in [docs/SNAPSHOT_TESTING.md](docs/SNAPSHOT_TESTING.md) style. + +## 7. Implementation order + +If you want to ship this incrementally: + +1. Ordering API surface in `types.ts` (`move`, `reorder`, `order` filter, `moveBetweenLists`) + conformance tests (red). +2. `yaml-file` ordering — YAML key order; `created` field on records. +3. `markdown-dir` ordering — filename prefix, list-level lock, `created` frontmatter timestamp, no-prefix back-compat. +4. `moveBetweenLists` on `TaskList` for both existing backends. +5. `gh-issues` backend skeleton (`openTaskList` + auth via `gh auth token` + `lists()` + `Tasks.all()` read-only). +6. `gh-issues` writes (`create`, `update`, `fire` for the GH-specific machine). +7. `gh-issues` ordering + `moveBetweenLists` (project Status field writes, item position). + +Each step ships green tests before the next starts. diff --git a/packages/task-list/src/backends/conformance.test.ts b/packages/task-list/src/backends/conformance.test.ts index 095cdd8235..af90d74265 100644 --- a/packages/task-list/src/backends/conformance.test.ts +++ b/packages/task-list/src/backends/conformance.test.ts @@ -2,7 +2,9 @@ import type { Volume } from "memfs"; import { afterEach, describe, expect, it, vi } from "vitest"; import { assertEvent, defaultStateMachine, type TaskEvent } from "../state.js"; import { + AnchorNotFoundError, InvalidTransitionError, + OrderMismatchError, TaskAlreadyExistsError, TaskNotFoundError, type BackendDeps, @@ -380,8 +382,8 @@ function describeBackendConformance( }) ).resolves.toEqual([ expect.objectContaining({ qualifiedId: "alpha/one" }), - expect.objectContaining({ qualifiedId: "beta/three", state: "archived" }), - expect.objectContaining({ qualifiedId: "beta/two" }) + expect.objectContaining({ qualifiedId: "beta/two" }), + expect.objectContaining({ qualifiedId: "beta/three", state: "archived" }) ]); await expect(taskList.get("beta/three")).resolves.toMatchObject({ state: "archived" @@ -507,11 +509,174 @@ function describeBackendConformance( 'Invalid task id "nested/id".' ); }); + + describe("ordering", () => { + async function seedThree(tasks: Tasks): Promise { + await tasks.create({ id: "alpha", name: "Alpha" }); + await tasks.create({ id: "bravo", name: "Bravo" }); + await tasks.create({ id: "charlie", name: "Charlie" }); + } + + function ids(tasks: readonly { id: string }[]): string[] { + return tasks.map((task) => task.id); + } + + it("creates tasks at the tail of priority order", async () => { + const { taskList } = await openBackend(factory, { path: rootPath }); + const tasks = taskList.list("planning"); + await seedThree(tasks); + + await expect(tasks.all().then(ids)).resolves.toEqual(["alpha", "bravo", "charlie"]); + }); + + it("move({ before }) places the task before the anchor", async () => { + const { taskList } = await openBackend(factory, { path: rootPath }); + const tasks = taskList.list("planning"); + await seedThree(tasks); + + await tasks.move("charlie", { before: "alpha" }); + + await expect(tasks.all().then(ids)).resolves.toEqual(["charlie", "alpha", "bravo"]); + }); + + it("move({ after }) places the task after the anchor", async () => { + const { taskList } = await openBackend(factory, { path: rootPath }); + const tasks = taskList.list("planning"); + await seedThree(tasks); + + await tasks.move("alpha", { after: "bravo" }); + + await expect(tasks.all().then(ids)).resolves.toEqual(["bravo", "alpha", "charlie"]); + }); + + it("move({ position: 'top' }) sends the task to the head", async () => { + const { taskList } = await openBackend(factory, { path: rootPath }); + const tasks = taskList.list("planning"); + await seedThree(tasks); + + await tasks.move("charlie", { position: "top" }); + + await expect(tasks.all().then(ids)).resolves.toEqual(["charlie", "alpha", "bravo"]); + }); + + it("move({ position: 'bottom' }) sends the task to the tail", async () => { + const { taskList } = await openBackend(factory, { path: rootPath }); + const tasks = taskList.list("planning"); + await seedThree(tasks); + + await tasks.move("alpha", { position: "bottom" }); + + await expect(tasks.all().then(ids)).resolves.toEqual(["bravo", "charlie", "alpha"]); + }); + + it("move() rejects unknown anchors", async () => { + const { taskList } = await openBackend(factory, { path: rootPath }); + const tasks = taskList.list("planning"); + await seedThree(tasks); + + await expect(tasks.move("alpha", { before: "missing" })).rejects.toBeInstanceOf(AnchorNotFoundError); + }); + + it("reorder replaces the entire order", async () => { + const { taskList } = await openBackend(factory, { path: rootPath }); + const tasks = taskList.list("planning"); + await seedThree(tasks); + + await tasks.reorder(["charlie", "alpha", "bravo"]); + + await expect(tasks.all().then(ids)).resolves.toEqual(["charlie", "alpha", "bravo"]); + }); + + it("reorder rejects missing or extra ids with OrderMismatchError", async () => { + const { taskList } = await openBackend(factory, { path: rootPath }); + const tasks = taskList.list("planning"); + await seedThree(tasks); + + await expect(tasks.reorder(["alpha", "bravo"])).rejects.toBeInstanceOf(OrderMismatchError); + await expect( + tasks.reorder(["alpha", "bravo", "charlie", "delta"]) + ).rejects.toBeInstanceOf(OrderMismatchError); + }); + + it("archive removes the task from priority order", async () => { + const { taskList } = await openBackend(factory, { path: rootPath }); + const tasks = taskList.list("planning"); + await seedThree(tasks); + + await tasks.fire("bravo", "archive"); + + await expect(tasks.all().then(ids)).resolves.toEqual(["alpha", "charlie"]); + }); + + it("delete removes the task from priority order", async () => { + const { taskList } = await openBackend(factory, { path: rootPath }); + const tasks = taskList.list("planning"); + await seedThree(tasks); + + await tasks.delete("bravo"); + + await expect(tasks.all().then(ids)).resolves.toEqual(["alpha", "charlie"]); + }); + + it("all({ order: 'alphabetical' }) sorts by id", async () => { + const { taskList } = await openBackend(factory, { path: rootPath }); + const tasks = taskList.list("planning"); + await seedThree(tasks); + await tasks.move("charlie", { position: "top" }); + + await expect(tasks.all({ order: "alphabetical" }).then(ids)).resolves.toEqual([ + "alpha", + "bravo", + "charlie" + ]); + }); + + it("all({ order: 'created' }) sorts by creation time", async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date("2026-01-01T00:00:00Z")); + + const { taskList } = await openBackend(factory, { path: rootPath }); + const tasks = taskList.list("planning"); + + await tasks.create({ id: "first", name: "First" }); + vi.setSystemTime(new Date("2026-01-02T00:00:00Z")); + await tasks.create({ id: "second", name: "Second" }); + vi.setSystemTime(new Date("2026-01-03T00:00:00Z")); + await tasks.create({ id: "third", name: "Third" }); + + await tasks.move("third", { position: "top" }); + + await expect(tasks.all({ order: "created" }).then(ids)).resolves.toEqual([ + "first", + "second", + "third" + ]); + }); + + it("moveBetweenLists transfers a task to another list at the tail", async () => { + const { taskList } = await openBackend(factory, { path: rootPath }); + const planning = taskList.list("planning"); + const doing = taskList.list("doing"); + + await planning.create({ id: "shared", name: "Shared" }); + await doing.create({ id: "existing", name: "Existing" }); + + const moved = await taskList.moveBetweenLists("planning/shared", "doing"); + + expect(moved).toMatchObject({ + list: "doing", + id: "shared", + qualifiedId: "doing/shared" + }); + await expect(planning.all().then(ids)).resolves.toEqual([]); + await expect(doing.all().then(ids)).resolves.toEqual(["existing", "shared"]); + }); + }); }); } describeBackendConformance("markdown-dir backend", markdownDirBackend, "/repo/tasks", (rootPath, list, id) => ({ - taskPath: `${rootPath}/${list}/${id}.md` + taskPath: `${rootPath}/${list}/01-${id}.md` })); describeBackendConformance("yaml-file backend", yamlFileBackend, "/repo/tasks.yaml", (rootPath) => ({ diff --git a/packages/task-list/src/backends/markdown-dir.test.ts b/packages/task-list/src/backends/markdown-dir.test.ts index d193bd4690..828b2a8341 100644 --- a/packages/task-list/src/backends/markdown-dir.test.ts +++ b/packages/task-list/src/backends/markdown-dir.test.ts @@ -237,8 +237,8 @@ state: draft "/repo/tasks/.keep": "" }); const blockedPaths = new Map([ - ["/repo/tasks/alpha/one.md", createDeferred()], - ["/repo/tasks/beta/two.md", createDeferred()] + ["/repo/tasks/alpha/01-one.md", createDeferred()], + ["/repo/tasks/beta/01-two.md", createDeferred()] ]); const startedPaths: string[] = []; const fs: TaskListFs = { @@ -287,12 +287,12 @@ state: draft await waitForCondition(() => startedPaths.length === 2); expect([...startedPaths].sort()).toEqual([ - "/repo/tasks/alpha/one.md", - "/repo/tasks/beta/two.md" + "/repo/tasks/alpha/01-one.md", + "/repo/tasks/beta/01-two.md" ]); - blockedPaths.get("/repo/tasks/alpha/one.md")?.resolve(); - blockedPaths.get("/repo/tasks/beta/two.md")?.resolve(); + blockedPaths.get("/repo/tasks/alpha/01-one.md")?.resolve(); + blockedPaths.get("/repo/tasks/beta/01-two.md")?.resolve(); await Promise.all([alphaUpdate, betaUpdate]); }); diff --git a/packages/task-list/src/backends/markdown-dir.ts b/packages/task-list/src/backends/markdown-dir.ts index c18cc71ca6..fb957e92ab 100644 --- a/packages/task-list/src/backends/markdown-dir.ts +++ b/packages/task-list/src/backends/markdown-dir.ts @@ -5,12 +5,15 @@ import taskSchema from "../schema/task.schema.json" with { type: "json" }; import { eventsFromState, findEvent } from "../state-machine.js"; import { resolveStateMachine } from "../state.js"; import { + AnchorNotFoundError, InvalidTransitionError, MalformedTaskError, + OrderMismatchError, TaskAlreadyExistsError, TaskNotFoundError, type BackendDeps, type ListFilter, + type MoveAnchor, type Task, type TaskCreate, type TaskFireOptions, @@ -20,13 +23,14 @@ import { type TaskUpdate } from "../types.js"; import { + applyOrder, hasErrorCode, isRecord, sortStrings, - sortTasks, statIfExists, validateTaskId, - writeAtomically + writeAtomically, + type OrderedEntry } from "./utils.js"; const ARCHIVE_DIRECTORY_NAME = "archive"; @@ -34,8 +38,11 @@ const MARKDOWN_EXTENSION = ".md"; const TASK_KIND = "task"; const TASK_VERSION = 1; const TASK_SCHEMA_ID = taskSchema.$id; +const ORDER_LOCK_FILENAME = ".order.lock"; +const MIN_PREFIX_WIDTH = 2; const RESERVED_FRONTMATTER_KEYS = new Set([ "$schema", + "created", "description", "kind", "name", @@ -99,8 +106,8 @@ function archiveDirectoryPath(rootPath: string, list: string): string { return path.join(listPath(rootPath, list), ARCHIVE_DIRECTORY_NAME); } -function activeTaskPath(rootPath: string, list: string, id: string): string { - return path.join(listPath(rootPath, list), `${id}${MARKDOWN_EXTENSION}`); +function activeTaskFilename(id: string, order: number, width: number): string { + return `${String(order).padStart(width, "0")}-${id}${MARKDOWN_EXTENSION}`; } function archivedTaskPath(rootPath: string, list: string, id: string): string { @@ -119,6 +126,33 @@ function isLockFile(entryName: string): boolean { return entryName.endsWith(".lock"); } +function isValidTaskIdShape(id: string): boolean { + return id.length > 0 && !id.startsWith(".") && !id.includes("/") && !id.includes("\\") && !id.includes(".."); +} + +function parseActiveFilename(entryName: string): { id: string; order: number | null } | undefined { + if (!isMarkdownFile(entryName)) return undefined; + const stem = entryName.slice(0, -MARKDOWN_EXTENSION.length); + + const match = /^(\d+)-(.+)$/.exec(stem); + if (match) { + const id = match[2]; + if (isValidTaskIdShape(id)) { + return { id, order: Number.parseInt(match[1], 10) }; + } + } + + if (isValidTaskIdShape(stem)) { + return { id: stem, order: null }; + } + + return undefined; +} + +function padWidthForCount(count: number): number { + return Math.max(MIN_PREFIX_WIDTH, String(Math.max(count, 1)).length); +} + function malformedTask(filePath: string, field: string): MalformedTaskError { return new MalformedTaskError(`Malformed task "${filePath}": invalid "${field}".`); } @@ -280,30 +314,42 @@ async function readTaskFile( }; } +async function findActiveTaskFilename( + fs: TaskListFs, + listDirectoryPath: string, + id: string +): Promise { + const entries = await readDirectoryNames(fs, listDirectoryPath); + for (const entryName of entries) { + if (isHiddenEntry(entryName) || isLockFile(entryName)) continue; + const parsed = parseActiveFilename(entryName); + if (parsed?.id === id) { + return entryName; + } + } + return undefined; +} + async function findTaskLocation( fs: TaskListFs, rootPath: string, list: string, id: string ): Promise { - const activePath = activeTaskPath(rootPath, list, id); - const activeStat = await statIfExists(fs, activePath); - - if (activeStat?.isFile()) { - return { - archived: false, - path: activePath - }; + const listDirectoryPath = listPath(rootPath, list); + const activeName = await findActiveTaskFilename(fs, listDirectoryPath, id); + if (activeName) { + const activePath = path.join(listDirectoryPath, activeName); + const activeStat = await statIfExists(fs, activePath); + if (activeStat?.isFile()) { + return { archived: false, path: activePath }; + } } const archivedPath = archivedTaskPath(rootPath, list, id); const archivedStat = await statIfExists(fs, archivedPath); - if (archivedStat?.isFile()) { - return { - archived: true, - path: archivedPath - }; + return { archived: true, path: archivedPath }; } return undefined; @@ -350,6 +396,7 @@ function createdFrontmatter( } } + frontmatter.created = new Date().toISOString(); return frontmatter; } @@ -418,36 +465,111 @@ function assertUpdateDoesNotSetState(patch: TaskUpdate): void { } } +interface ActiveEntry { + id: string; + order: number | null; + filename: string; +} + function createTasksView(deps: BackendDeps, list: string): Tasks { const listDirectoryPath = listPath(deps.path, list); const stateMachine = resolveStateMachine(deps.stateMachine); const validStates = new Set(stateMachine.states); - async function listFiles(directoryPath: string): Promise { - const entries = await readDirectoryNames(deps.fs, directoryPath); - const tasks: Task[] = []; + async function readActiveEntries(): Promise { + const entries = await readDirectoryNames(deps.fs, listDirectoryPath); + const result: ActiveEntry[] = []; for (const entryName of entries) { - if (isHiddenEntry(entryName) || isLockFile(entryName) || !isMarkdownFile(entryName)) { - continue; - } + if (isHiddenEntry(entryName) || isLockFile(entryName)) continue; + const parsed = parseActiveFilename(entryName); + if (!parsed) continue; - const entryPath = path.join(directoryPath, entryName); + const entryPath = path.join(listDirectoryPath, entryName); const entryStat = await statIfExists(deps.fs, entryPath); - if (!entryStat?.isFile()) { - continue; - } + if (!entryStat?.isFile()) continue; + + result.push({ id: parsed.id, order: parsed.order, filename: entryName }); + } + + result.sort((left, right) => { + const leftOrder = left.order ?? Number.POSITIVE_INFINITY; + const rightOrder = right.order ?? Number.POSITIVE_INFINITY; + if (leftOrder !== rightOrder) return leftOrder - rightOrder; + return left.filename.localeCompare(right.filename); + }); + + return result; + } + + async function readActiveTasks(): Promise<{ entries: ActiveEntry[]; tasks: Map }> { + const entries = await readActiveEntries(); + const tasks = new Map(); + + for (const entry of entries) { + const filePath = path.join(listDirectoryPath, entry.filename); + const file = await readTaskFile(deps.fs, list, entry.id, filePath, validStates); + tasks.set(entry.id, { task: file.task, raw: file.frontmatter }); + } + + return { entries, tasks }; + } + + async function readArchivedTasks(): Promise<{ task: Task; raw: TaskRecord }[]> { + const archivePath = archiveDirectoryPath(deps.path, list); + const entries = await readDirectoryNames(deps.fs, archivePath); + const result: { task: Task; raw: TaskRecord }[] = []; + + for (const entryName of entries) { + if (isHiddenEntry(entryName) || isLockFile(entryName) || !isMarkdownFile(entryName)) continue; + + const entryPath = path.join(archivePath, entryName); + const entryStat = await statIfExists(deps.fs, entryPath); + if (!entryStat?.isFile()) continue; const id = entryName.slice(0, -MARKDOWN_EXTENSION.length); - tasks.push((await readTaskFile(deps.fs, list, id, entryPath, validStates)).task); + const file = await readTaskFile(deps.fs, list, id, entryPath, validStates); + result.push({ task: file.task, raw: file.frontmatter }); } - return sortTasks(tasks); + return result.sort((left, right) => left.task.qualifiedId.localeCompare(right.task.qualifiedId)); } - async function withTaskLock(id: string, action: () => Promise): Promise { - validateTaskId(id); - const release = await acquireFileLock(activeTaskPath(deps.path, list, id), { + async function rewriteListPrefixes(orderedIds: readonly string[]): Promise { + const entries = await readActiveEntries(); + const byId = new Map(entries.map((entry) => [entry.id, entry])); + const width = padWidthForCount(orderedIds.length); + + for (let index = 0; index < orderedIds.length; index += 1) { + const id = orderedIds[index]; + const entry = byId.get(id); + if (!entry) continue; + + const desiredFilename = activeTaskFilename(id, index + 1, width); + if (entry.filename !== desiredFilename) { + const fromPath = path.join(listDirectoryPath, entry.filename); + const stagingPath = path.join(listDirectoryPath, `${desiredFilename}.staging-${process.pid}-${index}`); + await deps.fs.rename(fromPath, stagingPath); + entry.filename = path.basename(stagingPath); + } + } + + const refreshed = await readDirectoryNames(deps.fs, listDirectoryPath); + for (const entryName of refreshed) { + const stagingMatch = /\.staging-\d+-\d+$/.exec(entryName); + if (!stagingMatch) continue; + + const desiredName = entryName.slice(0, stagingMatch.index); + await deps.fs.rename( + path.join(listDirectoryPath, entryName), + path.join(listDirectoryPath, desiredName) + ); + } + } + + async function withListLock(action: () => Promise): Promise { + await deps.fs.mkdir(listDirectoryPath, { recursive: true }); + const release = await acquireFileLock(path.join(listDirectoryPath, ORDER_LOCK_FILENAME), { fs: deps.fs, staleMs: deps.lockStaleMs, retries: deps.lockRetries @@ -460,6 +582,11 @@ function createTasksView(deps: BackendDeps, list: string): Tasks { } } + async function withTaskLock(id: string, action: () => Promise): Promise { + validateTaskId(id); + return withListLock(action); + } + async function getTaskFile(id: string): Promise { validateTaskId(id); return readTaskAtLocation(deps.fs, deps.path, list, id, validStates); @@ -484,17 +611,23 @@ function createTasksView(deps: BackendDeps, list: string): Tasks { name: list, stateMachine, async all(filter?: ListFilter): Promise { - const activeTasks = await listFiles(listDirectoryPath); - const archivedTasks = filter?.includeArchived - ? await listFiles(archiveDirectoryPath(deps.path, list)) - : []; - const combinedTasks = [...activeTasks, ...archivedTasks]; - - if (filter?.state) { - return combinedTasks.filter((task) => task.state === filter.state); - } + const { entries: activeEntries, tasks: activeTasks } = await readActiveTasks(); + const archivedEntries = filter?.includeArchived ? await readArchivedTasks() : []; + + const orderedActive: OrderedEntry[] = activeEntries + .map((entry) => activeTasks.get(entry.id)!) + .filter((entry) => { + if (filter?.state && entry.task.state !== filter.state) return false; + return true; + }); + + const filteredArchived = archivedEntries.filter((entry) => { + if (filter?.state && entry.task.state !== filter.state) return false; + return true; + }); - return combinedTasks; + const orderedActiveTasks = applyOrder(orderedActive, filter?.order); + return [...orderedActiveTasks, ...filteredArchived.map((entry) => entry.task)]; }, async get(id: string): Promise { return (await getTaskFile(id)).task; @@ -504,19 +637,28 @@ function createTasksView(deps: BackendDeps, list: string): Tasks { validateTaskId(input.id); await deps.fs.mkdir(listDirectoryPath, { recursive: true }); - return withTaskLock(input.id, async () => { + return withListLock(async () => { const existing = await findTaskLocation(deps.fs, deps.path, list, input.id); if (existing) { throw new TaskAlreadyExistsError(`Task "${list}/${input.id}" already exists.`); } - const targetPath = activeTaskPath(deps.path, list, input.id); + const activeEntries = await readActiveEntries(); + const maxOrder = activeEntries.reduce( + (max, entry) => (entry.order !== null && entry.order > max ? entry.order : max), + 0 + ); + const nextOrder = maxOrder + 1; + const width = padWidthForCount(activeEntries.length + 1); + const filename = activeTaskFilename(input.id, nextOrder, width); + const targetPath = path.join(listDirectoryPath, filename); + const frontmatter = createdFrontmatter(deps.defaults, input, stateMachine.initial); const description = input.description ?? ""; await writeAtomically(deps.fs, targetPath, serializeTaskDocument(frontmatter, description)); - return createTask(list,input.id, frontmatter, description); + return createTask(list, input.id, frontmatter, description); }); }, async update(id: string, patch: TaskUpdate): Promise { @@ -602,12 +744,67 @@ function createTasksView(deps: BackendDeps, list: string): Tasks { await deps.fs.unlink(location.path); }); + }, + async move(id: string, anchor: MoveAnchor): Promise { + validateTaskId(id); + + return withListLock(async () => { + const { entries, tasks } = await readActiveTasks(); + const fromIndex = entries.findIndex((entry) => entry.id === id); + if (fromIndex < 0) { + throw new TaskNotFoundError(`Task "${list}/${id}" not found.`); + } + + const ordered = entries.map((entry) => entry.id); + ordered.splice(fromIndex, 1); + + let insertIndex: number; + if ("position" in anchor) { + insertIndex = anchor.position === "top" ? 0 : ordered.length; + } else { + const anchorId = "before" in anchor ? anchor.before : anchor.after; + const anchorIndex = ordered.indexOf(anchorId); + if (anchorIndex < 0) { + throw new AnchorNotFoundError(anchorId); + } + insertIndex = "before" in anchor ? anchorIndex : anchorIndex + 1; + } + + ordered.splice(insertIndex, 0, id); + await rewriteListPrefixes(ordered); + + return tasks.get(id)!.task; + }); + }, + async reorder(ids: readonly string[]): Promise { + for (const id of ids) { + validateTaskId(id); + } + + return withListLock(async () => { + const { entries, tasks } = await readActiveTasks(); + const currentIds = entries.map((entry) => entry.id); + const currentSet = new Set(currentIds); + const inputSet = new Set(ids); + const missing = currentIds.filter((id) => !inputSet.has(id)); + const extra = ids.filter((id) => !currentSet.has(id)); + + if (missing.length > 0 || extra.length > 0) { + throw new OrderMismatchError({ missing, extra }); + } + + await rewriteListPrefixes(ids); + + return ids.map((id) => tasks.get(id)!.task); + }); } }; } export async function markdownDirBackend(deps: BackendDeps): Promise { await ensureRootPath(deps); + const stateMachine = resolveStateMachine(deps.stateMachine); + const validStates = new Set(stateMachine.states); const list = (name: string): Tasks => { const listName = validateListName(name); @@ -645,7 +842,7 @@ export async function markdownDirBackend(deps: BackendDeps): Promise { tasks.push(...(await list(taskListName).all(filter))); } - return sortTasks(tasks); + return tasks; }; const get = async (qualifiedId: string): Promise => { @@ -653,10 +850,67 @@ export async function markdownDirBackend(deps: BackendDeps): Promise { return list(listName).get(id); }; + const moveBetweenLists = async (qualifiedId: string, targetList: string): Promise => { + const { list: sourceListName, id } = parseQualifiedId(qualifiedId); + const targetListName = validateListName(targetList); + + if (sourceListName === targetListName) { + const file = await readTaskAtLocation(deps.fs, deps.path, sourceListName, id, validStates); + return file.task; + } + + const targetExisting = await findTaskLocation(deps.fs, deps.path, targetListName, id); + if (targetExisting) { + throw new TaskAlreadyExistsError(`Task "${targetListName}/${id}" already exists.`); + } + + const sourceLocation = await findTaskLocation(deps.fs, deps.path, sourceListName, id); + if (!sourceLocation) { + throw new TaskNotFoundError(`Task "${sourceListName}/${id}" not found.`); + } + + const targetListDir = listPath(deps.path, targetListName); + await deps.fs.mkdir(targetListDir, { recursive: true }); + + const targetEntries = await (async () => { + const out: ActiveEntry[] = []; + const names = await readDirectoryNames(deps.fs, targetListDir); + for (const entryName of names) { + if (isHiddenEntry(entryName) || isLockFile(entryName)) continue; + const parsed = parseActiveFilename(entryName); + if (!parsed) continue; + out.push({ id: parsed.id, order: parsed.order, filename: entryName }); + } + return out; + })(); + + if (sourceLocation.archived) { + const archivedTargetDir = archiveDirectoryPath(deps.path, targetListName); + await deps.fs.mkdir(archivedTargetDir, { recursive: true }); + const archivedTargetPath = archivedTaskPath(deps.path, targetListName, id); + await deps.fs.rename(sourceLocation.path, archivedTargetPath); + const file = await readTaskFile(deps.fs, targetListName, id, archivedTargetPath, validStates); + return file.task; + } + + const maxOrder = targetEntries.reduce( + (max, entry) => (entry.order !== null && entry.order > max ? entry.order : max), + 0 + ); + const width = padWidthForCount(targetEntries.length + 1); + const targetFilename = activeTaskFilename(id, maxOrder + 1, width); + const targetPath = path.join(targetListDir, targetFilename); + + await deps.fs.rename(sourceLocation.path, targetPath); + const file = await readTaskFile(deps.fs, targetListName, id, targetPath, validStates); + return file.task; + }; + return { list, lists, allTasks, - get + get, + moveBetweenLists }; } diff --git a/packages/task-list/src/backends/utils.ts b/packages/task-list/src/backends/utils.ts index e163d8c4f2..42defec34b 100644 --- a/packages/task-list/src/backends/utils.ts +++ b/packages/task-list/src/backends/utils.ts @@ -1,5 +1,32 @@ import path from "node:path"; -import type { Task, TaskListFs } from "../types.js"; +import type { ListFilter, Task, TaskListFs } from "../types.js"; + +export interface OrderedEntry { + task: Task; + raw: Record; +} + +export function compareCreated(left: OrderedEntry, right: OrderedEntry): number { + const leftCreated = typeof left.raw.created === "string" ? left.raw.created : ""; + const rightCreated = typeof right.raw.created === "string" ? right.raw.created : ""; + + if (leftCreated === "" && rightCreated === "") { + return left.task.qualifiedId.localeCompare(right.task.qualifiedId); + } + if (leftCreated === "") return 1; + if (rightCreated === "") return -1; + return leftCreated.localeCompare(rightCreated); +} + +export function applyOrder(entries: OrderedEntry[], order: ListFilter["order"]): Task[] { + if (order === "alphabetical") { + return sortTasks(entries.map((entry) => entry.task)); + } + if (order === "created") { + return [...entries].sort(compareCreated).map((entry) => entry.task); + } + return entries.map((entry) => entry.task); +} let tmpFileCounter = 0; diff --git a/packages/task-list/src/backends/yaml-file.ts b/packages/task-list/src/backends/yaml-file.ts index 0dea770610..7881136d98 100644 --- a/packages/task-list/src/backends/yaml-file.ts +++ b/packages/task-list/src/backends/yaml-file.ts @@ -1,16 +1,19 @@ import { acquireFileLock } from "@poe-code/file-lock"; -import { parseDocument } from "yaml"; +import { isMap, parseDocument, type Document, type YAMLMap } from "yaml"; import storeSchema from "../schema/store.schema.json" with { type: "json" }; import taskSchema from "../schema/task.schema.json" with { type: "json" }; import { eventsFromState, findEvent } from "../state-machine.js"; import { resolveStateMachine } from "../state.js"; import { + AnchorNotFoundError, InvalidTransitionError, MalformedTaskError, + OrderMismatchError, TaskAlreadyExistsError, TaskNotFoundError, type BackendDeps, type ListFilter, + type MoveAnchor, type Task, type TaskCreate, type TaskFireOptions, @@ -20,12 +23,13 @@ import { type TaskUpdate } from "../types.js"; import { + applyOrder, isRecord, sortStrings, - sortTasks, statIfExists, validateTaskId, - writeAtomically + writeAtomically, + type OrderedEntry } from "./utils.js"; const STORE_KIND = "task-store"; @@ -34,7 +38,15 @@ const STORE_VERSION = 1; const TASK_KIND = "task"; const TASK_SCHEMA_ID = taskSchema.$id; const TASK_VERSION = 1; -const RESERVED_TASK_KEYS = new Set(["$schema", "description", "kind", "name", "state", "version"]); +const RESERVED_TASK_KEYS = new Set([ + "$schema", + "created", + "description", + "kind", + "name", + "state", + "version" +]); type StoreRecord = Record; type TaskRecord = Record; @@ -144,6 +156,7 @@ function createTaskRecord( } } + taskRecord.created = new Date().toISOString(); return taskRecord; } @@ -367,6 +380,57 @@ function getTaskOrThrow(store: StoreRecord, list: string, id: string): TaskRecor return taskRecord; } +function getListNode(document: Document, list: string): YAMLMap | undefined { + const lists = document.get("lists"); + if (!isMap(lists)) { + return undefined; + } + + const listNode = lists.get(list); + if (!isMap(listNode)) { + return undefined; + } + + return listNode; +} + +function pairKey(pair: { key: unknown }): string | undefined { + const key = pair.key; + if (typeof key === "string") { + return key; + } + if (key && typeof key === "object" && "value" in key && typeof (key as { value: unknown }).value === "string") { + return (key as { value: string }).value; + } + return undefined; +} + +function findItemIndex(listNode: YAMLMap, id: string): number { + return listNode.items.findIndex((pair) => pairKey(pair) === id); +} + +function activeItemIds(listNode: YAMLMap, validStates: ReadonlySet): string[] { + const ids: string[] = []; + for (const pair of listNode.items) { + const id = pairKey(pair); + if (id === undefined) continue; + + const value = pair.value; + let state: unknown; + if (value && typeof value === "object" && "get" in value && typeof (value as { get: unknown }).get === "function") { + state = (value as YAMLMap).get("state"); + } else if (isRecord(value)) { + state = value.state; + } + + if (typeof state === "string" && validStates.has(state) && state !== "archived") { + ids.push(id); + } + } + return ids; +} + + async function ensureStorePath(deps: BackendDeps): Promise { if (!deps.create) { await deps.fs.stat(deps.path); @@ -421,9 +485,14 @@ function createTasksView(deps: BackendDeps, list: string): Tasks { return []; } - const tasks = Object.entries(listRecord).map(([id, taskRecord]) => createTask(list, id, taskRecord as TaskRecord)); + const entries: OrderedEntry[] = Object.entries(listRecord) + .map(([id, taskRecord]) => ({ + task: createTask(list, id, taskRecord as TaskRecord), + raw: taskRecord as TaskRecord + })) + .filter(({ task }) => matchesFilter(task, filter)); - return sortTasks(tasks.filter((task) => matchesFilter(task, filter))); + return applyOrder(entries, filter?.order); } function assertFireableTaskEvent(task: Task, eventName: string) { @@ -563,6 +632,84 @@ function createTasksView(deps: BackendDeps, list: string): Tasks { document.deleteIn(["lists", list, id]); await writeAtomically(deps.fs, deps.path, serializeDocument(document)); }); + }, + async move(id: string, anchor: MoveAnchor): Promise { + validateTaskId(id); + + return withStoreLock(deps, async () => { + const { document, store } = await readStore(deps.fs, deps.path, validStates); + const taskRecord = getTaskOrThrow(store, list, id); + const listNode = getListNode(document, list); + if (!listNode) { + throw new TaskNotFoundError(`Task "${list}/${id}" not found.`); + } + + const fromIndex = findItemIndex(listNode, id); + if (fromIndex < 0) { + throw new TaskNotFoundError(`Task "${list}/${id}" not found.`); + } + + const [movedPair] = listNode.items.splice(fromIndex, 1); + + let insertIndex: number; + if ("position" in anchor) { + insertIndex = anchor.position === "top" ? 0 : listNode.items.length; + } else { + const anchorId = "before" in anchor ? anchor.before : anchor.after; + const anchorIndex = findItemIndex(listNode, anchorId); + if (anchorIndex < 0) { + listNode.items.splice(fromIndex, 0, movedPair); + throw new AnchorNotFoundError(anchorId); + } + insertIndex = "before" in anchor ? anchorIndex : anchorIndex + 1; + } + + listNode.items.splice(insertIndex, 0, movedPair); + await writeAtomically(deps.fs, deps.path, serializeDocument(document)); + + return createTask(list, id, taskRecord); + }); + }, + async reorder(ids: readonly string[]): Promise { + for (const id of ids) { + validateTaskId(id); + } + + return withStoreLock(deps, async () => { + const { document, store } = await readStore(deps.fs, deps.path, validStates); + const listNode = getListNode(document, list); + if (!listNode) { + throw new OrderMismatchError({ missing: [...ids], extra: [] }); + } + + const currentActive = activeItemIds(listNode, validStates); + const currentSet = new Set(currentActive); + const inputSet = new Set(ids); + const missing = currentActive.filter((id) => !inputSet.has(id)); + const extra = ids.filter((id) => !currentSet.has(id)); + + if (missing.length > 0 || extra.length > 0) { + throw new OrderMismatchError({ missing, extra }); + } + + const archivedPairs = listNode.items.filter((pair) => { + const id = pairKey(pair); + return id !== undefined && !currentSet.has(id); + }); + const orderedActive = ids.map((id) => { + const pair = listNode.items.find((p) => pairKey(p) === id); + if (!pair) { + throw new OrderMismatchError({ missing: [id], extra: [] }); + } + return pair; + }); + + listNode.items.splice(0, listNode.items.length, ...orderedActive, ...archivedPairs); + await writeAtomically(deps.fs, deps.path, serializeDocument(document)); + + const tasks = ids.map((id) => createTask(list, id, getTaskOrThrow(store, list, id))); + return tasks; + }); } }; } @@ -584,18 +731,24 @@ export async function yamlFileBackend(deps: BackendDeps): Promise { const allTasks = async (filter?: ListFilter): Promise => { const { store } = await readStore(deps.fs, deps.path, validStates); - const tasks: Task[] = []; + const result: Task[] = []; - for (const [listName, listRecord] of Object.entries(getListsRecord(store))) { - for (const [id, taskRecord] of Object.entries(listRecord as Record)) { - const task = createTask(listName, id, taskRecord as TaskRecord); - if (matchesFilter(task, filter)) { - tasks.push(task); - } - } + const listNames = sortStrings(Object.keys(getListsRecord(store))); + for (const listName of listNames) { + const listRecord = getListsRecord(store)[listName]; + if (!isRecord(listRecord)) continue; + + const entries: OrderedEntry[] = Object.entries(listRecord) + .map(([id, taskRecord]) => ({ + task: createTask(listName, id, taskRecord as TaskRecord), + raw: taskRecord as TaskRecord + })) + .filter(({ task }) => matchesFilter(task, filter)); + + result.push(...applyOrder(entries, filter?.order)); } - return sortTasks(tasks); + return result; }; const get = async (qualifiedId: string): Promise => { @@ -603,10 +756,35 @@ export async function yamlFileBackend(deps: BackendDeps): Promise { return list(listName).get(id); }; + const moveBetweenLists = async (qualifiedId: string, targetList: string): Promise => { + const { list: sourceListName, id } = parseQualifiedId(qualifiedId); + const targetListName = validateListName(targetList); + + return withStoreLock(deps, async () => { + const { document, store } = await readStore(deps.fs, deps.path, validStates); + const taskRecord = getTaskOrThrow(store, sourceListName, id); + + if (sourceListName === targetListName) { + return createTask(targetListName, id, taskRecord); + } + + if (getTaskRecord(store, targetListName, id)) { + throw new TaskAlreadyExistsError(`Task "${targetListName}/${id}" already exists.`); + } + + document.deleteIn(["lists", sourceListName, id]); + document.setIn(["lists", targetListName, id], taskRecord); + await writeAtomically(deps.fs, deps.path, serializeDocument(document)); + + return createTask(targetListName, id, taskRecord); + }); + }; + return { list, lists, allTasks, - get + get, + moveBetweenLists }; } diff --git a/packages/task-list/src/index.ts b/packages/task-list/src/index.ts index 41171a3768..44357bab1c 100644 --- a/packages/task-list/src/index.ts +++ b/packages/task-list/src/index.ts @@ -8,11 +8,14 @@ export { type StateMachineDef } from "./state-machine.js"; export { + AnchorNotFoundError, InvalidTransitionError, MalformedTaskError, + OrderMismatchError, TaskAlreadyExistsError, TaskNotFoundError, type ListFilter, + type MoveAnchor, type OpenTaskListOptions, type Task, type TaskCreate, @@ -20,6 +23,7 @@ export { type TaskFireOptions, type TaskList, type TaskListFs, + type TaskOrder, type TaskState, type Tasks, type TaskUpdate diff --git a/packages/task-list/src/types.ts b/packages/task-list/src/types.ts index 062a42a7ad..3d45315133 100644 --- a/packages/task-list/src/types.ts +++ b/packages/task-list/src/types.ts @@ -30,11 +30,19 @@ export interface TaskFireOptions { metadataPatch?: Record; } +export type TaskOrder = "priority" | "alphabetical" | "created"; + export interface ListFilter { state?: string; includeArchived?: boolean; + order?: TaskOrder; } +export type MoveAnchor = + | { before: string } + | { after: string } + | { position: "top" | "bottom" }; + export interface Tasks { readonly name: string; readonly stateMachine: StateMachineDef; @@ -46,6 +54,8 @@ export interface Tasks { canFire(id: string, event: string): Promise; events(id: string): Promise; delete(id: string): Promise; + move(id: string, anchor: MoveAnchor): Promise; + reorder(ids: readonly string[]): Promise; } export interface TaskList { @@ -53,6 +63,7 @@ export interface TaskList { lists(): Promise; allTasks(filter?: ListFilter): Promise; get(qualifiedId: string): Promise; + moveBetweenLists(qualifiedId: string, targetList: string): Promise; } export interface TaskDefaults { @@ -159,3 +170,32 @@ export class MalformedTaskError extends Error { this.name = "MalformedTaskError"; } } + +export class OrderMismatchError extends Error { + readonly missing: readonly string[]; + readonly extra: readonly string[]; + + constructor(options: { missing: readonly string[]; extra: readonly string[] }) { + const parts: string[] = []; + if (options.missing.length > 0) { + parts.push(`missing ${options.missing.map((id) => `"${id}"`).join(", ")}`); + } + if (options.extra.length > 0) { + parts.push(`extra ${options.extra.map((id) => `"${id}"`).join(", ")}`); + } + super(`reorder requires the exact set of active task ids: ${parts.join("; ")}.`); + this.name = "OrderMismatchError"; + this.missing = options.missing; + this.extra = options.extra; + } +} + +export class AnchorNotFoundError extends Error { + readonly anchor: string; + + constructor(anchor: string) { + super(`Anchor task "${anchor}" not found.`); + this.name = "AnchorNotFoundError"; + this.anchor = anchor; + } +} From 61b48170bcf6b56ab5c6e59d3ae28bf90c24c90a Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 07:59:04 -0400 Subject: [PATCH 002/111] docs(skill-plan): keep open questions in chat, never in the plan doc Restates the chat-vs-document split: per-level summaries, numbered decisions, open questions, confirmation asks all belong in chat. Drops the inline `- Open question:` convention and the "Open questions" sub-bullet from level 3. --- src/templates/plan/SKILL_plan.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/templates/plan/SKILL_plan.md b/src/templates/plan/SKILL_plan.md index 95409650ff..46a3b2ea03 100644 --- a/src/templates/plan/SKILL_plan.md +++ b/src/templates/plan/SKILL_plan.md @@ -23,7 +23,9 @@ version: 1 ## Chat vs document -Document = artifact. Chat = conversation. Per-level summaries, numbered decisions, and confirmation asks go in chat. Document holds plan content only: level headings, signatures, file lists, inline `- Open question:` notes. +Document = artifact. Chat = conversation. The document holds plan content only: level headings, signatures, file lists, decisions you've made. **Everything that needs the user's input — per-level summaries, numbered decisions, open questions, confirmation asks — goes in chat, never in the document.** A plan doc is what you'd hand to an executor; questions to the human do not belong in it. + +When the user resolves a question in chat, fold the answer into the relevant section of the doc. Do not record the resolution as a separate note. ## Ground rules @@ -31,6 +33,7 @@ Document = artifact. Chat = conversation. Per-level summaries, numbered decision 2. **Be concrete.** Real files, real functions, real types — no hand-waving. 3. **Summarize after each level — in chat.** Decisions made, what's open, what changed earlier. 4. **Numbered decisions when you need input — in chat.** One per line, options + your recommendation. +5. **No open questions in the doc.** If you don't know it yet, ask in chat. Don't seed `- Open question:` bullets, don't carve out an "Open questions" section. ## The Five Levels @@ -52,7 +55,6 @@ Concrete end state. This is the most important to get right. For example, practi - Architecture — where the code lives, what it touches. - Edge cases — technical and product. - Flags, env vars, config — and which are default-on. -- Open questions. ### 4. Interfaces and test plan @@ -76,7 +78,7 @@ Contracts + validation, aimed at autonomous execution. - One level at a time. Pause for confirmation before the next. - "just wing it" / "skip ahead" → draft the rest in one pass. - Earlier level changes (e.g. UX sharpens the problem) → rewrite it. -- Open questions inline: `- Open question: ...` +- Open questions go in chat, not in the doc. Once resolved, fold the answer into the relevant section. ## Output Format From 11c0a2d3d7e5777be6148d281c18e4ed59d3cd5a Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 07:59:17 -0400 Subject: [PATCH 003/111] chore(plans): convert agent-human-in-loop to ralph harness doc Switches the plan to the ralph schema and seeds the harness status block so the document is runnable as a ralph harness pair. --- docs/plans/agent-human-in-loop.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/plans/agent-human-in-loop.md b/docs/plans/agent-human-in-loop.md index b9b50a0e90..3e23d340ca 100644 --- a/docs/plans/agent-human-in-loop.md +++ b/docs/plans/agent-human-in-loop.md @@ -1,7 +1,10 @@ --- -$schema: https://poe-platform.github.io/poe-code/schemas/plans/plan.schema.json -kind: plan +$schema: https://poe-platform.github.io/poe-code/schemas/plans/ralph.schema.json +kind: ralph version: 1 +status: + state: in_progress + iteration: 0 --- # agent-human-in-loop From 1207e11816114cbeb763ec9099be6a1fd21605ef Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 07:59:30 -0400 Subject: [PATCH 004/111] docs(plans): add agent-harness, braintrust, and e2b plans - agent-harness: generic runner for agent-script harness pairs. - braintrust-integration: pipeline plan for tracing via Braintrust. - e2b-integration: pipeline plan for sandboxed execution via e2b. --- docs/plans/agent-harness.md | 133 +++ docs/plans/braintrust-integration.md | 628 ++++++++++++ docs/plans/e2b-integration.md | 1351 ++++++++++++++++++++++++++ 3 files changed, 2112 insertions(+) create mode 100644 docs/plans/agent-harness.md create mode 100644 docs/plans/braintrust-integration.md create mode 100644 docs/plans/e2b-integration.md diff --git a/docs/plans/agent-harness.md b/docs/plans/agent-harness.md new file mode 100644 index 0000000000..7f1fc44a26 --- /dev/null +++ b/docs/plans/agent-harness.md @@ -0,0 +1,133 @@ +--- +$schema: https://poe-platform.github.io/poe-code/schemas/plans/plan.schema.json +kind: plan +version: 1 +--- + +# agent-harness + +A generic runner for agent-script-based harnesses, paired with co-located markdown documents that supply prompts and config. + +## 1. What we're building + +A new package, `@poe-code/agent-harness`, that runs a **harness pair**: + +- `.ajs` — orchestration script (agent-script source, the program the runtime executes) +- `.md` — complementary markdown document with YAML frontmatter (prompts, agent config, status, research brief) + +The `.ajs` is the orchestrator; the `.md` is data the orchestrator reads. The runtime pairs them by filename, lints + executes the `.ajs`, and exposes the markdown's frontmatter and body to the script via the `harness` module (or an extension of it). + +This package replaces the bespoke runtimes in `@poe-code/experiment-loop`, `@poe-code/ralph`, `@poe-code/pipeline`, and `@poe-code/superintendent`. Each becomes a harness pair shipped as a built-in template, not a hand-written TypeScript loop. + +Non-goals: + +- Not a new language. Reuses `agent-script` parser/linter/runtime as-is. +- Not a replacement for `agent-harness-tools` runtime helpers (lock, hooks, run-logs, select-agent). Those keep their place; agent-harness uses them for cross-cutting concerns. +- Not removing the existing CLI commands' UX surface (`experiment run`, `ralph run`, ...). The CLI wrappers stay; their internals call the harness runner instead of the bespoke loop. +- No regex-based markdown parsing or templating system invented here — uses the existing `agent-script` loader. + +## 2. User-facing shape + +A harness is a pair of files with the same basename, in the same directory: + +```text +.poe-code/harnesses/ralph/ + ralph.ajs # orchestrator + ralph.md # plan / prompt / frontmatter (the document being run) +``` + +### The `.ajs` orchestrator + +ESM-shaped. One required default export (the entry), one optional named export (the frontmatter schema). No top-level `return`. No manual cancellation handling — the interpreter aborts between host calls, the snapshot scheduler persists progress, `restore()` resumes. + +```js +import { S } from "schema"; +import { spawn } from "agent"; +import { event } from "log"; + +export const schema = S.Object({ + iterations: S.Optional(S.Number({ minimum: 1, default: 3 })), + agent: S.Optional(S.String({ default: "claude-code" })), + status: S.Object({ + state: S.Enum(["open", "in_progress", "completed", "failed"] as const), + iteration: S.Number({ minimum: 0 }), + }), +}); + +export default async (frontmatter) => { + const { kind, filename, body } = import.meta; + + for (let i = frontmatter.status.iteration; i < frontmatter.iterations; i++) { + const r = await spawn({ agent: frontmatter.agent, prompt: body }); + event("iteration.completed", { kind, file: filename, i, summary: r.summary }); + } +}; +``` + +Contract: + +- `export default` — required, must be an async arrow. Receives the validated frontmatter as its single argument. Its return value is the harness result. +- `export const schema` — optional. If present, the loader evaluates it against `toolcraft-schema` builders and validates the `.md` frontmatter before invoking the entry. If absent, the entry receives the raw frontmatter map. +- `import.meta` — exposes `{ kind, version, filename, dirname, body }` of the **paired `.md`**, matching Node's ESM `import.meta` extensions. `body` is the markdown content below the YAML header. + +### The `.md` plan + +Plain markdown with YAML frontmatter. The frontmatter conforms to whatever `export const schema` declares; the body is free-form prose the orchestrator can use as the prompt. + +```markdown +--- +$schema: https://poe-platform.github.io/poe-code/schemas/harnesses/ralph.schema.json +kind: ralph +version: 1 +agent: claude-code +iterations: 3 +status: + state: open + iteration: 0 +--- +# Refactor the auth module + +Split the monolithic auth.ts into separate files for session management, +token validation, and middleware. Keep all existing tests passing. +``` + +### CLI + +```bash +# run a harness pair +poe-code harness run .poe-code/harnesses/ralph/ralph.md + +# discover-and-run from .poe-code/harnesses/ +poe-code harness run + +# scaffold a new harness pair +poe-code harness new my-loop + +# list installed harnesses +poe-code harness list +``` + +The runner pairs `.md` ↔ `.ajs` by basename in the same directory, lints the `.ajs`, validates the `.md` frontmatter against the extracted schema, then executes the entry. + +### Built-in harnesses + +`@poe-code/agent-harness` ships these as templates that `harness new ` scaffolds: + +- `ralph` — iterative single-agent loop +- `experiment` — measure, mutate, keep-or-revert via git +- `pipeline` — sequenced tasks with builder/reviewer roles +- `superintendent` — builder + parallel inspectors + judge + owner + +Each is one `.ajs` + one `.md`. The existing `experiment run` / `ralph run` / etc. CLI commands keep their UX surface but delegate to the harness runner internally. + +## 3. Implementation details and technical decisions + +To be drafted next. + +## 4. Interfaces and test plan + +To be drafted next. + +## 5. Code plan + +To be drafted next. diff --git a/docs/plans/braintrust-integration.md b/docs/plans/braintrust-integration.md new file mode 100644 index 0000000000..c2688ca849 --- /dev/null +++ b/docs/plans/braintrust-integration.md @@ -0,0 +1,628 @@ +--- +$schema: https://poe-platform.github.io/poe-code/schemas/plans/pipeline.schema.json +kind: pipeline +version: 1 + +tasks: + - id: add-config-scope + title: Add integrations.braintrust scope to poe-code-config + prompt: | + In packages/poe-code-config/src/schema.ts, register a new scope named + "integrations" using the existing `defineScope(...)` helper. Under it + add a single key `braintrust` shaped as: + + enabled: boolean (default false) + apiKey: string (optional) + apiUrl: string (optional) + project: string (optional) + + Wire the new scope into the same place every other scope is exported + from this package's index. Update any union/registry types so the new + block type-checks. Add unit tests under packages/poe-code-config/src + that verify: a config with no `integrations` block parses; a config + with `enabled: false` parses without apiKey/project; a config with + `enabled: true` parses (cross-field validation lives elsewhere). + Use memfs for any disk reads. No env interpolation logic in this task + — that already lives in the config layer. + + status: + implement: open + + - id: create-braintrust-package + title: Create @poe-code/braintrust workspace package skeleton + prompt: | + Create a new private workspace package at packages/braintrust. + + Files: + package.json — name "@poe-code/braintrust", "private": true, + "type": "module", peerDependencies: { "braintrust": "*" }, + peerDependenciesMeta: { "braintrust": { "optional": true } }. + dependencies: workspace pointers to "@poe-code/agent-spawn", + "@poe-code/pipeline", "@poe-code/superintendent", + "@poe-code/experiment-loop", "@poe-code/poe-code-config". + devDependencies: vitest matching the workspace version. + tsconfig.json — extend the workspace base tsconfig used by other + packages (copy from a sibling like packages/file-lock). + src/index.ts — empty for now (export {}). + README.md — one-line stub; full content lands in a later task. + + Add the new package to root package.json workspaces (it should be + picked up automatically by the existing pattern, verify). Run + `npm install` at the repo root and confirm the workspace resolves. + Do not write any feature code yet. + + status: + implement: open + + - id: impl-redact + title: Implement redact() + prompt: | + In packages/braintrust/src/redact.ts implement and export: + + export function redact(value: unknown): unknown; + + Rules: + - If value is a string and its UTF-8 byte length exceeds 65536, + return "[truncated:]". + - If value is a Buffer/Uint8Array containing a 0x00 byte in the + first 1024 bytes, return "[binary:]". + - Otherwise recurse into objects and arrays (returning new + structures) applying the same rules to leaves. + - If the JSON-serialised size of the entire value exceeds 262144, + replace the whole value with "[truncated:]". + Compute the byte length once at the top, do not double-walk. + + TDD: write tests in packages/braintrust/src/redact.test.ts first + covering each rule and a nested-structure case where unaffected + leaves are preserved. No filesystem touched. + + status: + implement: open + + - id: impl-client + title: Implement BraintrustClient wrapper + prompt: | + In packages/braintrust/src/client.ts implement a thin wrapper around + the Braintrust SDK. Public exports: + + export interface BraintrustClient { + getRootLogger(): Promise; // SDK Logger + getExperiment(name: string): Promise; // SDK Experiment + flush(timeoutMs: number): Promise; + recordError(err: unknown, ctx: string): void; + status(): { lastError: string | null; errorCount: number; + project: string }; + } + export function createClient(opts: { + apiKey: string; apiUrl?: string; project: string; + }): BraintrustClient; + + Behaviour: + - The SDK is loaded via `await import("braintrust")` lazily on + first use. Cache the loaded module on the client instance. + - `getRootLogger` calls SDK `initLogger({ projectName, apiKey, + apiUrl })` once and caches the result. + - `getExperiment(name)` calls `initExperiment({ projectName, + experimentName: name, apiKey, apiUrl })` once per name and + caches by name. + - `flush(timeoutMs)` calls `Promise.race` between the SDK's + `flush()` (across logger and all cached experiments) and a + timeout that resolves silently. + - `recordError` updates internal state used by `status()`. Never + throws. + - All SDK calls are wrapped in try/catch; errors call + `recordError` and are swallowed. The orchestrator never sees + a Braintrust failure. + + TDD: tests in client.test.ts using vi.mock("braintrust", ...) to + stub initLogger/initExperiment/flush. Cover: lazy import only on + first use, caching, flush timeout, error recording, status output. + + status: + implement: open + + - id: impl-trace-run + title: Implement traceRun() + prompt: | + In packages/braintrust/src/trace-run.ts implement and export: + + export type TraceSurface = + "pipeline" | "superintendent" | "experiment" | "spawn"; + + export function makeTraceRun(client: BraintrustClient): ( + surface: TraceSurface, + name: string, + fn: () => Promise + ) => Promise; + + Behaviour: + - Resolves the SDK's `traced` function via the client's lazy + import path (don't statically import braintrust). + - Calls `traced(fn, { name: ":", type: "task" })` + and returns its promise. + - On any setup failure (SDK missing, init error), records via + client.recordError and falls back to running `fn()` directly + so the orchestrator runs to completion. + - Adds a tag `surface:` to the root span when the SDK + API allows tags on `traced` (verify against the SDK; if not, + set the tag via `currentSpan().log({ tags: ... })` inside the + wrapper). + + TDD: tests in trace-run.test.ts with mocked SDK confirming the + span name, type, surface tag, and error fallback path. + + status: + implement: open + + - id: impl-span-builder + title: Implement logSpawnSession() + prompt: | + In packages/braintrust/src/span-builder.ts implement: + + export async function logSpawnSession( + client: BraintrustClient, + ctx: SpawnContext + ): Promise; + + `SpawnContext` is imported from "@poe-code/agent-spawn". + + Behaviour: + - Lazy-import braintrust to get `currentSpan`. + - Open an agent span as a child of `currentSpan()` (which the + spawn middleware will arrange — see adapters task). The span: + name: `agent:${ctx.agent}:${ctx.model ?? "?"}` + type: "task" + - Walk ctx.events (AcpEvent[]) and emit child spans for tool + calls: each ToolCall opens a span with type "tool", name + `tool_call:${tc.kind ?? "unknown"}`, input from tc.input, + output assembled from matching ToolCallUpdate events. + - On the agent span call .log with: + input: { prompt: ctx.prompt, mode: ctx.mode, cwd: ctx.cwd } + output: + metadata: { sessionId: ctx.sessionId, threadId: ctx.threadId } + metrics: { prompt_tokens, completion_tokens, tokens, + prompt_cached_tokens, prompt_cache_creation_tokens, + durationMs } + — pull from ctx.usage; missing fields omitted, not zeroed. + - All inputs/outputs go through redact() before .log(). + - On exception while building, call client.recordError and + return; never throw. + + TDD: tests in span-builder.test.ts using a fixture event sequence + (text + tool_call + tool_call_update + agent_message_chunk). + Assert the order of startSpan/log/end calls and that token counts + land in `metrics` under canonical keys. + + status: + implement: open + + - id: impl-row-builder + title: Implement orchestrator span/row helpers + prompt: | + In packages/braintrust/src/row-builder.ts implement helpers that + open child spans on currentSpan() for orchestrator events. All + helpers swallow errors via client.recordError. + + // Pipeline — opens a span on onTaskStart, logs on onTaskComplete. + export function makePipelineRowState(client: BraintrustClient): { + start(progress: TaskProgress): void; + complete(progress: TaskCompletion): void; + }; + + // Superintendent — one helper per role pair. + export function logSuperintendentRole( + client: BraintrustClient, + role: "builder" | "inspector" | "superintendent" | "owner", + result: unknown // BuilderResult | InspectorResult | ... + ): Promise; + + // Experiment-loop — opens an iteration span on the experiment + // (so it is also a row), populated across multiple callbacks. + export function makeExperimentIterationState( + client: BraintrustClient, + experimentName: string + ): { + start(index: number, agent: string): Promise; + baseline(b: Record): void; + metric(name: string, value: number): void; + commit(hash: string): void; + reset(hash: string): void; + complete(index: number, entry: JournalEntry): Promise; + }; + + Span shapes per docs/plans contract: + - Pipeline step span: type "task", name `step::`, + input { step_name, step_prompt, plan_section }, output + { result_summary, files_changed, success }, scores + { passed: success ? 1 : 0 }, metrics with usage + durationMs + from TaskCompletion. + - Superintendent role span: type "task", name `role:`, + input/output from result. For inspector: scores + { satisfied: 0|1 } from the verdict. + - Experiment iteration span: opened via + `experiment.startSpan({ name: "iteration:", type: "task" })`, + input { brief, baseline, agent, iteration }, output + { diff_summary, kept }, scores including `delta` vs baseline. + + Import only types from @poe-code/pipeline, @poe-code/superintendent, + @poe-code/experiment-loop. Never call into them at runtime. + All inputs/outputs go through redact(). + + TDD: tests in row-builder.test.ts asserting the payload passed to + span.log for each surface. + + status: + implement: open + + - id: impl-spawn-adapter + title: Implement spawn AcpMiddleware adapter + prompt: | + In packages/braintrust/src/adapters/spawn.ts implement and export: + + export function createSpawnMiddleware( + client: BraintrustClient + ): AcpMiddleware; + + `AcpMiddleware` comes from "@poe-code/agent-spawn". + + Behaviour: + - Run `await next()` first so the spawn completes and ctx.events + / ctx.usage / ctx.sessionResult are populated. + - Wrap the call in try/finally; in finally call + `await logSpawnSession(client, ctx)`. + - If `next()` threw, still log: pass an `aborted: true` flag + through metadata so logSpawnSession can mark the span as + aborted. Re-throw the original error after logging — middleware + must not swallow orchestrator errors. + + TDD: tests in adapters/spawn.test.ts using a stub SpawnContext and + a mocked logSpawnSession. Cover: happy path; next() throws (logs + then re-throws); SDK throws inside log (swallowed via client). + + status: + implement: open + + - id: impl-orchestrator-adapters + title: Implement pipeline, experiment, and superintendent callback adapters + prompt: | + In packages/braintrust/src/adapters/ create one file per surface: + + pipeline.ts — exports + createPipelineCallbacks(client): PipelineCallbackFields + where PipelineCallbackFields = Pick. + Wires onTaskStart/onTaskComplete to makePipelineRowState from + row-builder.ts. The other two callbacks are no-ops in v1 + (return them anyway so the merge helper can chain them). + + experiment.ts — exports + createExperimentCallbacks(client, experimentName): + ExperimentCallbackFields + where ExperimentCallbackFields = Pick. + Threads makeExperimentIterationState across the lifecycle. + The experimentName argument is the name used by initExperiment; + the bootstrap derives it from the experiment doc filename. + + superintendent.ts — exports + createSuperintendentCallbacks(client): LoopCallbacks + (LoopCallbacks from "@poe-code/superintendent"). + Each onXxxComplete fires logSuperintendentRole. onXxxFailed + logs a span with metadata.error and scores { passed: 0 }. + + No core package signature changes. Import only types from the + three core packages. Inputs/outputs already redacted by the + row-builder helpers. + + TDD: one test file per adapter. For each, assert the right + span/row helper is called with the right arguments for each + callback the surface exposes. + + status: + implement: open + + - id: impl-merge-callbacks + title: Implement mergeCallbacks helpers (CLI side) + prompt: | + Add a small new module that lives next to the CLI bootstrap + (recommend packages/poe-code-config/src/merge-callbacks.ts so it + can be reused from any subcommand without a new package). + + Export three helpers: + + mergePipelineCallbacks( + user: PipelineCallbackFields | undefined, + added: PipelineCallbackFields | undefined + ): PipelineCallbackFields | undefined; + + mergeExperimentCallbacks(...): ExperimentCallbackFields | undefined; + mergeLoopCallbacks( + user: LoopCallbacks | undefined, + added: LoopCallbacks | undefined + ): LoopCallbacks | undefined; + + Behaviour for every callback key present in either side: + - User callback runs first; if it throws, propagate + (their semantics must not change). + - Added callback runs second; if it throws, swallow and + console.warn once with the callback name. + - If only one side has the callback, use it directly. + + Type imports only from the relevant packages. No runtime + dependency on @poe-code/braintrust. + + TDD: tests cover ordering, user-error propagation, added-error + swallowed, asymmetric (only-user / only-added) cases. + + status: + implement: open + + - id: impl-bootstrap + title: Implement @poe-code/braintrust bootstrap() + prompt: | + In packages/braintrust/src/index.ts implement and export the + single public entry: + + export interface Integrations { + spawnMiddleware?: AcpMiddleware; + pipelineCallbacks?: PipelineCallbackFields; + experimentCallbacks?: ExperimentCallbackFields; + superintendentCallbacks?: LoopCallbacks; + traceRun( + surface: TraceSurface, + name: string, + fn: () => Promise + ): Promise; + shutdown(): Promise; + } + + export async function bootstrap( + config: PoeCodeConfig + ): Promise; + + Behaviour: + - If `config.integrations?.braintrust?.enabled !== true`, + return null. Do not import the SDK. + - Otherwise validate cross-field requirements: `apiKey` and + `project` must be present and non-empty. If not, throw with + a one-line message naming the missing field. + - Probe `await import("braintrust")`. If it throws + ERR_MODULE_NOT_FOUND, throw with exactly: + "Braintrust integration is enabled but the 'braintrust' + package is not installed. Run: npm i braintrust" + - Create a BraintrustClient via createClient(config.integrations + .braintrust). Wire all four adapters and traceRun off the + same client. + - shutdown() calls client.flush(5000). + + TDD: tests in bootstrap.test.ts using vi.mock("braintrust") to + simulate (a) module-not-found, (b) module present and healthy. + Cover: disabled config returns null without import; enabled + missing apiKey throws expected message; enabled missing peer + throws expected message; enabled + valid returns Integrations + with all four callback fields populated. + + status: + implement: open + test: open + + - id: wire-cli-integrations + title: Wire loadIntegrations into pipeline / experiment / superintendent / spawn CLI entries + prompt: | + In each of these CLI entry points: + packages/pipeline/src/run/pipeline.ts (or its CLI wrapper) + packages/experiment-loop/src/run/* (or its CLI wrapper) + packages/superintendent/src/runtime/run-superintendent.ts (or its + CLI wrapper) + packages/agent-spawn/src/spawn-acp.ts (or wherever spawnStreaming + is invoked from CLI) + + Add a small CLI-side helper file that does: + + export async function loadIntegrations( + config: PoeCodeConfig + ): Promise { + if (!config.integrations?.braintrust?.enabled) return null; + const mod = await import("@poe-code/braintrust"); + return mod.bootstrap(config); + } + + Place it where the CLI bootstrap currently composes options + (look for the existing place that loads config). It is the only + module in the codebase with a static reference to + "@poe-code/braintrust" — and it accesses it via dynamic import, + so the package isn't loaded when disabled. + + For each subcommand entry: + 1. Call loadIntegrations(config) once at start. + 2. Wrap the existing run call in + `integrations?.traceRun(surface, name, () => existingRun(opts)) + ?? existingRun(opts)`. + 3. Merge integrations.Callbacks into the user-supplied + callbacks via the merge helpers from impl-merge-callbacks. + 4. Add `integrations?.shutdown()` to the process-exit / SIGINT + path. Use the existing shutdown hook surface; do not roll a + new one. + + Pass the spawn middleware into the agent-spawn middleware chain + where existing middlewares are registered (see + packages/agent-spawn/src/acp/middlewares/). + + TDD: integration tests verifying that with enabled config the + run produces the expected callback chain order (added after user) + and that disabled config skips the dynamic import (mock + `loadIntegrations` and assert it returns null without touching + "@poe-code/braintrust"). + + status: + implement: open + test: open + + - id: impl-status-subcommand + title: Add `poe-code braintrust status` subcommand + prompt: | + Add a top-level CLI subcommand `poe-code braintrust` with a + `status` action. Follow the existing CLI command registration + pattern used by other subcommands (search for `defineCommand`, + `registerCommand`, or equivalent in the CLI package). + + Behaviour of `poe-code braintrust status`: + - Loads config via the existing loader. + - If integrations.braintrust is absent or enabled is false, + prints `disabled`. + - If enabled but unconfigured (missing apiKey/project) prints + one line per missing field. + - If enabled and the `braintrust` peer is not installed prints + `not installed: run npm i braintrust`. + - If enabled and configured, calls bootstrap(config), then + prints: `enabled, project=, last error: , + errors: `. Calls shutdown() before exiting. + + Use the existing design-system primitives for output (do not + `console.log` raw — match the style of other CLI commands). + + TDD: command-level tests using the same harness other CLI tests + use; mock @poe-code/braintrust where needed. + + status: + implement: open + test: open + + - id: integration-test-subagent-tree + title: End-to-end subagent tree test against mocked SDK + prompt: | + Add packages/braintrust/src/integration.test.ts that drives a + fake pipeline run through the real bootstrap + adapters with a + vi.mock("braintrust") stub that records every startSpan call + with its parent. + + The test should: + 1. Build a config with integrations.braintrust.enabled=true. + 2. Call bootstrap(config) to get Integrations. + 3. Run integrations.traceRun("pipeline", "demo", async () => { + // simulate two task starts/completes via the merged + // pipelineCallbacks; each onTaskStart fires the spawn + // middleware against a stub SpawnContext with two tool + // call events. + }); + 4. Assert the recorded span tree: + pipeline:demo (type=task, surface:pipeline tag) + ├── step::0 (type=task) + │ └── agent:: (type=task) + │ ├── tool_call: (type=tool) + │ └── tool_call: (type=tool) + └── step::1 + └── agent:: + └── tool_call: + + Also assert that token counts on the agent span land in `metrics` + under canonical keys (prompt_tokens, completion_tokens, tokens). + + No real network calls. No real braintrust SDK loaded. Use memfs + if any filesystem reads are required. + + status: + implement: open + + - id: write-qa-plan + title: Write QA markdown plan + prompt: | + Create docs/plans/qa/braintrust-integration.md as a numbered + markdown checklist for a human (or agent) to execute against a + real Braintrust workspace. + + Steps to include: + 1. `npm i braintrust` in the test workspace. + 2. Set env: BRAINTRUST_API_KEY=... + 3. Write a poe-code.config.json fragment with + integrations.braintrust = { enabled: true, + apiKey: "${BRAINTRUST_API_KEY}", project: "poe-code-qa" }. + 4. Run `npm run dev -- spawn --agent claude-code --prompt "say hi"` + — verify a single agent span with tool-call children appears + in the project's logs view. + 5. Run `npm run dev -- pipeline run ` — verify root + pipeline span with one child span per step, each containing a + subagent span and tool calls. Verify token usage appears as + numeric metrics (sortable column), not as text in metadata. + 6. Run `npm run dev -- experiment run ` — verify + one root span per run, one iteration child each, AND a row + per iteration in the Braintrust experiments view (including + discarded iterations with kept=false). + 7. Run `npm run dev -- superintendent run ` — verify + root → round → role → agent → tool nesting. + 8. Run with `enabled: true` but BRAINTRUST_API_KEY unset — expect + the bootstrap error "missing apiKey". + 9. Run with `enabled: true` but braintrust not installed — expect + "Run: npm i braintrust". + 10. Run with `enabled: false` — verify no Braintrust traffic + (e.g. set apiUrl to an unreachable host; the run still + completes). + 11. Run `poe-code braintrust status` in each of the three states + (disabled, enabled-unconfigured, enabled-healthy) — verify + the expected output. + + Do not script this. It is a markdown plan, executed by a human or + agent. + + status: + implement: open + + - id: write-package-readme + title: Write packages/braintrust/README.md + prompt: | + Replace the stub README at packages/braintrust/README.md with + the full per-CLAUDE.md content for a poe-code package. + + Sections required: + - Title: `@poe-code/braintrust` + - One-paragraph summary of what it does. + - Setup: `npm i braintrust` (peer dep). + - Configuration: the integrations.braintrust block, every key + documented with type and meaning. + - Environment variables exposed: BRAINTRUST_API_KEY (consumed + via config interpolation; not read directly). + - What lands in Braintrust: a condensed version of the span tree + diagrams from the design — pipeline, superintendent, + experiment-loop, standalone spawn. + - Failure modes: missing peer, missing apiKey, network errors. + - Pointer to `poe-code braintrust status`. + + Do not edit the root README. + + status: + implement: open +--- + +## Context + +Optional Braintrust observability for poe-code's four agent-running +surfaces (spawn / pipeline / superintendent / experiment-loop). Activates +via `integrations.braintrust.{enabled,apiKey,project}` in poe-code config. +Single Braintrust project for everything; surfaces separated by tags +inside the project. Spawned agents render as **subagent** child spans +under the orchestrator that launched them — one span tree per outermost +run, propagated via the SDK's `currentSpan()` async-context. + +Token usage and durations live in `metrics` under Braintrust's canonical +keys (`prompt_tokens`, `completion_tokens`, `tokens`, +`prompt_cached_tokens`, `prompt_cache_creation_tokens`); only IDs go in +`metadata`. Span types are lowercase strings — `"task"` for orchestrator +/ step / role / agent / iteration, `"tool"` for ACP tool calls. We do +not synthesise `"llm"` spans in v1; ACP doesn't expose raw model-call +boundaries. + +The new package `@poe-code/braintrust` is private (not published). The +Braintrust SDK is an optional peer dep — users who don't enable the +integration download nothing extra. The package is dynamically imported +only when config opts in. + +Experiment-loop additionally writes one row per iteration to a Braintrust +**experiment** (the only surface where Braintrust experiments are a real +fit, because iterations have a metric vs. baseline). The iteration span +opened on the experiment doubles as the experiment row. + +Build order matters: schema → package skeleton → leaf utilities (redact, +client, trace-run) → builders → adapters → bootstrap → CLI wiring → +status subcommand → integration test → docs. diff --git a/docs/plans/e2b-integration.md b/docs/plans/e2b-integration.md new file mode 100644 index 0000000000..dc72e92426 --- /dev/null +++ b/docs/plans/e2b-integration.md @@ -0,0 +1,1351 @@ +--- +$schema: https://poe-platform.github.io/poe-code/schemas/plans/pipeline.schema.json +kind: pipeline +version: 1 + +tasks: + - id: config-runtime-scope + title: Add runtime config scope to poe-code-config + prompt: | + In packages/poe-code-config, add `src/runtime.ts` defining a discriminated + union `RuntimeConfig = HostRuntime | DockerRuntime | E2bRuntime` keyed by + `type: "host" | "docker" | "e2b"`. Shared fields: `build_args`, `mounts` + (`{ source, target, readonly? }[]`), `link`. DockerRuntime adds `image?`, + `dockerfile?`, `build_context?`, `engine?`, `network?`, `extra_args?`. + E2bRuntime adds `template_id?`, `dockerfile?`, `build_context?`, `cpu?`, + `memory_mb?`, `timeout_minutes?`, `preserve_after_exit_hours?` + (default 24, range 0-168 — keeps the sandbox alive after job exit so + morning sync still finds it), `api_key_env?` (default "E2B_API_KEY"). + + Export `parseRuntime(raw: unknown): RuntimeConfig` and + `resolveRuntime({ cwd, config }): RuntimeResolveResult` where + RuntimeResolveResult = `{ runtime, runner, dockerfilePath, buildContext }`. + `dockerfile` defaults to `/.poe-code/Dockerfile`; `build_context` + defaults to `cwd`. Hard-error if `type` is `docker`/`e2b` and neither + `image`/`template_id` nor a Dockerfile at the resolved path exists. + + Wire the new scope into `src/types.ts` (`ResolvedConfig.runtime`), + `src/merge.ts` (replace-by-field for scalars; concat for `mounts`, + global prepended), and `src/schema.ts`. Re-export from `src/index.ts`. + + No regex parsing — deep-merge per the project rule. + status: + implement: open + test: open + commit: open + + - id: config-runner-scope + title: Add runner scope (per-invocation behavior) to poe-code-config + prompt: | + In packages/poe-code-config/src/runtime.ts (or a sibling `runner.ts`), + define `RunnerScope = { detach: boolean; upload_max_file_mb: number; + download_conflict: "refuse" | "overwrite"; workspace?: { exclude?: string[] } }`. + Defaults: detach=false, upload_max_file_mb=100, download_conflict="refuse", + workspace.exclude=[".git", "node_modules", "dist", ".turbo", ".next", + ".poe-code/state.json"]. + + `workspace.exclude` and `mounts` are concatenative on merge (global + prepended to project). Add `RunnerScope` to `ResolvedConfig.runner`, + schema, and exports. + + Tests: parsing valid/invalid inputs; merge concat semantics; default + application when scope absent. + status: + implement: open + test: open + commit: open + + - id: config-state-manager + title: Add StateManager (templates + jobs) to poe-code-config + prompt: | + Create packages/poe-code-config/src/state/index.ts exporting + `loadStateManager(homeDir?: string): Promise` where + StateManager exposes `templates: TemplateRegistry` and `jobs: JobRegistry`. + + In src/state/templates.ts: + - Backing file: `/.poe-code/state/templates.json` + - Shape: `{ docker: { [hash]: TemplateEntry }, e2b: { [hash]: TemplateEntry } }` + - TemplateEntry: `{ hash, template_id?, image?, runtime_type, dockerfile_path, built_at }` + - Methods: `get(backend, hash)`, `put(backend, entry)`, `remove`, `list(backend?)` + - File-locked using @poe-code/file-lock around read-modify-write. + + In src/state/jobs.ts: + - One JSON file per job at `/.poe-code/state/jobs/.json` + - JobEntry: `{ id, env_id, env_kind, tool, argv, cwd, started_at, + status: "pending"|"running"|"exited"|"killed"|"lost", exit_code?, + exited_at?, log_file? }` + - Atomic writes via tmp file + rename. + - Methods: `get`, `put`, `update(id, patch)`, `list(filter?)`, `remove`. + + Tests with memfs (per CLAUDE.md): concurrent put/update preserves + invariants under file-lock; partial-write recovery; list filtering. + No real fs writes in unit tests except snapshots. + status: + implement: open + test: open + commit: open + + - id: harness-execution-env-contract + title: Define ExecutionEnv contract in agent-harness-tools + prompt: | + In packages/agent-harness-tools, add `src/execution-env.ts` with: + + ```ts + export interface ExecutionEnvFactory { + readonly type: "host" | "docker" | "e2b"; + open(spec: OpenSpec): Promise; + attach(envId: string): Promise; + } + + export interface OpenSpec { + cwd: string; + runtime: RuntimeConfig; + env: Record; + uploadIgnoreFiles: string[]; + jobLabel: { tool: string; argv: string[] }; + } + + export interface OpenedEnv { + readonly id: string; + readonly job: JobHandle | null; + uploadWorkspace(): Promise; + downloadWorkspace(opts: { conflictPolicy: "refuse" | "overwrite" }): Promise; + exec(spec: RunSpec): RunHandle; + detach(): Promise; + shell(): RunHandle; + close(): Promise; + } + + export interface JobHandle { + readonly id: string; + readonly envId: string; + readonly tool: string; + readonly argv: string[]; + status(): Promise; + stream(opts?: { sinceByte?: number }): AsyncIterable; + wait(): Promise<{ exitCode: number }>; + kill(signal?: NodeJS.Signals): Promise; + } + ``` + + RunSpec/RunHandle come from @poe-code/process-runner. Add a registry: + `registerExecutionEnvFactory(f)` and `selectExecutionEnv(runtime)` that + picks a factory by `runtime.type`. No factory implementations yet. + + Re-export everything from src/index.ts. The test verifies registry + lookup, missing-factory error, and that `selectExecutionEnv` is the + only branch on `runtime.type` — add a grep-style snapshot test if + practical. + + No SDK deps in this package. + status: + implement: open + test: open + commit: open + + - id: harness-workspace-transfer + title: Implement workspace upload/download in agent-harness-tools + prompt: | + In packages/agent-harness-tools, add `src/workspace-transfer.ts` + exporting `uploadWorkspace(env, opts)` and `downloadWorkspace(env, opts)`. + + Upload: + - Walk `cwd`. Apply `.gitignore` then `.poe-code-ignore` (additive, + never un-ignores). Apply `runner.workspace.exclude`. + - Skip files >`upload_max_file_mb` (default 100). Print one warning per skip. + - Stream as a tar to `env.uploadDir`-equivalent path. + - Return `UploadResult { files, bytes, skipped: { path, bytes, reason }[] }`. + + Download: + - Mirror remote /workspace back. Hash each local file at upload time, + stash hashes on the in-memory `OpenedEnv` handle. + - On download, re-hash local; if changed AND differs from remote, + treat as conflict. + - `conflictPolicy: "refuse"` → return `DownloadResult.conflicts[]`, + do not write the affected files. + - `conflictPolicy: "overwrite"` → clobber. + + Use memfs for tests (per CLAUDE.md). Cover: gitignore precedence, + additive poe-code-ignore, oversize skip, conflict refuse-and-list, + overwrite path. No real fs. + status: + implement: open + test: open + commit: open + + - id: harness-log-stream + title: Tee-to-file log stream and offset-aware tail + prompt: | + In packages/agent-harness-tools, add `src/log-stream.ts` with: + + export function wrapForLogTee(argv: string[], jobId: string): string[]; + export function streamLogFile(env, jobId, opts: { sinceByte?: number }): AsyncIterable; + + `wrapForLogTee` returns shell argv that runs the inner command with + stdout+stderr teed to `/tmp/poe-jobs/.log` and writes the exit + code to `/tmp/poe-jobs/.exit` after the process exits. Form: + `["sh", "-c", "mkdir -p /tmp/poe-jobs && () 2>&1 | tee /tmp/poe-jobs/.log; echo $? > /tmp/poe-jobs/.exit"]`. + + `streamLogFile` reads from `sinceByte` (default 0), then tails. On + backends without filesystem-watch, fall back to polling at 250ms. + + Add a `waitForExit(env, jobId): Promise<{ exitCode }>` that polls for + the `.exit` file and parses its contents. + + Unit tests with memfs: replay from offset 0; replay from arbitrary + offset; wait resolves with exit code; argv wrapping is shell-safe + (escape jobId). + status: + implement: open + test: open + commit: open + + - id: harness-run-poe-command + title: Implement runPoeCommand orchestrator + prompt: | + In packages/agent-harness-tools, add `src/run-poe-command.ts` exporting: + + export async function runPoeCommand(opts: { + factory: ExecutionEnvFactory; + openSpec: OpenSpec; + detach: boolean; + state: StateManager; + signal?: AbortSignal; + }): Promise< + | { kind: "sync"; exitCode: number; download: DownloadResult } + | { kind: "detached"; jobId: string; envId: string } + >; + + Lifecycle: + 1. Generate job_id (ULID). Write JobEntry with status="pending" + via `state.jobs.put`. + 2. `env = await factory.open(openSpec)`. + 3. `await env.uploadWorkspace()`. + 4. Wrap argv via `wrapForLogTee(argv, jobId)`. Call `env.exec(...)` + to get RunHandle. + 5. Update job status="running", env_id, started_at. + 6. Sync mode: pipe RunHandle stdout/stderr to process; await + `waitForExit`; download workspace per `runner.download_conflict`; + env.close(); update status="exited", exit_code. + 7. Detach mode: skip stream + wait + download + close. Return + { jobId, envId }. On signal abort during sync, kill, sync, close. + + Tests with a mock factory + memfs StateManager: pending→running→exited + transition; detach leaves env open; download conflict surfaces in + result; abort signal kills cleanly. No SDK or child_process. + status: + implement: open + test: open + commit: open + + - id: process-runner-host-factory + title: Add hostExecutionEnvFactory in process-runner + prompt: | + In packages/process-runner, add `src/host/host-execution-env.ts` + exporting `hostExecutionEnvFactory: ExecutionEnvFactory` (type: "host"). + + `open(spec)`: returns an OpenedEnv whose: + - `id` is "host" + - `uploadWorkspace`/`downloadWorkspace`/`close` are no-ops + - `exec(spec)` calls `createHostRunner().exec(spec)` (existing API) + - `shell()` runs the user's $SHELL with tty:true via host runner + - `detach()` rejects: host has no addressable env + + `attach(id)` rejects with a clear error: "host runtime does not + support reattach". + + Re-export from src/index.ts. Tests: round-trip exec through the host + runner; uploads are no-ops; attach throws. + + Do not import @poe-code/agent-harness-tools to avoid a cycle — + duplicate the contract types or move them into a shared types-only + package if needed. The harness-tools registry imports the factory + via dynamic registration at app startup. + status: + implement: open + test: open + commit: open + + - id: migrate-agent-spawn + title: Migrate agent-spawn off child_process to runPoeCommand + prompt: | + In packages/agent-spawn, replace `spawnChildProcess` calls in + `src/spawn.ts` and `src/spawn-interactive.ts` with the + runPoeCommand path: + + 1. Resolve runtime via `resolveRuntime({ cwd, config })`. + 2. `factory = selectExecutionEnv(runtime)`. + 3. `runPoeCommand({ factory, openSpec: {...}, detach, state, signal })`. + + For interactive spawn, route through `OpenedEnv.shell()` for tty. + + Behavior MUST be bit-for-bit identical when `runtime.type === "host"`. + All existing tests in this package must pass without modification. + + Remove the direct `import { spawn } from "node:child_process"` at the + top of src/spawn.ts. Remove src/run-command.ts only if it's no longer + called. + + Wire the host factory at startup: a small `register-factories.ts` + that calls `registerExecutionEnvFactory(hostExecutionEnvFactory)` — + imported once from the spawn entrypoint and from each tool entry. + status: + implement: open + test: open + commit: open + + - id: migrate-loop-tools + title: Migrate experiment-loop, ralph, superintendent to runPoeCommand + prompt: | + Apply the same migration as agent-spawn to: + - packages/experiment-loop/src/run/loop.ts + - packages/ralph/src/runtime/* (all files that currently spawn) + - packages/superintendent/src/runtime/run-builder.ts, + run-superintendent.ts, run-inspector.ts, run-owner-review.ts + + Each tool's existing inner-agent invocation (which today calls + `node:child_process` or @poe-code/agent-spawn directly) routes + through `runPoeCommand` with the resolved factory. For `runtime.type + === "host"` behavior must be unchanged; existing tests must pass. + + No `if (runtime.type === ...)` outside `selectExecutionEnv`. Verify + with a grep test. + + Each tool's entrypoint imports the `register-factories` module so the + host factory is registered before any `selectExecutionEnv` call. + status: + implement: open + test: open + commit: open + + - id: cli-universal-flags + title: Add universal --runtime/--detach/--mount-poe-code flags to all four task commands + prompt: | + Wire `--runtime host|docker|e2b`, `--runtime-image `, + `--runtime-template `, `--detach`, `--mount-poe-code` on: + - poe-code spawn + - poe-code experiment + - poe-code ralph + - poe-code superintendent + + Source of truth: each command's option definitions. Mirror the same + flags into the SDK exports (per CLAUDE.md "CLI vs SDK" rule). + + Flag semantics: each overrides the matching field on the resolved + runtime/runner config. Without the flag, config wins; with it, the + flag wins. `--detach` is a boolean toggle. + + Surface help text via the design system (no chalk, no @clack/prompts + direct usage). + + Snapshot-test the `--help` output of each command (per + docs/SNAPSHOT_TESTING.md). Take a screenshot of `poe-code spawn --help` + via `npm run screenshot-poe-code -- spawn --help` to verify visually. + status: + implement: open + test: open + commit: open + + - id: docker-factory-and-build + title: Add dockerExecutionEnvFactory with content-addressed image build + prompt: | + In packages/process-runner, add `src/docker/docker-execution-env.ts` + exporting `dockerExecutionEnvFactory: ExecutionEnvFactory` (type: "docker"). + + `open(spec)`: + - If `runtime.image` set, pull/use directly. + - Else compute hash = sha256(dockerfile_bytes + sorted(build_args)). + Look up in `state.templates.get("docker", hash)`. Hit → use cached + image tag. Miss → `docker build --tag poe-code/local:` against + the resolved `build_context`, write entry, use new image. + - Run container with mounts from `runtime.mounts`. + `uploadWorkspace`/`downloadWorkspace` use `docker cp` of a tarball. + `attach(envId)` reconnects to a container by id. + `engine` field selects docker vs podman; default auto-detect via + existing `detectEngine()`. + + Register this factory alongside host. Integration test gated on local + docker availability (skip if `docker info` fails). Unit test with + mocked Runner. + + For the dockerfile build path, the build is done by spawning the + docker CLI through the host runner — no docker SDK dep. + status: + implement: open + test: open + commit: open + + - id: cli-runtime-init-build-templates + title: Add poe-code runtime init/build/templates commands + prompt: | + Create packages/poe-code/src/commands/runtime/index.ts that registers + the `runtime` namespace, then: + + `runtime/init.ts` — `poe-code runtime init [--type host|docker|e2b] + [--no-dockerfile] [--yes]`. Idempotent: if .poe-code/Dockerfile and + .poe-code/config.json exist, update only `runtime.type` (deep-merge). + With `--yes` accept defaults; otherwise prompt via design system. + Default Dockerfile content: node:22-bookworm-slim + git + + `npm i -g @poe-code/cli @anthropic-ai/claude-code`. + + `runtime/build.ts` — `poe-code runtime build [--force]`. Resolves + runtime; if e2b, calls `e2bExecutionEnvFactory`'s template build path + via a small exposed helper. If docker, calls the docker factory's + build helper. Writes the result to `state.templates`. With `--force` + ignores cache. + + `runtime/templates/ls.ts` — list cached entries grouped by backend. + Use the design-system table component. + + `runtime/templates/clear.ts` — drop all entries (with `--yes`) or + prompt for confirmation. Only clears local-built entries; pinned + `image`/`template_id` references in config are not touched. + + Snapshot/screenshot tests for ls + clear output. + status: + implement: open + test: open + commit: open + + - id: runner-e2b-package + title: Create runner-e2b package implementing e2bExecutionEnvFactory + prompt: | + Create new package packages/runner-e2b with: + + package.json — name @poe-code/runner-e2b; declares `e2b` SDK as a + runtime dependency (NOT @modelcontextprotocol/sdk; that rule is + unrelated but we follow the same "SDK only where used" discipline). + README.md listing env vars (E2B_API_KEY) and config options + (runtime.api_key_env, cpu, memory_mb, timeout_minutes). + tsconfig.json matching sibling packages. + + src/index.ts — `export const e2bExecutionEnvFactory: ExecutionEnvFactory`. + + src/sdk.ts — the only file that imports the e2b SDK. Exports thin + typed wrappers: `createSandbox(opts)`, `connectSandbox(id)`, + `buildTemplate(opts)`, `listSandboxes()`. Lints fail elsewhere if + anyone else imports the SDK. + + src/template-build.ts — `buildOrResolveTemplate({ runtime, dockerfilePath, + buildContext, state }): Promise<{ templateId: string; cached: boolean }>`. + Hash inputs, look up in state.templates.get("e2b", hash); on miss + call sdk.buildTemplate, write entry, return. + + src/factory.ts — open() resolves API key from + `auth.providers.e2b` (or runtime.api_key_env), resolves template + (template_id direct, else buildOrResolveTemplate), creates sandbox, + returns OpenedEnv. attach(envId) connects to existing sandbox. + + src/opened-env.ts — implements OpenedEnv. uploadWorkspace uses sdk + filesystem write of a tar; downloadWorkspace tars + reads. exec + forwards to sdk command run. shell uses tty:true. detach() registers + the running job in state and returns JobHandle. close() closes sandbox. + + src/job-handle.ts — implements JobHandle. status() consults + sdk.commands.get + the .exit marker file. stream() uses sdk file watch + on `/tmp/poe-jobs/.log` via streamLogFile. wait() polls .exit. + kill() sends signal via sdk. + + Keep-alive after exit: when JobHandle.wait() resolves, the wrapper + script extends the sandbox timeout via the e2b SDK to + `runtime.preserve_after_exit_hours` (default 24). This is critical + for the overnight workflow — agent finishes at 2am, sandbox sits + alive until morning sync. Released on `sync --close` or `stop`. + Add `preserve_after_exit_hours` to the E2bRuntime config in + poe-code-config (default 24, range 0-168). The wrapper script in + log-stream.ts gets a final line: after writing the `.exit` file, + call a small "extend timeout" helper exec from inside the sandbox + that talks to the e2b API; or simpler — the host-side runPoeCommand + issues the extend call when wait() resolves in detach mode. + + Unit tests: mock sdk.ts. Integration test gated on E2B_API_KEY: + build minimal template, open, exec echo, download, close. Skipped + from default `npm test`; runs in a dedicated workflow. + + Register the factory in the same `register-factories` module as host + and docker. + status: + implement: open + test: open + commit: open + + - id: cli-runtime-jobs + title: Add poe-code runtime jobs ls/attach/logs/stop/sandbox commands + prompt: | + In packages/poe-code/src/commands/runtime/jobs/: + + `ls.ts` — list state.jobs entries. Reconcile each `running` entry by + calling `factory.attach(env_id).status()` and downgrading missing + sandboxes to `lost`. Render via the design-system table: + JOB | TOOL | RUNTIME | STATUS | STARTED | SANDBOX. + + Single-job ergonomics: every command below accepts `` as + optional. When omitted, resolve to "the only detached job that + matches the command's intent" (running for attach/logs; running or + exited for sync/stop). On ambiguity, error and list candidates. + This optimizes for the common overnight workflow (one job at a + time). + + `attach.ts [jobId]` — load entry; `factory.attach(env_id)`; replay + via JobHandle.stream({ sinceByte: 0 }) by default, or `--since 5m` + to seek by mtime. Ctrl-C detaches the local stream but does NOT + kill the job. Print `detaching (job continues running)`. With no + jobId, picks the latest running job. + + `logs.ts [jobId] [--since ]` — non-interactive dump. With + no jobId, picks the latest running or exited job. + + `stop.ts [jobId] [--sync] [--force-sync]` — JobHandle.kill('SIGTERM'); + 30s grace; SIGKILL. With `--sync` download workspace per + conflict policy ("refuse" by default). `--force-sync` overrides + to "overwrite". Update state to "killed" + exit_code 130. + + `sync.ts [jobId] [--force-sync] [--close]` — the primitive pull. + For a running job: snapshot download, sandbox stays alive. + For an exited job: final download. With `--close`, also close the + sandbox after the pull. Conflict policy honored; `--force-sync` + overrides "refuse" → "overwrite". `stop --sync` and + `attach --sync-on-exit` are sugar over this primitive — implement + both by composing `sync.ts`. + + `sandbox.ts ` — `factory.attach(envId).shell()`; pipe local + stdin/stdout with tty. Ctrl-D closes the shell but leaves the + sandbox running. + + Add `--detach` plumbing through the four task commands so they call + runPoeCommand with detach=true and print + `job started: \nsandbox: \ndetached.`. + + Snapshot/screenshot tests for `runtime jobs ls` (mock state), `jobs + logs` output, and `--detach` output. + status: + implement: open + test: open + commit: open + + - id: qa-and-readmes + title: Manual QA doc, README updates, design-doc regeneration + prompt: | + Create docs/plans/qa/e2b-integration.md as a markdown checklist + (per CLAUDE.md "QA is not a script"): + - Fresh repo: `poe-code runtime init` writes .poe-code/Dockerfile + and .poe-code/config.json. + - First-run e2b builds template; second run hits cache. + - `poe-code ralph plan.md --runtime e2b --detach` returns jobId; + sandbox visible in e2b dashboard. + - `poe-code runtime jobs attach ` resumes log; Ctrl-C detaches + without killing. + - `poe-code runtime jobs stop ` kills + syncs back. + - Modify a local file mid-run, then sync-back: refuse-and-list + output is clear. + - Same Dockerfile shared with a teammate → same template_id resolves. + + Update READMEs to list new env vars and config options (per CLAUDE.md + package-rules): + - packages/poe-code-config/README.md: runtime + runner scopes, + state file locations. + - packages/agent-harness-tools/README.md: ExecutionEnv contract, + runPoeCommand entry point. + - packages/process-runner/README.md: host + docker factories. + - packages/runner-e2b/README.md: full doc (env vars, config, + template build flow). + + Run `npm run generate:design-docs` if any visual language changed. + + Do NOT touch the project root README without a separate request + (per CLAUDE.md readme rule). + status: + implement: open + commit: open +--- + +# e2b integration + +Run spawn, experiment, ralph, and superintendent on e2b sandboxes, sync or async (detach + reconnect), caller's choice. + +## 1. What we're building + +End the "works on my machine" failure mode. The repo declares its execution environment once — a Dockerfile plus a `runtime` config block — and `poe-code spawn|experiment|ralph|superintendent` runs identically on the host, in Docker, or in an e2b sandbox. + +All four top-level tools accept the same runtime selector. e2b is a third backend alongside host and docker; docker support ships in this work because it shares the same config scope, and skipping it would split the pitch. Per-tool branching is not allowed — every tool gets the runtime treatment for free. + +Execution mode is a caller decision, not a per-tool default: + +- **sync** — block until exit, stream output, tear down on close. +- **async** — `--detach` returns a job id, sandbox + job keep running, reattach later from any machine. + +Mode is selectable per-invocation (`--detach`) and as a config default (`runner.detach: true`). + +The conceptual model: the local CLI opens an env, uploads the workspace, and runs the same `poe-code ` invocation inside it. No re-implementation per backend — the inner process runs on the host runner inside the box. + +Encapsulation lives in `@poe-code/agent-harness-tools`: owns the `ExecutionEnv` contract and the lifecycle (open → upload → exec → stream → close or detach). The e2b SDK lives in a new `@poe-code/runner-e2b` package; the docker runner already exists in `@poe-code/process-runner`. Both implement the same factory. Harness-tools has no SDK dependencies. + +Reuses, not reinvented: + +- The `runtime` config scope previously designed in `docs/plans/archive/spawn-docker-integration.md` ships here, extended with `type: "e2b"`. Same `dockerfile`, `image`/`template_id`, `build_context`, `build_args`, `mounts`, `link` fields. +- e2b builds templates from Dockerfiles, so one Dockerfile drives both backends. +- Templates are content-addressed by Dockerfile hash and cached in the state file; teammates with the same Dockerfile reuse the same template. + +## 2. User-facing shape + +### Declaring a runtime + +Convention: every repo opting into a non-host runtime ships a `.poe-code/Dockerfile` next to `.poe-code/config.json`. No path discovery, no per-project bikeshedding. + +```text +.poe-code/ +├── config.json +└── Dockerfile ← canonical location +``` + +A minimal one: + +```dockerfile +FROM node:22-bookworm-slim +RUN apt-get update && apt-get install -y --no-install-recommends git ca-certificates \ + && rm -rf /var/lib/apt/lists/* +RUN npm i -g @poe-code/cli @anthropic-ai/claude-code +WORKDIR /workspace +``` + +The `runtime` block in `.poe-code/config.json` selects the backend: + +```jsonc +// .poe-code/config.json +{ + "runtime": { + "type": "e2b", + "build_args": { "NODE_VERSION": "22" }, + "mounts": [ + { "source": ".", "target": "/workspace" } + ], + "link": "https://github.com/my-org/repo/blob/main/.poe-code/Dockerfile" + } +} +``` + +`type` accepts `"host" | "docker" | "e2b"`. With `host` (the default), nothing changes vs. today. + +Defaults derived from the convention: + +- `dockerfile` → `.poe-code/Dockerfile` (override only if you have a non-standard layout, e.g. monorepo). +- `build_context` → repo root (the directory containing `.poe-code/`). + +Pre-built images opt out of the Dockerfile entirely and just point at a registered artifact: + +```jsonc +{ "runtime": { "type": "docker", "image": "ghcr.io/my-org/dev:latest" } } +{ "runtime": { "type": "e2b", "template_id": "tmpl_abc123" } } +``` + +If `type` is `docker` or `e2b`, neither `image`/`template_id` nor a Dockerfile at the conventional path is present, runtime resolution hard-errors with a pointer to `poe-code runtime init`. + +### Scaffolding + +```console +$ poe-code runtime init +created .poe-code/Dockerfile (minimal node:22 + poe-code + claude) +updated .poe-code/config.json: runtime.type = "e2b" +next: commit, then run `poe-code runtime build` (or just run any tool). +``` + +`poe-code runtime init --type docker` flips the type. `--no-dockerfile` skips writing the Dockerfile (useful when you'll point at a pre-built `image`/`template_id`). + +### Per-invocation overrides + +Every tool accepts the same flags. Config is the default; flags override. + +```text +--runtime host|docker|e2b override runtime.type +--runtime-image override docker image +--runtime-template override e2b template_id +--detach async; print jobId and exit +--sandbox (reserved; reuse not supported in v1) +--mount-poe-code dev: upload local poe-code build into the env +``` + +### spawn + +With `runtime.type: host` (the default), behavior is identical to today. + +```console +$ poe-code spawn claude "fix the failing test" --runtime e2b +opening e2b sandbox (template tmpl_abc123)... +uploading workspace (.gitignore-respected, 142 files, 8.3 MB)... +[claude] reading test output... +[claude] editing src/foo.ts... +[claude] tests passing. +syncing workspace back... +done. exit 0. + +$ poe-code spawn claude "..." --runtime e2b --detach +opening e2b sandbox... +uploading workspace... +job started: job_01HZX... +sandbox: sb_4f9c... +detached. attach with: poe-code jobs attach job_01HZX... +``` + +### experiment / ralph / superintendent + +Same flag surface. Long-running loops are the obvious `--detach` use case: + +```console +$ poe-code ralph plan.md --runtime e2b --detach +opening e2b sandbox... +uploading workspace... +job started: job_01HZY... +detached. + +$ poe-code superintendent plan.md --runtime e2b --detach +job started: job_01HZZ... +``` + +### Command surface + +The four task commands (`spawn`, `experiment`, `ralph`, `superintendent`) keep their existing shape and gain the universal flags above. Everything else runtime-related is grouped under one noun: `poe-code runtime`. + +```text +poe-code runtime build build template from the project's Dockerfile (force) +poe-code runtime templates ls list cached dockerfile_hash → template_id entries +poe-code runtime templates clear drop the local template cache + +poe-code runtime jobs ls list active and recently-exited jobs +poe-code runtime jobs attach reattach to a running job's log stream +poe-code runtime jobs logs dump logs (supports --since) +poe-code runtime jobs stop kill the job; sync workspace back on exit +poe-code runtime jobs sandbox open an interactive shell in the sandbox +``` + +No top-level `poe-code jobs` namespace — jobs are a runtime concept and live under it. + +### Building / refreshing templates + +For the dockerfile path, the first run with a new Dockerfile builds an e2b template; the hash → template id is written to the state file and reused. Teammates with the same Dockerfile reuse the same template. + +```console +$ poe-code spawn claude "..." --runtime e2b +no cached template for .poe-code/Dockerfile (hash 7f3a91...). building... +e2b template build: ........ done (template tmpl_dee44a in 47s) + cached: ~/.poe-code/state/templates.json +opening sandbox (tmpl_dee44a)... +``` + +### Job control + +```console +$ poe-code runtime jobs ls +JOB TOOL RUNTIME STATUS STARTED SANDBOX +job_01HZX... spawn:claude e2b running 2026-05-01 10:14 sb_4f9c... +job_01HZY... ralph e2b running 2026-05-01 10:18 sb_2a1e... +job_01HZZ... superintendent e2b exited(0) 2026-05-01 09:52 sb_8b3d... + +$ poe-code runtime jobs attach job_01HZY... +[ralph] iteration 4 — applying patch... +^C +detaching (job continues running). use `runtime jobs stop` to kill. + +$ poe-code runtime jobs logs job_01HZY... --since 2m +[ralph] iteration 5 — running tests... + +$ poe-code runtime jobs stop job_01HZY... +killed. workspace synced back. exit 130. + +$ poe-code runtime jobs sandbox sb_4f9c... +opening interactive shell in sandbox... +sandbox$ pwd +/workspace +``` + +### Workspace transfer + +Default behavior: + +- Upload: `cwd` minus `.gitignore` minus `.poe-code-ignore` (additive). Files >100MB warned and skipped. +- Download (sync mode): on clean exit, mirror back. Conflict policy: refuse to overwrite locally-modified files; print a list and exit non-zero. +- Download (detach): no auto-download. `jobs stop` and `jobs attach … --sync-on-exit` trigger it explicitly. + +### Auth and env + +Provider tokens (poe, anthropic, codex, …) and `POE_*` env vars are forwarded from local `poe-code-config` + auth-store onto the inner `exec`. Never written into the sandbox image. Never persisted on disk inside the sandbox. The user's `~/.poe-code/config.json` content is materialized into the sandbox's home dir before exec, so the inner `poe-code` resolves config identically. + +## 3. Implementation details and technical decisions + +### Package layout + +```text +packages/ + agent-harness-tools/ owns ExecutionEnv contract + lifecycle (no SDKs) + process-runner/ existing host + docker runners; gains "build from dockerfile" path + runner-e2b/ new; e2b SDK lives only here + poe-code-config/ new runtime + runner scopes + agent-spawn/ switches from child_process to ExecutionEnv +``` + +`agent-harness-tools` keeps its zero-SDK rule — depends on `process-runner` and `runner-e2b` only through the `ExecutionEnv` factory interface. `agent-spawn`, `experiment-loop`, `ralph`, and `superintendent` all stop calling `child_process.spawn` and `process-runner` directly; they call `harness-tools` to open an env, then `exec` inside it. There is no per-tool branching on `runtime.type` — every tool gets the runtime treatment for free. + +### `ExecutionEnv` contract (in `agent-harness-tools`) + +```ts +export interface ExecutionEnvFactory { + readonly type: "host" | "docker" | "e2b"; + open(spec: OpenSpec): Promise; + attach(jobId: string): Promise; // for detach + reattach +} + +export interface OpenSpec { + cwd: string; + runtime: RuntimeConfig; // resolved from poe-code-config + env: Record; // forwarded provider tokens + POE_* + uploadIgnoreFiles: string[]; // ['.gitignore', '.poe-code-ignore'] + jobLabel: { tool: string; argv: string[] }; +} + +export interface OpenedEnv { + readonly id: string; // sandbox/container id; "host" for host + readonly job: JobHandle | null; // populated only after detach() + uploadWorkspace(): Promise; + downloadWorkspace(opts: { conflictPolicy: "refuse" | "overwrite" }): Promise; + exec(spec: RunSpec): RunHandle; // RunSpec/RunHandle from process-runner + detach(): Promise; // freeze ownership, register job, return id + shell(): RunHandle; // interactive tty + close(): Promise; +} +``` + +Three implementations, all in their own packages: `host` and `docker` in `process-runner`, `e2b` in `runner-e2b`. The harness ships a tiny `selectExecutionEnv(runtime)` helper that picks a factory by `runtime.type`. Adding a fourth backend is one new package and one register-call — no edits to harness-tools or any tool. + +### Runtime config scope + +`poe-code-config` already supports nested JSON via the existing scope mechanism. Add two scopes — `runtime` and `runner`: + +```ts +type RuntimeConfig = + | { type: "host" } + | DockerRuntime + | E2bRuntime; + +interface DockerRuntime { + type: "docker"; + image?: string; // mutually exclusive with dockerfile + dockerfile?: string; + build_context?: string; + build_args?: Record; + mounts?: Mount[]; // ["./src", "/workspace/src"] etc. + ports?: Port[]; + network?: string; + extra_args?: string[]; + link?: string; // informational + engine?: "docker" | "podman"; +} + +interface E2bRuntime { + type: "e2b"; + template_id?: string; // mutually exclusive with dockerfile + dockerfile?: string; + build_context?: string; + build_args?: Record; + mounts?: Mount[]; // upload-only on open + link?: string; + api_key_env?: string; // default "E2B_API_KEY" +} + +interface RunnerScope { + detach: boolean; // default false + upload_max_file_mb: number; // default 100; oversize files warned + skipped + download_conflict: "refuse" | "overwrite"; // default "refuse" +} +``` + +Validation lives in `poe-code-config/src/runtime.ts`. The doc-level merge in `merge.ts` already supports nested objects; per-field replace, per-array concat for `mounts` (global `default_mounts` prepend project `mounts`). + +### Templates and content addressing + +Both `docker` and `e2b` accept either a pre-built artifact (`image` / `template_id`) or a Dockerfile. For the Dockerfile path, the cache key is `sha256(dockerfile_bytes + sorted(build_args))`. Cache file: `~/.poe-code/state/templates.json`: + +```json +{ + "e2b": { + "7f3a91ee...": { "template_id": "tmpl_dee44a", "built_at": "2026-05-01T..." } + }, + "docker": { + "7f3a91ee...": { "image": "poe-code/local:7f3a91ee", "built_at": "..." } + } +} +``` + +First-run miss for the active backend triggers `runtime build`; the result is written to the cache. Two devs racing the build is harmless — the second write replaces the first; both template ids work. `runtime templates ls` and `runtime templates clear` operate on this file. + +### Job model and persistence + +A "job" is a detached `OpenedEnv` plus its inner `exec` invocation. Jobs are persisted at `~/.poe-code/state/jobs/.json`: + +```json +{ + "id": "job_01HZX...", + "tool": "spawn:claude", + "runtime": "e2b", + "sandbox_id": "sb_4f9c...", + "started_at": "...", + "status": "running" | "exited" | "killed", + "exit_code": null, + "argv": ["spawn", "claude", "fix the failing test"], + "cwd": "/Users/kjopek/Workspace/foo", + "log_file": "~/.poe-code/state/jobs/.log" +} +``` + +Jobs are local to the machine that detached. `runtime jobs ls` reads the directory; running jobs are health-checked by querying the backend (e2b: `sandboxes.list`). Stale entries (sandbox gone, job marked running) are flipped to `status: "exited", exit_code: -1` and a `reason: "sandbox_disappeared"` field is added. + +Cross-machine reattach is **out of scope for v1**. The job id is meaningful only on the machine that detached. We document this in `runtime jobs ls --help`. + +### Workspace upload / download + +Upload uses an ignore-aware tar: + +1. Walk `cwd`, applying `.gitignore` rules, then `.poe-code-ignore` (additive — never un-ignores something gitignore excluded). +2. Skip files >`runner.upload_max_file_mb` (default 100) and print a warning per skip. +3. Stream a tarball over the SDK's filesystem API. e2b: `sandbox.files.write` with a stream; docker: `docker cp` of the tarball + extract. +4. Emit a single summary line: `uploading workspace (.gitignore-respected, 142 files, 8.3 MB)...`. + +Download mirrors the same ignore set in reverse, comparing local mtime/hash vs remote. `conflict_policy: "refuse"` (default) prints conflicting paths and exits non-zero; `"overwrite"` clobbers. No three-way merge. + +### Auth and inner-process env + +- Provider tokens come from `auth-store` and are passed only via `env` on the inner `exec`. Never written to a file inside the sandbox. Never baked into the template. +- The user's resolved `poe-code-config` (merged global + project) is serialized to JSON and written to the sandbox at `$HOME/.poe-code/config.json` *immediately before* `exec` (e2b file write API; docker bind-mount or `cp`). It is removed in `close()`. This makes the inner `poe-code` resolve config identically to the host. +- `E2B_API_KEY` is read from the host env (configurable name via `runtime.api_key_env`); never forwarded into the sandbox. + +### Interactive shell + +`runtime jobs sandbox ` calls `OpenedEnv.shell()`, which opens a tty-attached `bash`/`sh` inside the existing sandbox/container. e2b: `sandbox.commands.run("bash", { tty: true })` piped through `process.stdin/stdout`. Local Ctrl-D detaches the shell but leaves the sandbox running. Same primitive backs `attach`'s log stream — both go through the same RunHandle plumbing in `process-runner/types.ts`. + +### Edge cases + +- **Ignore-file precedence.** `.gitignore` first (covers third-party deps), `.poe-code-ignore` second and additive only. Never un-ignores. If a user wants `node_modules` *included* in the upload (unusual but plausible for offline reproduction), they remove it from `.gitignore` — we do not invent an "include" syntax. +- **Race on first-run template build.** Two CLI invocations on different machines build the same Dockerfile concurrently. Each writes its own template id to its own state file; both are valid. No locking, no coordination. +- **Sandbox disappears during sync detach.** e2b auto-pauses idle sandboxes after a configurable timeout. Sync mode keeps the sandbox alive via the active connection; detached mode relies on e2b's keep-alive (default 60s of idle → pause). We document the cap; killing a paused sandbox is a `runtime jobs stop` no-op that cleans the state file. +- **Workspace conflicts on download.** Default `refuse` exits non-zero with a list. Surfaced clearly in `attach --sync-on-exit` and `jobs stop`. +- **Dockerfile changes mid-job.** The job carries the template id it opened with. Editing the Dockerfile after detach has no effect on the running job; the next `open` rebuilds. +- **`--mount-poe-code` (dev).** Uploads the local `poe-code` build (`packages/poe-code/dist/` plus deps) to `/usr/local/lib/poe-code` and prepends it to the inner `PATH`. For testing unreleased local changes inside the sandbox. + +### Flags, env vars, defaults + +| Surface | Default | Override | +| --- | --- | --- | +| `runtime.type` | `host` | config `runtime.type`, flag `--runtime` | +| `runner.detach` | `false` | config `runner.detach`, flag `--detach` | +| `runner.upload_max_file_mb` | `100` | config only | +| `runner.download_conflict` | `refuse` | config only; `--sync-on-exit --overwrite` future | +| e2b api key env | `E2B_API_KEY` | `runtime.api_key_env` | +| Template cache | `~/.poe-code/state/templates.json` | not configurable | +| Job state dir | `~/.poe-code/state/jobs/` | not configurable | + +## 4. Interfaces and test plan + +### Module-boundary types + +`@poe-code/agent-harness-tools` (new exports): + +```ts +export interface ExecutionEnvFactory { /* see L3 */ } +export interface OpenSpec { /* see L3 */ } +export interface OpenedEnv { /* see L3 */ } + +export interface UploadResult { + files: number; + bytes: number; + skipped: { path: string; bytes: number; reason: "max_size" }[]; +} + +export interface DownloadResult { + files: number; + bytes: number; + conflicts: { path: string; reason: "local_modified" }[]; +} + +export interface JobHandle { + readonly id: string; + readonly envId: string; + readonly tool: string; + readonly argv: string[]; + status(): Promise; + stream(opts?: { sinceByte?: number }): AsyncIterable; + wait(): Promise<{ exitCode: number }>; + kill(signal?: NodeJS.Signals): Promise; +} + +export type JobStatus = "running" | "exited" | "killed" | "lost"; + +export function selectExecutionEnv( + runtime: RuntimeConfig +): ExecutionEnvFactory; + +export function runPoeCommand(opts: RunPoeCommandOptions): Promise; + +export interface RunPoeCommandOptions { + factory: ExecutionEnvFactory; + openSpec: OpenSpec; + detach: boolean; + state: StateManager; + signal?: AbortSignal; +} + +export type RunPoeCommandResult = + | { kind: "sync"; exitCode: number; download: DownloadResult } + | { kind: "detached"; jobId: string; envId: string }; +``` + +`@poe-code/poe-code-config` (new exports): + +```ts +export type RuntimeConfig = + | { type: "host" } + | DockerRuntime + | E2bRuntime; + +export interface DockerRuntime { /* see L3 */ } +export interface E2bRuntime { /* see L3 */ } +export interface RunnerScope { /* see L3 */ } + +export interface RuntimeResolveResult { + runtime: RuntimeConfig; + runner: RunnerScope; + dockerfilePath: string | null; // resolved absolute, or null when image/template_id used + buildContext: string | null; +} + +export function resolveRuntime(opts: { + cwd: string; + config: ResolvedConfig; +}): RuntimeResolveResult; + +export interface StateManager { + templates: TemplateRegistry; + jobs: JobRegistry; +} + +export interface TemplateRegistry { + get(backend: "docker" | "e2b", hash: string): TemplateEntry | null; + put(backend: "docker" | "e2b", entry: TemplateEntry): Promise; + remove(backend: "docker" | "e2b", hash: string): Promise; + list(backend?: "docker" | "e2b"): TemplateEntry[]; +} + +export interface JobRegistry { + get(jobId: string): JobEntry | null; + put(entry: JobEntry): Promise; + update(jobId: string, patch: Partial): Promise; + list(filter?: { status?: JobStatus[]; tool?: string }): JobEntry[]; +} + +export function loadStateManager(homeDir?: string): Promise; +``` + +`@poe-code/runner-e2b` (single named export): + +```ts +export const e2bExecutionEnvFactory: ExecutionEnvFactory; +``` + +`@poe-code/process-runner` (additional exports): + +```ts +export const hostExecutionEnvFactory: ExecutionEnvFactory; +export const dockerExecutionEnvFactory: ExecutionEnvFactory; +``` + +### Test plan + +**Unit — `poe-code-config`:** + +- `resolveRuntime` merging cases: project overrides global; arrays concat; mutually exclusive image/dockerfile rejected; missing dockerfile + missing image hard-errors. +- `StateManager`: concurrent `put` calls preserve invariants (use `file-lock`); reading partial-write state is detected and rejected; per-job file write is atomic via `tmp + rename`. + +**Unit — `agent-harness-tools`:** + +- `runPoeCommand` flow with a mock `ExecutionEnvFactory`: state moves `pending → running → exited`; sync path closes env; detach path leaves env open and returns jobId. +- Workspace transfer: gitignore parsed, additive `.poe-code-ignore`, max-size skip, conflict refuse-and-list. Use `memfs` per CLAUDE.md. +- Log streaming: `stream({ sinceByte: 0 })` replays history; `stream({ sinceByte: N })` starts at offset; `wait()` resolves on exit-marker file. + +**Unit — `process-runner`:** + +- `hostExecutionEnvFactory.open` is a thin adapter: `exec` round-trips through existing host runner; `uploadDir`/`downloadDir`/`close` are no-ops. +- `dockerExecutionEnvFactory`: open with `image`, with `dockerfile`, both fail-closed when neither. + +**Unit — `runner-e2b`:** + +- Mock the e2b SDK at the boundary; verify `open` resolves template via `StateManager.templates`, builds on miss, opens sandbox. +- `attach(envId)` calls SDK reconnect; rejects on "sandbox not found" with a typed error. + +**Integration:** + +- New package `runner-e2b/test/integration.test.ts` (gated on `E2B_API_KEY`). Builds a minimal Dockerfile, opens a sandbox, runs `echo`, downloads. Skipped without API key. Not in default `npm test`. +- `agent-spawn` end-to-end with `runtime.type: "docker"` against the local docker daemon — gated on docker availability. + +**E2E (`npm run e2e:verbose`):** + +- `poe-code runtime init` creates files; subsequent `poe-code spawn ...` against host succeeds (no docker required). +- `poe-code runtime jobs ls` against an empty state returns clean output. +- Skipped or smoke-only for docker/e2b paths. + +**Visual / screenshot:** + +- `npm run screenshot-poe-code -- runtime --help`, `runtime jobs ls`, `runtime templates ls`. +- `--detach` output of `poe-code spawn` (against a mock factory). + +**Manual QA — markdown checklist** at `docs/plans/qa/e2b-integration.md`: + +- [ ] Fresh repo, run `poe-code runtime init`, verify `.poe-code/Dockerfile` and `.poe-code/config.json` written. +- [ ] `poe-code spawn claude "..." --runtime e2b` first run builds template; second run hits cache. +- [ ] `poe-code ralph plan.md --runtime e2b --detach` returns jobId; sandbox visible in e2b dashboard. +- [ ] `poe-code runtime jobs attach ` resumes log; Ctrl-C detaches without killing. +- [ ] `poe-code runtime jobs stop ` kills + syncs. +- [ ] Modify a local file mid-run, then sync-back: refuse-and-list output is clear. +- [ ] Same Dockerfile shared with a teammate → same template_id resolves. + +### Rollout / migration + +No existing callers break: `runtime.type` defaults to `host`, which is the current code path. The `child_process.spawn` call sites in `agent-spawn`, `experiment-loop`, `ralph`, `superintendent` are migrated through the new `runPoeCommand` helper, but the host `ExecutionEnvFactory` adapter routes them back to today's behavior bit-for-bit. + +Migration ordering (keeps the branch green): + +1. Land `runtime` + `runner` config scopes with parser/validator. No callers. +2. Land `ExecutionEnv` contract and `host` factory in `process-runner`. No callers. +3. Land `runPoeCommand` in `agent-harness-tools` against the host factory only. No callers. +4. Migrate `agent-spawn` to call `runPoeCommand`. Behavior unchanged for `type: host`. +5. Migrate `experiment-loop`, `ralph`, `superintendent` similarly. +6. Land `docker` factory + template build path. New CLI: `poe-code runtime init`, `runtime build`, `runtime templates *`. +7. Land `runner-e2b`. New CLI: `runtime jobs *`. +8. Land `--detach` plumbing through `runPoeCommand`. +9. Documentation + screenshots. + +Each step is independently shippable; nothing past step 1 is a breaking change. + +### Autonomy checklist + +For an agent picking this up to run end-to-end without coming back: + +- [ ] All four task commands accept `--runtime`, `--detach`, `--mount-poe-code` and read the same config scopes. +- [ ] `runtime.type === "host"` runs identically to today (verified by existing test suite). +- [ ] `selectExecutionEnv(runtime)` is the only branch on `runtime.type`. Grep-test: no `if (runtime.type === ...)` outside that helper. +- [ ] No `child_process.spawn` calls remain in `agent-spawn`, `experiment-loop`, `ralph`, `superintendent`. +- [ ] `StateManager` is the only writer to `~/.poe-code/state/`. Grep-test in CI. +- [ ] e2b SDK appears only in `runner-e2b` deps. Lint rule via `package.json` rules or `npm run lint:deps`. +- [ ] `poe-code runtime init` is idempotent: re-running on an initialized repo updates `runtime.type` but does not overwrite an existing Dockerfile (prompts unless `--yes`). +- [ ] Snapshot tests cover `runtime jobs ls` formatting (per `docs/SNAPSHOT_TESTING.md`). +- [ ] Manual QA doc is markdown, executable by an agent (per CLAUDE.md QA convention). +- [ ] All new packages have a README listing env vars and config options (per CLAUDE.md package rules). + +## 5. Code plan + +### Files to create + +**`packages/poe-code-config/src/runtime.ts`** — runtime + runner scope types, parser, validator, `resolveRuntime`. + +```ts +export type RuntimeConfig = HostRuntime | DockerRuntime | E2bRuntime; +export interface RuntimeResolveResult { /* L4 */ } +export function parseRuntime(raw: unknown): RuntimeConfig; +export function parseRunnerScope(raw: unknown): RunnerScope; +export function resolveRuntime(opts: { cwd: string; config: ResolvedConfig }): RuntimeResolveResult; +``` + +**`packages/poe-code-config/src/state/index.ts`** — `StateManager` entry point. + +```ts +export async function loadStateManager(homeDir?: string): Promise; +``` + +**`packages/poe-code-config/src/state/templates.ts`** — `TemplateRegistry` over `~/.poe-code/state/templates.json` with `file-lock`. + +**`packages/poe-code-config/src/state/jobs.ts`** — `JobRegistry` over `~/.poe-code/state/jobs/.json` (one file per job; atomic via `tmp + rename`). + +**`packages/agent-harness-tools/src/execution-env.ts`** — `ExecutionEnvFactory`, `OpenedEnv`, `JobHandle` interfaces; `selectExecutionEnv` registry. + +```ts +export function registerExecutionEnvFactory(factory: ExecutionEnvFactory): void; +export function selectExecutionEnv(runtime: RuntimeConfig): ExecutionEnvFactory; +``` + +**`packages/agent-harness-tools/src/run-poe-command.ts`** — the universal entry point. + +```ts +export async function runPoeCommand(opts: RunPoeCommandOptions): Promise; +``` + +**`packages/agent-harness-tools/src/workspace-transfer.ts`** — gitignore + poe-code-ignore aware tar; oversize skip. + +```ts +export async function uploadWorkspace(env: OpenedEnv, opts: UploadOptions): Promise; +export async function downloadWorkspace(env: OpenedEnv, opts: DownloadOptions): Promise; +``` + +**`packages/agent-harness-tools/src/log-stream.ts`** — tee-to-file inside sandbox + offset-aware tail on the host. + +```ts +export function wrapForLogTee(argv: string[], jobId: string): string[]; // returns sh -c "..." +export function streamLogFile(env: OpenedEnv, jobId: string, opts: { sinceByte?: number }): AsyncIterable; +``` + +**`packages/process-runner/src/host/host-execution-env.ts`** — `hostExecutionEnvFactory`. Wraps existing host runner; uploads/downloads are no-ops. + +**`packages/process-runner/src/docker/docker-execution-env.ts`** — `dockerExecutionEnvFactory`. Builds image from Dockerfile when `image` is absent (delegates to `StateManager.templates` for hash → image). Container lifecycle. + +**`packages/runner-e2b/`** — NEW package. + +```text +packages/runner-e2b/ +├── package.json +├── README.md env vars, config options +├── tsconfig.json +└── src/ + ├── index.ts export { e2bExecutionEnvFactory } + ├── factory.ts implements ExecutionEnvFactory + ├── opened-env.ts implements OpenedEnv (upload, exec, download, close, shell) + ├── template-build.ts hash + cache + e2b template build + ├── job-handle.ts implements JobHandle (status, stream, wait, kill) + ├── sdk.ts thin wrapper around @e2b SDK; the only file that imports it + └── *.test.ts +``` + +**`packages/poe-code/src/commands/runtime/`** — new CLI namespace. + +```text +packages/poe-code/src/commands/runtime/ +├── index.ts root: registers subcommands +├── init.ts poe-code runtime init +├── build.ts poe-code runtime build +├── templates/ls.ts poe-code runtime templates ls +├── templates/clear.ts poe-code runtime templates clear +├── jobs/ls.ts poe-code runtime jobs ls +├── jobs/attach.ts poe-code runtime jobs attach +├── jobs/logs.ts poe-code runtime jobs logs +├── jobs/stop.ts poe-code runtime jobs stop +└── jobs/sandbox.ts poe-code runtime jobs sandbox +``` + +**`docs/plans/qa/e2b-integration.md`** — manual QA checklist (markdown, executable by agent, per CLAUDE.md rule). + +### Files to change + +**`packages/poe-code-config/src/index.ts`** — re-export `RuntimeConfig`, `RunnerScope`, `resolveRuntime`, `loadStateManager`. + +**`packages/poe-code-config/src/types.ts`** — add `runtime` and `runner` to `ResolvedConfig`. + +**`packages/poe-code-config/src/merge.ts`** — extend merge rules: `runtime` is replace-by-field; `runtime.mounts` and `runner.workspace.exclude` concat (global prepended to project). + +**`packages/poe-code-config/src/schema.ts`** — JSON schema for the new scopes (for `poe-code-config-schema-generation` per the existing plan). + +**`packages/agent-harness-tools/src/index.ts`** — re-export `ExecutionEnvFactory`, `OpenedEnv`, `JobHandle`, `runPoeCommand`, `selectExecutionEnv`, transfer + log helpers. + +**`packages/agent-harness-tools/package.json`** — add `@poe-code/poe-code-config` (new) and `@poe-code/process-runner` (already there) deps. No SDK deps. + +**`packages/process-runner/src/index.ts`** — export `hostExecutionEnvFactory`, `dockerExecutionEnvFactory`. + +**`packages/agent-spawn/src/spawn.ts`** — replace direct `child_process.spawn` with `runPoeCommand` + selected factory. Host factory keeps current behavior. + +**`packages/agent-spawn/src/spawn-interactive.ts`** — same migration; interactive uses `OpenedEnv.shell()` for tty. + +**`packages/experiment-loop/src/run/loop.ts`** — wrap inner agent invocations through the same path. + +**`packages/ralph/src/runtime/*`** — same. + +**`packages/superintendent/src/runtime/run-builder.ts`**, **`run-superintendent.ts`**, **`run-inspector.ts`**, **`run-owner-review.ts`** — same. + +**`packages/poe-code/src/commands/index.ts`** — register the `runtime` namespace. + +**`packages/poe-code/src/cli.ts`** (or wherever flags are wired) — universal flags `--runtime`, `--runtime-image`, `--runtime-template`, `--detach`, `--mount-poe-code` available on all four task commands. Surfaced via the design system (no `chalk` / `@clack/prompts` direct). + +**SDK callers** — same flags exposed in the SDK (per CLAUDE.md "CLI vs SDK" rule). + +**Each new/changed package's `README.md`** — env vars and config options, per CLAUDE.md package rules. + +### Function signatures (new / modified) + +```ts +// agent-harness-tools/src/run-poe-command.ts +export async function runPoeCommand(opts: { + factory: ExecutionEnvFactory; + openSpec: OpenSpec; + detach: boolean; + state: StateManager; + signal?: AbortSignal; +}): Promise; + +// agent-harness-tools/src/execution-env.ts +export function selectExecutionEnv(runtime: RuntimeConfig): ExecutionEnvFactory; +export function registerExecutionEnvFactory(f: ExecutionEnvFactory): void; + +// poe-code-config/src/runtime.ts +export function resolveRuntime(opts: { + cwd: string; + config: ResolvedConfig; +}): RuntimeResolveResult; + +// poe-code-config/src/state/index.ts +export async function loadStateManager(homeDir?: string): Promise; + +// process-runner/src/host/host-execution-env.ts +export const hostExecutionEnvFactory: ExecutionEnvFactory; + +// process-runner/src/docker/docker-execution-env.ts +export const dockerExecutionEnvFactory: ExecutionEnvFactory; + +// runner-e2b/src/index.ts +export const e2bExecutionEnvFactory: ExecutionEnvFactory; + +// runner-e2b/src/template-build.ts +export async function buildOrResolveTemplate(opts: { + runtime: E2bRuntime; + dockerfilePath: string; + buildContext: string; + state: StateManager; +}): Promise<{ templateId: string; cached: boolean }>; + +// agent-spawn/src/spawn.ts (modified) +export async function spawn(agentId: string, options: SpawnOptions): Promise; +// internally now goes through runPoeCommand +``` + +### Build order + +Each step keeps the branch green; nothing later than step 1 is a breaking change. + +1. **Config scopes + state manager** (`poe-code-config`) + - Add `runtime.ts`, `state/*`, schema, merge rules. + - Tests: parser, merge, registry CRUD with `memfs`. + - No callers wired yet. + +2. **Execution env contract + host factory** (`agent-harness-tools`, `process-runner`) + - Add `execution-env.ts`, `run-poe-command.ts`, `workspace-transfer.ts`, `log-stream.ts`. + - Add `hostExecutionEnvFactory` (no-op uploads, wraps existing `Runner`). + - Tests: mock factory + `runPoeCommand` flow. + +3. **Migrate `agent-spawn` to host factory** + - Replace `child_process.spawn` with `runPoeCommand` + host factory. + - Behavior bit-for-bit identical when `runtime.type === "host"`. + - Existing spawn tests pass unchanged. + +4. **Migrate `experiment-loop`, `ralph`, `superintendent`** + - Same pattern. No new behavior. + +5. **Universal CLI flags + `runtime init`** + - `--runtime`, `--detach`, `--mount-poe-code` wired on the four task commands and SDK. + - `poe-code runtime init` scaffolds Dockerfile + config. + +6. **Docker factory + template build path** (`process-runner`) + - `dockerExecutionEnvFactory`, image build from Dockerfile via `StateManager.templates`. + - `poe-code runtime build`, `runtime templates ls|clear`. + - Integration test gated on local docker. + +7. **e2b factory** (`runner-e2b` — new package) + - SDK wrapper, factory, opened-env, template build, job handle. + - Integration test gated on `E2B_API_KEY`. + +8. **Detach + jobs commands** + - State writes, log tee, attach/stream/wait reattach. + - `runtime jobs ls|attach|logs|stop|sandbox`. + +9. **Manual QA + screenshots + READMEs** + - QA markdown doc; design-system screenshots for the new commands; per-package READMEs. From 2211ba21a38e99f050a6d8218b4fa7bc11e95848 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 08:05:00 -0400 Subject: [PATCH 005/111] feat(config): add runtime config scope --- docs/plans/agent-human-in-loop.md.lock | 1 + docs/plans/e2b-integration.md | 7 +- docs/plans/e2b-integration.md.lock | 1 + packages/poe-code-config/src/index.ts | 13 + packages/poe-code-config/src/merge.ts | 59 ++- packages/poe-code-config/src/runtime.test.ts | 236 +++++++++++ packages/poe-code-config/src/runtime.ts | 394 ++++++++++++++++++ packages/poe-code-config/src/schema.ts | 2 + .../src/types.compile-check.ts | 20 +- packages/poe-code-config/src/types.ts | 21 +- 10 files changed, 739 insertions(+), 15 deletions(-) create mode 100644 docs/plans/agent-human-in-loop.md.lock create mode 100644 docs/plans/e2b-integration.md.lock create mode 100644 packages/poe-code-config/src/runtime.test.ts create mode 100644 packages/poe-code-config/src/runtime.ts diff --git a/docs/plans/agent-human-in-loop.md.lock b/docs/plans/agent-human-in-loop.md.lock new file mode 100644 index 0000000000..3e8780964c --- /dev/null +++ b/docs/plans/agent-human-in-loop.md.lock @@ -0,0 +1 @@ +{"pid":1345,"host":"m5mb-kjopek","acquiredAt":"2026-04-30T21:32:40.452Z"} \ No newline at end of file diff --git a/docs/plans/e2b-integration.md b/docs/plans/e2b-integration.md index dc72e92426..c92f5a7fc4 100644 --- a/docs/plans/e2b-integration.md +++ b/docs/plans/e2b-integration.md @@ -30,8 +30,8 @@ tasks: No regex parsing — deep-merge per the project rule. status: - implement: open - test: open + implement: done + test: done commit: open - id: config-runner-scope @@ -319,7 +319,8 @@ tasks: commit: open - id: cli-universal-flags - title: Add universal --runtime/--detach/--mount-poe-code flags to all four task commands + title: Add universal --runtime/--detach/--mount-poe-code flags to all four task + commands prompt: | Wire `--runtime host|docker|e2b`, `--runtime-image `, `--runtime-template `, `--detach`, `--mount-poe-code` on: diff --git a/docs/plans/e2b-integration.md.lock b/docs/plans/e2b-integration.md.lock new file mode 100644 index 0000000000..98f06c935c --- /dev/null +++ b/docs/plans/e2b-integration.md.lock @@ -0,0 +1 @@ +{"pid":1590,"host":"m5mb-kjopek","acquiredAt":"2026-05-03T12:03:16.600Z"} \ No newline at end of file diff --git a/packages/poe-code-config/src/index.ts b/packages/poe-code-config/src/index.ts index 016a2e0aab..752e9078fe 100644 --- a/packages/poe-code-config/src/index.ts +++ b/packages/poe-code-config/src/index.ts @@ -9,6 +9,7 @@ export type { MemoryConfig, MemoryMcpConfig, MemoryQueryConfig, + ResolvedConfig, SchemaField, ScopeDefinition, ScopedConfig, @@ -17,6 +18,18 @@ export type { } from "./types.js"; export { defineScope } from "./schema.js"; +export { + parseRuntime, + resolveRuntime, + runtimeConfigScope, + type DockerRuntime, + type E2bRuntime, + type HostRuntime, + type RuntimeConfig, + type RuntimeMount, + type RuntimeResolveResult, + type RuntimeRunner +} from "./runtime.js"; export { planConfigScope } from "./plan-scope.js"; export { createConfigStore } from "./config.js"; export { deepMergeDocuments } from "./merge.js"; diff --git a/packages/poe-code-config/src/merge.ts b/packages/poe-code-config/src/merge.ts index 9f972f8da1..0f93196af0 100644 --- a/packages/poe-code-config/src/merge.ts +++ b/packages/poe-code-config/src/merge.ts @@ -7,11 +7,7 @@ export function deepMergeDocuments(base: ConfigDocument, override: ConfigDocumen for (const scope of scopes) { const baseScope = base[scope] ?? {}; const overrideScope = override[scope] ?? {}; - const scopeEntries = Object.entries(overrideScope).filter(([, value]) => value !== undefined); - const nextScope = { - ...baseScope, - ...Object.fromEntries(scopeEntries) - }; + const nextScope = mergeScope(scope, baseScope, overrideScope); if (Object.keys(nextScope).length > 0) { merged[scope] = nextScope; @@ -20,3 +16,56 @@ export function deepMergeDocuments(base: ConfigDocument, override: ConfigDocumen return merged; } + +function mergeScope( + scope: string, + baseScope: Record, + overrideScope: Record +): Record { + if (scope === "runtime") { + return mergeRuntimeScope(baseScope, overrideScope); + } + + const scopeEntries = Object.entries(overrideScope).filter(([, value]) => value !== undefined); + return { + ...baseScope, + ...Object.fromEntries(scopeEntries) + }; +} + +function mergeRuntimeScope( + baseScope: Record, + overrideScope: Record +): Record { + const merged: Record = {}; + const keys = new Set([...Object.keys(baseScope), ...Object.keys(overrideScope)]); + + for (const key of keys) { + const baseValue = baseScope[key]; + const overrideValue = overrideScope[key]; + if (overrideValue === undefined) { + if (baseValue !== undefined) { + merged[key] = baseValue; + } + continue; + } + + if (key === "mounts" && Array.isArray(baseValue) && Array.isArray(overrideValue)) { + merged[key] = [...baseValue, ...overrideValue]; + continue; + } + + if (isRecord(baseValue) && isRecord(overrideValue)) { + merged[key] = mergeRuntimeScope(baseValue, overrideValue); + continue; + } + + merged[key] = overrideValue; + } + + return merged; +} + +function isRecord(value: unknown): value is Record { + return Boolean(value && typeof value === "object" && !Array.isArray(value)); +} diff --git a/packages/poe-code-config/src/runtime.test.ts b/packages/poe-code-config/src/runtime.test.ts new file mode 100644 index 0000000000..a73de97ab3 --- /dev/null +++ b/packages/poe-code-config/src/runtime.test.ts @@ -0,0 +1,236 @@ +import path from "node:path"; +import { describe, expect, it, vi } from "vitest"; +import { deepMergeDocuments } from "./merge.js"; +import { parseRuntime, resolveRuntime, runtimeConfigScope } from "./runtime.js"; +import { resolveScope } from "./resolve.js"; + +const existsSyncMock = vi.hoisted(() => vi.fn<(filePath: string) => boolean>()); + +vi.mock("node:fs", () => ({ + existsSync: existsSyncMock +})); + +describe("runtime config", () => { + it("defaults to the host runtime", () => { + expect(parseRuntime(undefined)).toEqual({ + type: "host", + build_args: {}, + mounts: [] + }); + }); + + it("rejects invalid runtime values", () => { + expect(() => parseRuntime(null)).toThrow("runtime: expected an object."); + expect(() => parseRuntime("docker")).toThrow("runtime: expected an object."); + expect(() => parseRuntime({ type: "container" })).toThrow( + 'type: expected "host", "docker", or "e2b".' + ); + }); + + it("parses docker runtime fields", () => { + expect( + parseRuntime({ + type: "docker", + image: "node:22", + build_args: { NODE_VERSION: "22" }, + mounts: [{ source: ".", target: "/workspace", readonly: true }], + link: "https://example.test/dockerfile", + engine: "podman", + network: "host", + extra_args: ["--gpus", "all"] + }) + ).toEqual({ + type: "docker", + image: "node:22", + build_args: { NODE_VERSION: "22" }, + mounts: [{ source: ".", target: "/workspace", readonly: true }], + link: "https://example.test/dockerfile", + engine: "podman", + network: "host", + extra_args: ["--gpus", "all"] + }); + }); + + it("applies e2b defaults and validates preserve range", () => { + expect(parseRuntime({ type: "e2b", template_id: "tmpl_123" })).toEqual({ + type: "e2b", + template_id: "tmpl_123", + build_args: {}, + mounts: [], + preserve_after_exit_hours: 24, + api_key_env: "E2B_API_KEY" + }); + + expect( + parseRuntime({ + type: "e2b", + template_id: "tmpl_123", + cpu: 4, + memory_mb: 8192, + timeout_minutes: 60, + preserve_after_exit_hours: 168, + api_key_env: "CUSTOM_E2B_API_KEY" + }) + ).toMatchObject({ + type: "e2b", + cpu: 4, + memory_mb: 8192, + timeout_minutes: 60, + preserve_after_exit_hours: 168, + api_key_env: "CUSTOM_E2B_API_KEY" + }); + + expect(() => + parseRuntime({ type: "e2b", template_id: "tmpl_123", preserve_after_exit_hours: 169 }) + ).toThrow("preserve_after_exit_hours: expected a number from 0 to 168"); + }); + + it("resolves dockerfile and build context defaults when a docker runtime builds from a Dockerfile", () => { + existsSyncMock.mockReturnValueOnce(true); + const cwd = "/repo"; + + expect(resolveRuntime({ cwd, config: { runtime: parseRuntime({ type: "docker" }) } })).toEqual({ + runtime: { + type: "docker", + build_args: {}, + mounts: [] + }, + runner: "docker", + dockerfilePath: path.join(cwd, ".poe-code", "Dockerfile"), + buildContext: cwd + }); + expect(existsSyncMock).toHaveBeenCalledWith(path.join(cwd, ".poe-code", "Dockerfile")); + }); + + it("resolves custom dockerfile and build context paths", () => { + existsSyncMock.mockReturnValueOnce(true).mockReturnValueOnce(true); + + expect( + resolveRuntime({ + cwd: "/repo", + config: { + runtime: parseRuntime({ + type: "docker", + dockerfile: "containers/Dockerfile", + build_context: "containers" + }) + } + }) + ).toMatchObject({ + runner: "docker", + dockerfilePath: "/repo/containers/Dockerfile", + buildContext: "/repo/containers" + }); + + expect( + resolveRuntime({ + cwd: "/repo", + config: { + runtime: parseRuntime({ + type: "e2b", + dockerfile: "/tmp/runtime.Dockerfile", + build_context: "/tmp/context" + }) + } + }) + ).toMatchObject({ + runner: "e2b", + dockerfilePath: "/tmp/runtime.Dockerfile", + buildContext: "/tmp/context" + }); + }); + + it("uses prebuilt docker and e2b artifacts without requiring a Dockerfile", () => { + existsSyncMock.mockReturnValue(false); + + expect( + resolveRuntime({ + cwd: "/repo", + config: { runtime: parseRuntime({ type: "docker", image: "node:22" }) } + }) + ).toMatchObject({ + runner: "docker", + dockerfilePath: null, + buildContext: null + }); + + expect( + resolveRuntime({ + cwd: "/repo", + config: { runtime: parseRuntime({ type: "e2b", template_id: "tmpl_123" }) } + }) + ).toMatchObject({ + runner: "e2b", + dockerfilePath: null, + buildContext: null + }); + }); + + it("hard-errors when docker or e2b has neither a prebuilt artifact nor Dockerfile", () => { + existsSyncMock.mockReturnValue(false); + + expect(() => + resolveRuntime({ cwd: "/repo", config: { runtime: parseRuntime({ type: "docker" }) } }) + ).toThrow("Docker runtime requires image or a Dockerfile at /repo/.poe-code/Dockerfile."); + + expect(() => + resolveRuntime({ cwd: "/repo", config: { runtime: parseRuntime({ type: "e2b" }) } }) + ).toThrow("E2B runtime requires template_id or a Dockerfile at /repo/.poe-code/Dockerfile."); + }); + + it("exposes a runtime scope with direct runtime fields", () => { + expect( + parseRuntime( + resolveScope( + runtimeConfigScope.schema, + { + type: "e2b", + template_id: "tmpl_123", + preserve_after_exit_hours: 0 + }, + {} + ) + ) + ).toEqual({ + type: "e2b", + template_id: "tmpl_123", + build_args: {}, + mounts: [], + preserve_after_exit_hours: 0, + api_key_env: "E2B_API_KEY" + }); + }); + + it("deep-merges runtime config with mount concatenation", () => { + expect( + deepMergeDocuments( + { + runtime: { + type: "docker", + build_args: { NODE_VERSION: "22" }, + mounts: [{ source: "~/.ssh", target: "/root/.ssh", readonly: true }], + engine: "docker" + } + }, + { + runtime: { + build_args: { PACKAGE_MANAGER: "npm" }, + mounts: [{ source: ".", target: "/workspace" }], + network: "host" + } + } + ) + ).toEqual({ + runtime: { + type: "docker", + build_args: { NODE_VERSION: "22", PACKAGE_MANAGER: "npm" }, + mounts: [ + { source: "~/.ssh", target: "/root/.ssh", readonly: true }, + { source: ".", target: "/workspace" } + ], + engine: "docker", + network: "host" + } + }); + }); +}); diff --git a/packages/poe-code-config/src/runtime.ts b/packages/poe-code-config/src/runtime.ts new file mode 100644 index 0000000000..868b13430a --- /dev/null +++ b/packages/poe-code-config/src/runtime.ts @@ -0,0 +1,394 @@ +import { existsSync } from "node:fs"; +import path from "node:path"; +import type { ResolvedConfig, SchemaField, ScopeDefinition } from "./types.js"; + +export interface RuntimeMount { + source: string; + target: string; + readonly?: boolean; +} + +interface SharedRuntimeFields { + build_args: Record; + mounts: RuntimeMount[]; + link?: string; +} + +export interface HostRuntime extends SharedRuntimeFields { + type: "host"; +} + +export interface DockerRuntime extends SharedRuntimeFields { + type: "docker"; + image?: string; + dockerfile?: string; + build_context?: string; + engine?: "docker" | "podman"; + network?: string; + extra_args?: string[]; +} + +export interface E2bRuntime extends SharedRuntimeFields { + type: "e2b"; + template_id?: string; + dockerfile?: string; + build_context?: string; + cpu?: number; + memory_mb?: number; + timeout_minutes?: number; + preserve_after_exit_hours?: number; + api_key_env?: string; +} + +export type RuntimeConfig = HostRuntime | DockerRuntime | E2bRuntime; +export type RuntimeRunner = RuntimeConfig["type"]; + +export interface RuntimeResolveResult { + runtime: RuntimeConfig; + runner: RuntimeRunner; + dockerfilePath: string | null; + buildContext: string | null; +} + +export const runtimeConfigScope = { + scope: "runtime", + schema: { + type: { + type: "string", + default: "host", + doc: "Runtime backend: host, docker, or e2b" + }, + build_args: { + type: "json", + default: {} as Record, + parse: parseBuildArgs, + doc: "Build arguments passed to the runtime image build" + }, + mounts: { + type: "json", + default: [] as RuntimeMount[], + parse: parseMounts, + doc: "Additional runtime mounts" + }, + link: { + type: "string", + default: "", + doc: "Informational link for the runtime definition" + }, + image: { + type: "string", + default: "", + doc: "Prebuilt Docker image" + }, + dockerfile: { + type: "string", + default: "", + doc: "Path to the Dockerfile used for docker or e2b builds" + }, + build_context: { + type: "string", + default: "", + doc: "Path to the Docker build context" + }, + engine: { + type: "string", + default: "", + doc: "Container engine for Docker runtime" + }, + network: { + type: "string", + default: "", + doc: "Docker network" + }, + extra_args: { + type: "json", + default: undefined as string[] | undefined, + parse: parseOptionalStringArray, + doc: "Extra Docker runtime arguments" + }, + template_id: { + type: "string", + default: "", + doc: "Prebuilt E2B template id" + }, + cpu: { + type: "json", + default: undefined as number | undefined, + parse: parseOptionalNumber, + doc: "E2B CPU count" + }, + memory_mb: { + type: "json", + default: undefined as number | undefined, + parse: parseOptionalNumber, + doc: "E2B memory in megabytes" + }, + timeout_minutes: { + type: "json", + default: undefined as number | undefined, + parse: parseOptionalNumber, + doc: "E2B timeout in minutes" + }, + preserve_after_exit_hours: { + type: "json", + default: undefined as number | undefined, + parse: parseOptionalNumber, + doc: "Hours to keep an E2B sandbox alive after job exit" + }, + api_key_env: { + type: "string", + default: "", + doc: "Environment variable name containing the E2B API key" + } + } +} satisfies ScopeDefinition>; + +export function parseRuntime(raw: unknown): RuntimeConfig { + if (raw === undefined) { + return { + type: "host", + build_args: {}, + mounts: [] + }; + } + const record = asRecord(raw); + if (record === undefined) { + throw new Error("runtime: expected an object."); + } + const type = parseRuntimeType(record.type); + const shared = parseSharedRuntimeFields(record); + + if (type === "docker") { + return omitUndefined({ + ...shared, + type, + image: parseOptionalString(record.image), + dockerfile: parseOptionalString(record.dockerfile), + build_context: parseOptionalString(record.build_context), + engine: parseEngine(record.engine), + network: parseOptionalString(record.network), + extra_args: parseOptionalStringArray(record.extra_args) + }); + } + + if (type === "e2b") { + const preserveAfterExitHours = parseOptionalNumber(record.preserve_after_exit_hours) ?? 24; + if (preserveAfterExitHours < 0 || preserveAfterExitHours > 168) { + throw new Error("preserve_after_exit_hours: expected a number from 0 to 168."); + } + + return omitUndefined({ + ...shared, + type, + template_id: parseOptionalString(record.template_id), + dockerfile: parseOptionalString(record.dockerfile), + build_context: parseOptionalString(record.build_context), + cpu: parseOptionalNumber(record.cpu), + memory_mb: parseOptionalNumber(record.memory_mb), + timeout_minutes: parseOptionalNumber(record.timeout_minutes), + preserve_after_exit_hours: preserveAfterExitHours, + api_key_env: parseOptionalString(record.api_key_env) ?? "E2B_API_KEY" + }); + } + + return { + ...shared, + type + }; +} + +export function resolveRuntime({ + cwd, + config +}: { + cwd: string; + config: ResolvedConfig; +}): RuntimeResolveResult { + const runtime = config.runtime; + if (runtime.type === "host") { + return { + runtime, + runner: "host", + dockerfilePath: null, + buildContext: null + }; + } + + const dockerfilePath = path.resolve( + cwd, + runtime.dockerfile ?? path.join(".poe-code", "Dockerfile") + ); + const buildContext = path.resolve(cwd, runtime.build_context ?? "."); + + if (runtime.type === "docker") { + if (runtime.image !== undefined) { + return { + runtime, + runner: "docker", + dockerfilePath: null, + buildContext: null + }; + } + if (!existsSync(dockerfilePath)) { + throw new Error(`Docker runtime requires image or a Dockerfile at ${dockerfilePath}.`); + } + return { + runtime, + runner: "docker", + dockerfilePath, + buildContext + }; + } + + if (runtime.template_id !== undefined) { + return { + runtime, + runner: "e2b", + dockerfilePath: null, + buildContext: null + }; + } + if (!existsSync(dockerfilePath)) { + throw new Error(`E2B runtime requires template_id or a Dockerfile at ${dockerfilePath}.`); + } + return { + runtime, + runner: "e2b", + dockerfilePath, + buildContext + }; +} + +function parseSharedRuntimeFields(record: Record): SharedRuntimeFields { + return omitUndefined({ + build_args: parseBuildArgs(record.build_args), + mounts: parseMounts(record.mounts), + link: parseOptionalString(record.link) + }); +} + +function parseRuntimeType(value: unknown): RuntimeConfig["type"] { + if (value === undefined) { + return "host"; + } + if (value === "host" || value === "docker" || value === "e2b") { + return value; + } + throw new Error('type: expected "host", "docker", or "e2b".'); +} + +function parseBuildArgs(value: unknown): Record { + if (value === undefined) { + return {}; + } + const record = asRecord(value); + if (record === undefined) { + throw new Error("build_args: expected an object."); + } + + const parsed: Record = {}; + for (const [key, entry] of Object.entries(record)) { + if (typeof entry !== "string") { + throw new Error(`build_args.${key}: expected a string.`); + } + parsed[key] = entry; + } + return parsed; +} + +function parseMounts(value: unknown): RuntimeMount[] { + if (value === undefined) { + return []; + } + if (!Array.isArray(value)) { + throw new Error("mounts: expected an array."); + } + + return value.map((entry, index) => { + const record = asRecord(entry); + if (record === undefined) { + throw new Error(`mounts[${index}]: expected an object.`); + } + const source = record.source; + const target = record.target; + if (typeof source !== "string") { + throw new Error(`mounts[${index}].source: expected a string.`); + } + if (typeof target !== "string") { + throw new Error(`mounts[${index}].target: expected a string.`); + } + + return omitUndefined({ + source, + target, + readonly: parseOptionalBoolean(record.readonly, `mounts[${index}].readonly`) + }); + }); +} + +function parseOptionalString(value: unknown): string | undefined { + if (value === undefined) { + return undefined; + } + if (typeof value !== "string") { + throw new Error("expected a string."); + } + if (value.length === 0) { + return undefined; + } + return value; +} + +function parseOptionalStringArray(value: unknown): string[] | undefined { + if (value === undefined) { + return undefined; + } + if (!Array.isArray(value)) { + throw new Error("expected an array."); + } + return value.map((entry, index) => { + if (typeof entry !== "string") { + throw new Error(`[${index}]: expected a string.`); + } + return entry; + }); +} + +function parseEngine(value: unknown): "docker" | "podman" | undefined { + const engine = parseOptionalString(value); + if (engine === undefined || engine === "docker" || engine === "podman") { + return engine; + } + throw new Error('engine: expected "docker" or "podman".'); +} + +function parseOptionalNumber(value: unknown): number | undefined { + if (value === undefined) { + return undefined; + } + if (typeof value !== "number" || !Number.isFinite(value)) { + throw new Error("expected a finite number."); + } + return value; +} + +function parseOptionalBoolean(value: unknown, key: string): boolean | undefined { + if (value === undefined) { + return undefined; + } + if (typeof value !== "boolean") { + throw new Error(`${key}: expected a boolean.`); + } + return value; +} + +function asRecord(value: unknown): Record | undefined { + if (!value || typeof value !== "object" || Array.isArray(value)) { + return undefined; + } + return value as Record; +} + +function omitUndefined>(value: T): T { + return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined)) as T; +} diff --git a/packages/poe-code-config/src/schema.ts b/packages/poe-code-config/src/schema.ts index da59ce7b95..6a78cdf57f 100644 --- a/packages/poe-code-config/src/schema.ts +++ b/packages/poe-code-config/src/schema.ts @@ -9,3 +9,5 @@ export function defineScope( schema }; } + +export { runtimeConfigScope } from "./runtime.js"; diff --git a/packages/poe-code-config/src/types.compile-check.ts b/packages/poe-code-config/src/types.compile-check.ts index 084b3bf2df..49dd8445c3 100644 --- a/packages/poe-code-config/src/types.compile-check.ts +++ b/packages/poe-code-config/src/types.compile-check.ts @@ -1,4 +1,10 @@ -import type { ConfigDocument, InferConfig, MemoryConfig, ScopedConfig } from "./types.js"; +import type { + ConfigDocument, + InferConfig, + MemoryConfig, + ResolvedConfig, + ScopedConfig +} from "./types.js"; import { defineScope } from "./schema.js"; type AssertAssignable = true; @@ -83,3 +89,15 @@ type ignoredConfigDocumentMemoryEntry = AssertAssignable< models?: Record; } >; + +type ignoredResolvedConfigRuntime = AssertAssignable< + ResolvedConfig, + { + runtime: { + type: "host" | "docker" | "e2b"; + build_args: Record; + mounts: Array<{ source: string; target: string; readonly?: boolean }>; + link?: string; + }; + } +>; diff --git a/packages/poe-code-config/src/types.ts b/packages/poe-code-config/src/types.ts index 70a0a37759..ef31926812 100644 --- a/packages/poe-code-config/src/types.ts +++ b/packages/poe-code-config/src/types.ts @@ -1,4 +1,5 @@ import type { FileSystem } from "@poe-code/config-mutations"; +import type { RuntimeConfig } from "./runtime.js"; export type PrimitiveConfigFieldType = "string" | "number" | "boolean"; export type ConfigFieldType = PrimitiveConfigFieldType | "json"; @@ -9,7 +10,9 @@ export interface TypeMap { boolean: boolean; } -export interface PrimitiveSchemaField { +export interface PrimitiveSchemaField< + T extends PrimitiveConfigFieldType = PrimitiveConfigFieldType +> { type: T; default: TypeMap[T]; doc: string; @@ -26,11 +29,12 @@ export interface JsonSchemaField { export type SchemaField = PrimitiveSchemaField | JsonSchemaField; -export type InferSchemaField = T extends PrimitiveSchemaField - ? TypeMap[U] - : T extends JsonSchemaField - ? U - : never; +export type InferSchemaField = + T extends PrimitiveSchemaField + ? TypeMap[U] + : T extends JsonSchemaField + ? U + : never; export type ScopeSchema = Record; @@ -91,4 +95,9 @@ export interface ConfigStoreOptions { export type ConfigDocument = Record> & { memory?: MemoryConfig; + runtime?: Record; }; + +export interface ResolvedConfig { + runtime: RuntimeConfig; +} From c3ed3503dbfa95d85a36e62c72589ec01eaeeb9a Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 08:10:08 -0400 Subject: [PATCH 006/111] feat(config): add runner scope --- docs/plans/e2b-integration.md | 6 +- docs/plans/e2b-integration.md.lock | 2 +- packages/poe-code-config/src/index.ts | 2 + packages/poe-code-config/src/merge.ts | 15 +- packages/poe-code-config/src/runtime.test.ts | 178 +++++++++++++++++- packages/poe-code-config/src/runtime.ts | 98 +++++++++- .../src/types.compile-check.ts | 8 + packages/poe-code-config/src/types.ts | 3 +- 8 files changed, 293 insertions(+), 19 deletions(-) diff --git a/docs/plans/e2b-integration.md b/docs/plans/e2b-integration.md index c92f5a7fc4..4d6cdf3a62 100644 --- a/docs/plans/e2b-integration.md +++ b/docs/plans/e2b-integration.md @@ -32,7 +32,7 @@ tasks: status: implement: done test: done - commit: open + commit: done - id: config-runner-scope title: Add runner scope (per-invocation behavior) to poe-code-config @@ -51,8 +51,8 @@ tasks: Tests: parsing valid/invalid inputs; merge concat semantics; default application when scope absent. status: - implement: open - test: open + implement: done + test: done commit: open - id: config-state-manager diff --git a/docs/plans/e2b-integration.md.lock b/docs/plans/e2b-integration.md.lock index 98f06c935c..ee711006e7 100644 --- a/docs/plans/e2b-integration.md.lock +++ b/docs/plans/e2b-integration.md.lock @@ -1 +1 @@ -{"pid":1590,"host":"m5mb-kjopek","acquiredAt":"2026-05-03T12:03:16.600Z"} \ No newline at end of file +{"pid":1590,"host":"m5mb-kjopek","acquiredAt":"2026-05-03T12:09:17.078Z"} \ No newline at end of file diff --git a/packages/poe-code-config/src/index.ts b/packages/poe-code-config/src/index.ts index 752e9078fe..9b0d8427c1 100644 --- a/packages/poe-code-config/src/index.ts +++ b/packages/poe-code-config/src/index.ts @@ -19,12 +19,14 @@ export type { export { defineScope } from "./schema.js"; export { + parseRunner, parseRuntime, resolveRuntime, runtimeConfigScope, type DockerRuntime, type E2bRuntime, type HostRuntime, + type RunnerScope, type RuntimeConfig, type RuntimeMount, type RuntimeResolveResult, diff --git a/packages/poe-code-config/src/merge.ts b/packages/poe-code-config/src/merge.ts index 0f93196af0..7a1c58eb10 100644 --- a/packages/poe-code-config/src/merge.ts +++ b/packages/poe-code-config/src/merge.ts @@ -35,7 +35,8 @@ function mergeScope( function mergeRuntimeScope( baseScope: Record, - overrideScope: Record + overrideScope: Record, + path: string[] = [] ): Record { const merged: Record = {}; const keys = new Set([...Object.keys(baseScope), ...Object.keys(overrideScope)]); @@ -50,13 +51,17 @@ function mergeRuntimeScope( continue; } - if (key === "mounts" && Array.isArray(baseValue) && Array.isArray(overrideValue)) { + if ( + isRuntimeConcatenativeArray([...path, key]) && + Array.isArray(baseValue) && + Array.isArray(overrideValue) + ) { merged[key] = [...baseValue, ...overrideValue]; continue; } if (isRecord(baseValue) && isRecord(overrideValue)) { - merged[key] = mergeRuntimeScope(baseValue, overrideValue); + merged[key] = mergeRuntimeScope(baseValue, overrideValue, [...path, key]); continue; } @@ -66,6 +71,10 @@ function mergeRuntimeScope( return merged; } +function isRuntimeConcatenativeArray(path: string[]): boolean { + return path.join(".") === "mounts" || path.join(".") === "runner.workspace.exclude"; +} + function isRecord(value: unknown): value is Record { return Boolean(value && typeof value === "object" && !Array.isArray(value)); } diff --git a/packages/poe-code-config/src/runtime.test.ts b/packages/poe-code-config/src/runtime.test.ts index a73de97ab3..ad2a47d5c0 100644 --- a/packages/poe-code-config/src/runtime.test.ts +++ b/packages/poe-code-config/src/runtime.test.ts @@ -1,7 +1,7 @@ import path from "node:path"; import { describe, expect, it, vi } from "vitest"; import { deepMergeDocuments } from "./merge.js"; -import { parseRuntime, resolveRuntime, runtimeConfigScope } from "./runtime.js"; +import { parseRunner, parseRuntime, resolveRuntime, runtimeConfigScope } from "./runtime.js"; import { resolveScope } from "./resolve.js"; const existsSyncMock = vi.hoisted(() => vi.fn<(filePath: string) => boolean>()); @@ -27,6 +27,99 @@ describe("runtime config", () => { ); }); + it("defaults runner scope values when runtime scope is absent", () => { + expect(resolveScope(runtimeConfigScope.schema, undefined, {}).runner).toEqual({ + detach: false, + upload_max_file_mb: 100, + download_conflict: "refuse", + workspace: { + exclude: [".git", "node_modules", "dist", ".turbo", ".next", ".poe-code/state.json"] + } + }); + }); + + it("parses runner scope fields", () => { + expect( + parseRunner({ + detach: true, + upload_max_file_mb: 250, + download_conflict: "overwrite", + workspace: { + exclude: ["coverage", "tmp"] + } + }) + ).toEqual({ + detach: true, + upload_max_file_mb: 250, + download_conflict: "overwrite", + workspace: { + exclude: ["coverage", "tmp"] + } + }); + }); + + it("applies runner defaults for omitted nested fields", () => { + expect(parseRunner({})).toEqual({ + detach: false, + upload_max_file_mb: 100, + download_conflict: "refuse", + workspace: { + exclude: [".git", "node_modules", "dist", ".turbo", ".next", ".poe-code/state.json"] + } + }); + + expect(parseRunner({ workspace: {} })).toEqual({ + detach: false, + upload_max_file_mb: 100, + download_conflict: "refuse", + workspace: { + exclude: [".git", "node_modules", "dist", ".turbo", ".next", ".poe-code/state.json"] + } + }); + }); + + it("parses runner scope through the runtime schema", () => { + expect( + resolveScope( + runtimeConfigScope.schema, + { + runner: JSON.stringify({ + detach: true, + upload_max_file_mb: 1, + download_conflict: "overwrite", + workspace: { exclude: [] } + }) + }, + {} + ).runner + ).toEqual({ + detach: true, + upload_max_file_mb: 1, + download_conflict: "overwrite", + workspace: { + exclude: [] + } + }); + }); + + it("rejects invalid runner scope values", () => { + expect(() => parseRunner(null)).toThrow("runner: expected an object."); + expect(() => parseRunner({ detach: "yes" })).toThrow("runner.detach: expected a boolean."); + expect(() => parseRunner({ upload_max_file_mb: Number.POSITIVE_INFINITY })).toThrow( + "runner.upload_max_file_mb: expected a finite number." + ); + expect(() => parseRunner({ upload_max_file_mb: 0 })).toThrow( + "runner.upload_max_file_mb: expected a positive finite number." + ); + expect(() => parseRunner({ download_conflict: "merge" })).toThrow( + 'runner.download_conflict: expected "refuse" or "overwrite".' + ); + expect(() => parseRunner({ workspace: [] })).toThrow("runner.workspace: expected an object."); + expect(() => parseRunner({ workspace: { exclude: [".git", 42] } })).toThrow( + "runner.workspace.exclude[1]: expected a string." + ); + }); + it("parses docker runtime fields", () => { expect( parseRuntime({ @@ -201,7 +294,7 @@ describe("runtime config", () => { }); }); - it("deep-merges runtime config with mount concatenation", () => { + it("deep-merges runtime config with mount and workspace exclude concatenation", () => { expect( deepMergeDocuments( { @@ -209,14 +302,24 @@ describe("runtime config", () => { type: "docker", build_args: { NODE_VERSION: "22" }, mounts: [{ source: "~/.ssh", target: "/root/.ssh", readonly: true }], - engine: "docker" + engine: "docker", + runner: { + workspace: { + exclude: ["global-cache"] + } + } } }, { runtime: { build_args: { PACKAGE_MANAGER: "npm" }, mounts: [{ source: ".", target: "/workspace" }], - network: "host" + network: "host", + runner: { + workspace: { + exclude: ["project-cache"] + } + } } } ) @@ -229,7 +332,72 @@ describe("runtime config", () => { { source: ".", target: "/workspace" } ], engine: "docker", - network: "host" + network: "host", + runner: { + workspace: { + exclude: ["global-cache", "project-cache"] + } + } + } + }); + }); + + it("keeps one-sided runtime concat arrays when merging", () => { + expect( + deepMergeDocuments( + { + runtime: { + mounts: [{ source: "~/.cache", target: "/cache" }], + runner: { + workspace: { + exclude: ["global-cache"] + } + } + } + }, + { + runtime: { + runner: { + detach: true + } + } + } + ) + ).toEqual({ + runtime: { + mounts: [{ source: "~/.cache", target: "/cache" }], + runner: { + detach: true, + workspace: { + exclude: ["global-cache"] + } + } + } + }); + + expect( + deepMergeDocuments( + { runtime: { runner: { detach: false } } }, + { + runtime: { + mounts: [{ source: ".", target: "/workspace" }], + runner: { + workspace: { + exclude: ["project-cache"] + } + } + } + } + ) + ).toEqual({ + runtime: { + mounts: [{ source: ".", target: "/workspace" }], + runner: { + detach: false, + workspace: { + exclude: ["project-cache"] + } + } } }); }); diff --git a/packages/poe-code-config/src/runtime.ts b/packages/poe-code-config/src/runtime.ts index 868b13430a..ea0a82cbe2 100644 --- a/packages/poe-code-config/src/runtime.ts +++ b/packages/poe-code-config/src/runtime.ts @@ -8,6 +8,15 @@ export interface RuntimeMount { readonly?: boolean; } +export interface RunnerScope { + detach: boolean; + upload_max_file_mb: number; + download_conflict: "refuse" | "overwrite"; + workspace?: { + exclude?: string[]; + }; +} + interface SharedRuntimeFields { build_args: Record; mounts: RuntimeMount[]; @@ -43,6 +52,15 @@ export interface E2bRuntime extends SharedRuntimeFields { export type RuntimeConfig = HostRuntime | DockerRuntime | E2bRuntime; export type RuntimeRunner = RuntimeConfig["type"]; +const defaultWorkspaceExclude = [ + ".git", + "node_modules", + "dist", + ".turbo", + ".next", + ".poe-code/state.json" +]; + export interface RuntimeResolveResult { runtime: RuntimeConfig; runner: RuntimeRunner; @@ -70,6 +88,12 @@ export const runtimeConfigScope = { parse: parseMounts, doc: "Additional runtime mounts" }, + runner: { + type: "json", + default: createDefaultRunnerScope(), + parse: parseRunner, + doc: "Runner process and workspace transfer settings" + }, link: { type: "string", default: "", @@ -143,6 +167,29 @@ export const runtimeConfigScope = { } } satisfies ScopeDefinition>; +export function parseRunner(raw: unknown): RunnerScope { + if (raw === undefined) { + return createDefaultRunnerScope(); + } + const record = asRecord(raw); + if (record === undefined) { + throw new Error("runner: expected an object."); + } + + const uploadMaxFileMb = + parseOptionalNumber(record.upload_max_file_mb, "runner.upload_max_file_mb") ?? 100; + if (uploadMaxFileMb <= 0) { + throw new Error("runner.upload_max_file_mb: expected a positive finite number."); + } + + return omitUndefined({ + detach: parseOptionalBoolean(record.detach, "runner.detach") ?? false, + upload_max_file_mb: uploadMaxFileMb, + download_conflict: parseDownloadConflict(record.download_conflict), + workspace: parseRunnerWorkspace(record.workspace) + }); +} + export function parseRuntime(raw: unknown): RuntimeConfig { if (raw === undefined) { return { @@ -202,7 +249,7 @@ export function resolveRuntime({ config }: { cwd: string; - config: ResolvedConfig; + config: Pick; }): RuntimeResolveResult { const runtime = config.runtime; if (runtime.type === "host") { @@ -277,6 +324,45 @@ function parseRuntimeType(value: unknown): RuntimeConfig["type"] { throw new Error('type: expected "host", "docker", or "e2b".'); } +function createDefaultRunnerScope(): RunnerScope { + return { + detach: false, + upload_max_file_mb: 100, + download_conflict: "refuse", + workspace: { + exclude: [...defaultWorkspaceExclude] + } + }; +} + +function parseRunnerWorkspace(value: unknown): RunnerScope["workspace"] { + if (value === undefined) { + return { + exclude: [...defaultWorkspaceExclude] + }; + } + const record = asRecord(value); + if (record === undefined) { + throw new Error("runner.workspace: expected an object."); + } + + return { + exclude: parseOptionalStringArray(record.exclude, "runner.workspace.exclude") ?? [ + ...defaultWorkspaceExclude + ] + }; +} + +function parseDownloadConflict(value: unknown): RunnerScope["download_conflict"] { + if (value === undefined) { + return "refuse"; + } + if (value === "refuse" || value === "overwrite") { + return value; + } + throw new Error('runner.download_conflict: expected "refuse" or "overwrite".'); +} + function parseBuildArgs(value: unknown): Record { if (value === undefined) { return {}; @@ -339,16 +425,16 @@ function parseOptionalString(value: unknown): string | undefined { return value; } -function parseOptionalStringArray(value: unknown): string[] | undefined { +function parseOptionalStringArray(value: unknown, key = ""): string[] | undefined { if (value === undefined) { return undefined; } if (!Array.isArray(value)) { - throw new Error("expected an array."); + throw new Error(`${key ? `${key}: ` : ""}expected an array.`); } return value.map((entry, index) => { if (typeof entry !== "string") { - throw new Error(`[${index}]: expected a string.`); + throw new Error(`${key}[${index}]: expected a string.`); } return entry; }); @@ -362,12 +448,12 @@ function parseEngine(value: unknown): "docker" | "podman" | undefined { throw new Error('engine: expected "docker" or "podman".'); } -function parseOptionalNumber(value: unknown): number | undefined { +function parseOptionalNumber(value: unknown, key = ""): number | undefined { if (value === undefined) { return undefined; } if (typeof value !== "number" || !Number.isFinite(value)) { - throw new Error("expected a finite number."); + throw new Error(`${key ? `${key}: ` : ""}expected a finite number.`); } return value; } diff --git a/packages/poe-code-config/src/types.compile-check.ts b/packages/poe-code-config/src/types.compile-check.ts index 49dd8445c3..a4898aa02d 100644 --- a/packages/poe-code-config/src/types.compile-check.ts +++ b/packages/poe-code-config/src/types.compile-check.ts @@ -99,5 +99,13 @@ type ignoredResolvedConfigRuntime = AssertAssignable< mounts: Array<{ source: string; target: string; readonly?: boolean }>; link?: string; }; + runner: { + detach: boolean; + upload_max_file_mb: number; + download_conflict: "refuse" | "overwrite"; + workspace?: { + exclude?: string[]; + }; + }; } >; diff --git a/packages/poe-code-config/src/types.ts b/packages/poe-code-config/src/types.ts index ef31926812..8ff2ebf82a 100644 --- a/packages/poe-code-config/src/types.ts +++ b/packages/poe-code-config/src/types.ts @@ -1,5 +1,5 @@ import type { FileSystem } from "@poe-code/config-mutations"; -import type { RuntimeConfig } from "./runtime.js"; +import type { RunnerScope, RuntimeConfig } from "./runtime.js"; export type PrimitiveConfigFieldType = "string" | "number" | "boolean"; export type ConfigFieldType = PrimitiveConfigFieldType | "json"; @@ -100,4 +100,5 @@ export type ConfigDocument = Record> & { export interface ResolvedConfig { runtime: RuntimeConfig; + runner: RunnerScope; } From e198a005000bf816600fc66612406d7a0dbac5cc Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 08:17:59 -0400 Subject: [PATCH 007/111] feat(poe-code-config): add state manager registries --- docs/plans/e2b-integration.md | 8 +- docs/plans/e2b-integration.md.lock | 2 +- package-lock.json | 3 +- packages/poe-code-config/package.json | 3 +- packages/poe-code-config/src/index.ts | 12 + packages/poe-code-config/src/state/fs.ts | 31 +++ packages/poe-code-config/src/state/index.ts | 38 +++ packages/poe-code-config/src/state/jobs.ts | 256 ++++++++++++++++++ .../poe-code-config/src/state/state.test.ts | 217 +++++++++++++++ .../poe-code-config/src/state/templates.ts | 145 ++++++++++ 10 files changed, 708 insertions(+), 7 deletions(-) create mode 100644 packages/poe-code-config/src/state/fs.ts create mode 100644 packages/poe-code-config/src/state/index.ts create mode 100644 packages/poe-code-config/src/state/jobs.ts create mode 100644 packages/poe-code-config/src/state/state.test.ts create mode 100644 packages/poe-code-config/src/state/templates.ts diff --git a/docs/plans/e2b-integration.md b/docs/plans/e2b-integration.md index 4d6cdf3a62..ab4b2e4130 100644 --- a/docs/plans/e2b-integration.md +++ b/docs/plans/e2b-integration.md @@ -53,7 +53,7 @@ tasks: status: implement: done test: done - commit: open + commit: done - id: config-state-manager title: Add StateManager (templates + jobs) to poe-code-config @@ -81,9 +81,9 @@ tasks: invariants under file-lock; partial-write recovery; list filtering. No real fs writes in unit tests except snapshots. status: - implement: open - test: open - commit: open + implement: done + test: done + commit: done - id: harness-execution-env-contract title: Define ExecutionEnv contract in agent-harness-tools diff --git a/docs/plans/e2b-integration.md.lock b/docs/plans/e2b-integration.md.lock index ee711006e7..33ef5e2725 100644 --- a/docs/plans/e2b-integration.md.lock +++ b/docs/plans/e2b-integration.md.lock @@ -1 +1 @@ -{"pid":1590,"host":"m5mb-kjopek","acquiredAt":"2026-05-03T12:09:17.078Z"} \ No newline at end of file +{"pid":1590,"host":"m5mb-kjopek","acquiredAt":"2026-05-03T12:16:49.467Z"} \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index fdebdd54eb..0f20878a20 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7202,7 +7202,8 @@ "version": "0.0.1", "dependencies": { "@poe-code/config-extends": "*", - "@poe-code/config-mutations": "*" + "@poe-code/config-mutations": "*", + "@poe-code/file-lock": "*" } }, "packages/poe-oauth": { diff --git a/packages/poe-code-config/package.json b/packages/poe-code-config/package.json index 6db33569e0..4022e2cbd8 100644 --- a/packages/poe-code-config/package.json +++ b/packages/poe-code-config/package.json @@ -19,6 +19,7 @@ ], "dependencies": { "@poe-code/config-extends": "*", - "@poe-code/config-mutations": "*" + "@poe-code/config-mutations": "*", + "@poe-code/file-lock": "*" } } diff --git a/packages/poe-code-config/src/index.ts b/packages/poe-code-config/src/index.ts index 9b0d8427c1..d24816342e 100644 --- a/packages/poe-code-config/src/index.ts +++ b/packages/poe-code-config/src/index.ts @@ -67,3 +67,15 @@ export { resolveProjectConfigPath, writeScope } from "./store.js"; +export { + createStateManager, + loadStateManager, + type JobEntry, + type JobListFilter, + type JobRegistry, + type JobStatus, + type StateManager, + type TemplateBackend, + type TemplateEntry, + type TemplateRegistry +} from "./state/index.js"; diff --git a/packages/poe-code-config/src/state/fs.ts b/packages/poe-code-config/src/state/fs.ts new file mode 100644 index 0000000000..a19ae746f0 --- /dev/null +++ b/packages/poe-code-config/src/state/fs.ts @@ -0,0 +1,31 @@ +import * as nodeFs from "node:fs/promises"; + +export interface StateFileSystem { + mkdir(path: string, options: { recursive: true }): Promise; + readFile(path: string, encoding: BufferEncoding): Promise; + writeFile( + path: string, + data: string, + options?: BufferEncoding | { encoding?: BufferEncoding } + ): Promise; + rename(oldPath: string, newPath: string): Promise; + readdir(path: string): Promise; + stat(path: string): Promise<{ + isFile(): boolean; + mtimeMs: number; + }>; + unlink(path: string): Promise; + open(path: string, flags: string): Promise<{ + close(): Promise; + writeFile( + data: string, + options?: BufferEncoding | { encoding?: BufferEncoding } + ): Promise; + }>; +} + +export const defaultStateFs = nodeFs as unknown as StateFileSystem; + +export function isNotFoundError(error: unknown): boolean { + return error instanceof Error && "code" in error && error.code === "ENOENT"; +} diff --git a/packages/poe-code-config/src/state/index.ts b/packages/poe-code-config/src/state/index.ts new file mode 100644 index 0000000000..bea0eef0c3 --- /dev/null +++ b/packages/poe-code-config/src/state/index.ts @@ -0,0 +1,38 @@ +import os from "node:os"; +import { createJobRegistry, type JobRegistry } from "./jobs.js"; +import { createTemplateRegistry, type TemplateRegistry } from "./templates.js"; +import type { StateFileSystem } from "./fs.js"; + +export interface StateManager { + templates: TemplateRegistry; + jobs: JobRegistry; +} + +export async function loadStateManager(homeDir: string = os.homedir()): Promise { + return { + templates: createTemplateRegistry(homeDir), + jobs: createJobRegistry(homeDir) + }; +} + +export function createStateManager(homeDir: string, fs?: StateFileSystem): StateManager { + return { + templates: createTemplateRegistry(homeDir, fs), + jobs: createJobRegistry(homeDir, fs) + }; +} + +export { + createJobRegistry, + type JobEntry, + type JobListFilter, + type JobRegistry, + type JobStatus +} from "./jobs.js"; +export { + createTemplateRegistry, + type TemplateBackend, + type TemplateEntry, + type TemplateRegistry +} from "./templates.js"; +export type { StateFileSystem } from "./fs.js"; diff --git a/packages/poe-code-config/src/state/jobs.ts b/packages/poe-code-config/src/state/jobs.ts new file mode 100644 index 0000000000..93df3198a1 --- /dev/null +++ b/packages/poe-code-config/src/state/jobs.ts @@ -0,0 +1,256 @@ +import path from "node:path"; +import { acquireFileLock, type FileLockFs } from "@poe-code/file-lock"; +import { defaultStateFs, isNotFoundError, type StateFileSystem } from "./fs.js"; + +export type JobStatus = "pending" | "running" | "exited" | "killed" | "lost"; + +export interface JobEntry { + id: string; + env_id: string; + env_kind: string; + tool: string; + argv: string[]; + cwd: string; + started_at: string; + status: JobStatus; + exit_code?: number; + exited_at?: string; + log_file?: string; +} + +export interface JobListFilter { + env_id?: string; + env_kind?: string; + tool?: string; + status?: JobStatus; +} + +export interface JobRegistry { + get(id: string): Promise; + put(entry: JobEntry): Promise; + update(id: string, patch: Partial): Promise; + list(filter?: JobListFilter): Promise; + remove(id: string): Promise; +} + +export function createJobRegistry( + homeDir: string, + fs: StateFileSystem = defaultStateFs +): JobRegistry { + const jobsDir = path.join(homeDir, ".poe-code", "state", "jobs"); + + function jobPath(id: string): string { + assertSafeJobId(id); + return path.join(jobsDir, `${id}.json`); + } + + async function get(id: string): Promise { + try { + return parseJobEntry(await fs.readFile(jobPath(id), "utf8")); + } catch (error) { + if (isNotFoundError(error)) { + return null; + } + + throw error; + } + } + + async function put(entry: JobEntry): Promise { + assertJobEntry(entry); + const filePath = jobPath(entry.id); + await fs.mkdir(jobsDir, { recursive: true }); + const release = await acquireFileLock(filePath, { fs: fs as unknown as FileLockFs }); + try { + await writeJobAtomically(filePath, entry); + } finally { + await release(); + } + } + + async function update(id: string, patch: Partial): Promise { + const filePath = jobPath(id); + await fs.mkdir(jobsDir, { recursive: true }); + const release = await acquireFileLock(filePath, { fs: fs as unknown as FileLockFs }); + try { + const current = await get(id); + if (current === null) { + return null; + } + + const updated = { + ...current, + ...patch, + id: current.id + }; + assertJobEntry(updated); + await writeJobAtomically(filePath, updated); + return updated; + } finally { + await release(); + } + } + + async function list(filter: JobListFilter = {}): Promise { + let entries: string[]; + + try { + entries = await fs.readdir(jobsDir); + } catch (error) { + if (isNotFoundError(error)) { + return []; + } + + throw error; + } + + const jobs: JobEntry[] = []; + for (const entry of entries.sort()) { + if (!entry.endsWith(".json")) { + continue; + } + + const filePath = path.join(jobsDir, entry); + const stat = await fs.stat(filePath); + if (!stat.isFile()) { + continue; + } + + const job = parseJobEntry(await fs.readFile(filePath, "utf8")); + if (matchesFilter(job, filter)) { + jobs.push(job); + } + } + return jobs; + } + + async function remove(id: string): Promise { + const filePath = jobPath(id); + try { + await fs.stat(jobsDir); + } catch (error) { + if (isNotFoundError(error)) { + return; + } + + throw error; + } + + const release = await acquireFileLock(filePath, { fs: fs as unknown as FileLockFs }); + try { + await fs.unlink(filePath); + } catch (error) { + if (!isNotFoundError(error)) { + throw error; + } + } finally { + await release(); + } + } + + async function writeJobAtomically(filePath: string, entry: JobEntry): Promise { + await fs.mkdir(path.dirname(filePath), { recursive: true }); + const tempPath = `${filePath}.${process.pid}.${Date.now()}.${Math.random() + .toString(36) + .slice(2)}.tmp`; + + try { + await fs.writeFile(tempPath, `${JSON.stringify(entry, null, 2)}\n`, { + encoding: "utf8" + }); + await fs.rename(tempPath, filePath); + } catch (error) { + await removeTempFile(tempPath); + throw error; + } + } + + async function removeTempFile(tempPath: string): Promise { + try { + await fs.unlink(tempPath); + } catch (error) { + if (!isNotFoundError(error)) { + throw error; + } + } + } + + return { + get, + put, + update, + list, + remove + }; +} + +function assertSafeJobId(id: string): void { + if ( + id.length === 0 || + id === "." || + id === ".." || + path.isAbsolute(id) || + id.includes("/") || + id.includes("\\") || + id.includes("\0") + ) { + throw new Error("Invalid job id."); + } +} + +function assertJobEntry(entry: JobEntry): void { + if (!isJobEntry(entry)) { + throw new Error("Invalid job entry."); + } +} + +function matchesFilter(job: JobEntry, filter: JobListFilter): boolean { + return ( + (filter.env_id === undefined || job.env_id === filter.env_id) && + (filter.env_kind === undefined || job.env_kind === filter.env_kind) && + (filter.tool === undefined || job.tool === filter.tool) && + (filter.status === undefined || job.status === filter.status) + ); +} + +function parseJobEntry(content: string): JobEntry { + const parsed = JSON.parse(content) as unknown; + if (!isJobEntry(parsed)) { + throw new Error("Invalid job state file."); + } + return parsed; +} + +function isJobEntry(value: unknown): value is JobEntry { + return ( + isRecord(value) && + typeof value.id === "string" && + typeof value.env_id === "string" && + typeof value.env_kind === "string" && + typeof value.tool === "string" && + Array.isArray(value.argv) && + value.argv.every((arg) => typeof arg === "string") && + typeof value.cwd === "string" && + typeof value.started_at === "string" && + isJobStatus(value.status) && + (value.exit_code === undefined || typeof value.exit_code === "number") && + (value.exited_at === undefined || typeof value.exited_at === "string") && + (value.log_file === undefined || typeof value.log_file === "string") + ); +} + +function isJobStatus(value: unknown): value is JobStatus { + return ( + value === "pending" || + value === "running" || + value === "exited" || + value === "killed" || + value === "lost" + ); +} + +function isRecord(value: unknown): value is Record { + return Boolean(value && typeof value === "object" && !Array.isArray(value)); +} + +export type { StateFileSystem } from "./fs.js"; diff --git a/packages/poe-code-config/src/state/state.test.ts b/packages/poe-code-config/src/state/state.test.ts new file mode 100644 index 0000000000..8432c36f0c --- /dev/null +++ b/packages/poe-code-config/src/state/state.test.ts @@ -0,0 +1,217 @@ +import path from "node:path"; +import { createFsFromVolume, Volume } from "memfs"; +import { describe, expect, it } from "vitest"; +import { createJobRegistry, type JobEntry, type StateFileSystem } from "./jobs.js"; +import { createStateManager } from "./index.js"; +import { createTemplateRegistry, type TemplateEntry } from "./templates.js"; + +function createMemFs(files: Record = {}): StateFileSystem { + return createFsFromVolume(Volume.fromJSON(files, "/")).promises as unknown as StateFileSystem; +} + +function createTemplate(hash: string, overrides: Partial = {}): TemplateEntry { + return { + hash, + runtime_type: "docker", + dockerfile_path: `/repo/${hash}/Dockerfile`, + built_at: `2026-05-03T12:00:${hash.padStart(2, "0")}.000Z`, + image: `poe-code:${hash}`, + ...overrides + }; +} + +function createJob(id: string, overrides: Partial = {}): JobEntry { + return { + id, + env_id: `env-${id}`, + env_kind: "docker", + tool: "npm", + argv: ["run", "test"], + cwd: "/repo", + started_at: "2026-05-03T12:00:00.000Z", + status: "pending", + ...overrides + }; +} + +describe("state manager", () => { + it("loads template and job registries for the home directory", async () => { + const fs = createMemFs(); + const state = createStateManager("/home/tester", fs); + + await state.templates.put("docker", createTemplate("alpha")); + await state.jobs.put(createJob("job-1")); + + await expect(state.templates.get("docker", "alpha")).resolves.toMatchObject({ + hash: "alpha" + }); + await expect(state.jobs.get("job-1")).resolves.toMatchObject({ + id: "job-1" + }); + }); +}); + +describe("TemplateRegistry", () => { + it("serializes concurrent puts through the file lock", async () => { + const fs = createMemFs(); + const registry = createTemplateRegistry("/home/tester", fs); + const entries = Array.from({ length: 20 }, (_, index) => + createTemplate(String(index).padStart(2, "0")) + ); + + await Promise.all(entries.map((entry) => registry.put("docker", entry))); + + await expect(registry.list("docker")).resolves.toEqual(entries); + }); + + it("lists all backends or one backend", async () => { + const fs = createMemFs(); + const registry = createTemplateRegistry("/home/tester", fs); + const docker = createTemplate("docker-hash"); + const e2b = createTemplate("e2b-hash", { + runtime_type: "e2b", + template_id: "tpl_123", + image: undefined + }); + + await registry.put("docker", docker); + await registry.put("e2b", e2b); + + await expect(registry.list("docker")).resolves.toEqual([docker]); + await expect(registry.list()).resolves.toEqual([docker, e2b]); + }); + + it("removes a template by backend and hash", async () => { + const fs = createMemFs(); + const registry = createTemplateRegistry("/home/tester", fs); + + await registry.put("docker", createTemplate("alpha")); + await registry.remove("docker", "alpha"); + + await expect(registry.get("docker", "alpha")).resolves.toBeNull(); + }); + + it("ignores persisted templates stored under a mismatched hash key", async () => { + const templatesPath = path.join("/home/tester", ".poe-code", "state", "templates.json"); + const fs = createMemFs({ + [templatesPath]: `${JSON.stringify( + { + docker: { + alpha: createTemplate("bravo") + }, + e2b: {} + }, + null, + 2 + )}\n` + }); + const registry = createTemplateRegistry("/home/tester", fs); + + await expect(registry.get("docker", "alpha")).resolves.toBeNull(); + await expect(registry.list("docker")).resolves.toEqual([]); + }); +}); + +describe("JobRegistry", () => { + it("serializes concurrent updates through the file lock", async () => { + const fs = createMemFs(); + const registry = createJobRegistry("/home/tester", fs); + + await registry.put(createJob("job-1")); + await Promise.all([ + registry.update("job-1", { status: "running" }), + registry.update("job-1", { exit_code: 0 }), + registry.update("job-1", { exited_at: "2026-05-03T12:01:00.000Z" }), + registry.update("job-1", { log_file: "/logs/job-1.log" }) + ]); + + await expect(registry.get("job-1")).resolves.toEqual({ + ...createJob("job-1"), + status: "running", + exit_code: 0, + exited_at: "2026-05-03T12:01:00.000Z", + log_file: "/logs/job-1.log" + }); + }); + + it("ignores partial temp files left behind by interrupted atomic writes", async () => { + const job = createJob("job-1", { status: "running" }); + const jobsDir = path.join("/home/tester", ".poe-code", "state", "jobs"); + const fs = createMemFs({ + [path.join(jobsDir, "job-1.json")]: `${JSON.stringify(job, null, 2)}\n`, + [path.join(jobsDir, "job-1.json.tmp")]: "{" + }); + const registry = createJobRegistry("/home/tester", fs); + + await expect(registry.get("job-1")).resolves.toEqual(job); + await expect(registry.list()).resolves.toEqual([job]); + }); + + it("filters listed jobs by status, tool, env kind, and env id", async () => { + const fs = createMemFs(); + const registry = createJobRegistry("/home/tester", fs); + const runningNpm = createJob("running-npm", { status: "running" }); + const exitedNpm = createJob("exited-npm", { + status: "exited", + exit_code: 0, + exited_at: "2026-05-03T12:01:00.000Z" + }); + const runningNode = createJob("running-node", { + status: "running", + tool: "node", + env_kind: "e2b", + env_id: "env-special" + }); + + await registry.put(runningNpm); + await registry.put(exitedNpm); + await registry.put(runningNode); + + await expect(registry.list({ status: "running" })).resolves.toEqual([ + runningNode, + runningNpm + ]); + await expect(registry.list({ status: "running", tool: "node" })).resolves.toEqual([ + runningNode + ]); + await expect(registry.list({ env_kind: "e2b", env_id: "env-special" })).resolves.toEqual([ + runningNode + ]); + }); + + it("removes a job file", async () => { + const fs = createMemFs(); + const registry = createJobRegistry("/home/tester", fs); + + await registry.put(createJob("job-1")); + await registry.remove("job-1"); + + await expect(registry.get("job-1")).resolves.toBeNull(); + }); + + it("rejects job ids that would escape the jobs directory", async () => { + const fs = createMemFs(); + const registry = createJobRegistry("/home/tester", fs); + const escapedJob = createJob("../outside"); + + await expect(registry.put(escapedJob)).rejects.toThrow("Invalid job id."); + await expect(registry.get("../outside")).rejects.toThrow("Invalid job id."); + await expect(registry.update("../outside", { status: "running" })).rejects.toThrow( + "Invalid job id." + ); + await expect(registry.remove("../outside")).rejects.toThrow("Invalid job id."); + }); + + it("rejects invalid job updates without corrupting the stored job", async () => { + const fs = createMemFs(); + const registry = createJobRegistry("/home/tester", fs); + const job = createJob("job-1"); + + await registry.put(job); + await expect( + registry.update("job-1", { status: "finished" as JobEntry["status"] }) + ).rejects.toThrow("Invalid job entry."); + + await expect(registry.get("job-1")).resolves.toEqual(job); + }); +}); diff --git a/packages/poe-code-config/src/state/templates.ts b/packages/poe-code-config/src/state/templates.ts new file mode 100644 index 0000000000..526d403b16 --- /dev/null +++ b/packages/poe-code-config/src/state/templates.ts @@ -0,0 +1,145 @@ +import path from "node:path"; +import { acquireFileLock, type FileLockFs } from "@poe-code/file-lock"; +import { defaultStateFs, isNotFoundError, type StateFileSystem } from "./fs.js"; + +export type TemplateBackend = "docker" | "e2b"; + +export interface TemplateEntry { + hash: string; + template_id?: string; + image?: string; + runtime_type: string; + dockerfile_path: string; + built_at: string; +} + +type TemplateState = Record>; + +export interface TemplateRegistry { + get(backend: TemplateBackend, hash: string): Promise; + put(backend: TemplateBackend, entry: TemplateEntry): Promise; + remove(backend: TemplateBackend, hash: string): Promise; + list(backend?: TemplateBackend): Promise; +} + +export function createTemplateRegistry( + homeDir: string, + fs: StateFileSystem = defaultStateFs +): TemplateRegistry { + const filePath = path.join(homeDir, ".poe-code", "state", "templates.json"); + + async function readState(): Promise { + try { + const raw = await fs.readFile(filePath, "utf8"); + return normalizeTemplateState(JSON.parse(raw)); + } catch (error) { + if (isNotFoundError(error)) { + return createEmptyState(); + } + + throw error; + } + } + + async function writeState(state: TemplateState): Promise { + await fs.writeFile(filePath, `${JSON.stringify(state, null, 2)}\n`, { + encoding: "utf8" + }); + } + + async function updateState(mutator: (state: TemplateState) => void): Promise { + await fs.mkdir(path.dirname(filePath), { recursive: true }); + const release = await acquireFileLock(filePath, { fs: fs as unknown as FileLockFs }); + try { + const state = await readState(); + mutator(state); + await writeState(state); + } finally { + await release(); + } + } + + async function get(backend: TemplateBackend, hash: string): Promise { + const state = await readState(); + return state[backend][hash] ?? null; + } + + async function put(backend: TemplateBackend, entry: TemplateEntry): Promise { + await updateState((state) => { + state[backend][entry.hash] = entry; + }); + } + + async function remove(backend: TemplateBackend, hash: string): Promise { + await updateState((state) => { + delete state[backend][hash]; + }); + } + + async function list(backend?: TemplateBackend): Promise { + const state = await readState(); + const entries = + backend === undefined + ? [...Object.values(state.docker), ...Object.values(state.e2b)] + : Object.values(state[backend]); + + return entries.sort((left, right) => left.hash.localeCompare(right.hash)); + } + + return { + get, + put, + remove, + list + }; +} + +function createEmptyState(): TemplateState { + return { + docker: {}, + e2b: {} + }; +} + +function normalizeTemplateState(value: unknown): TemplateState { + if (!isRecord(value)) { + return createEmptyState(); + } + + return { + docker: normalizeTemplateEntries(value.docker), + e2b: normalizeTemplateEntries(value.e2b) + }; +} + +function normalizeTemplateEntries(value: unknown): Record { + if (!isRecord(value)) { + return {}; + } + + const entries: Record = {}; + for (const [hash, entry] of Object.entries(value)) { + if (isTemplateEntry(entry) && entry.hash === hash) { + entries[hash] = entry; + } + } + return entries; +} + +function isTemplateEntry(value: unknown): value is TemplateEntry { + return ( + isRecord(value) && + typeof value.hash === "string" && + typeof value.runtime_type === "string" && + typeof value.dockerfile_path === "string" && + typeof value.built_at === "string" && + (value.template_id === undefined || typeof value.template_id === "string") && + (value.image === undefined || typeof value.image === "string") + ); +} + +function isRecord(value: unknown): value is Record { + return Boolean(value && typeof value === "object" && !Array.isArray(value)); +} + +export type { StateFileSystem } from "./fs.js"; From ac7b688cec5e835b09695659b3af2407f388d9bb Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 08:23:56 -0400 Subject: [PATCH 008/111] feat: add execution environment registry --- docs/plans/e2b-integration.md | 4 +- docs/plans/e2b-integration.md.lock | 2 +- package-lock.json | 4 +- packages/agent-harness-tools/package.json | 4 +- .../src/execution-env.test.ts | 86 +++++++++++++++++++ .../agent-harness-tools/src/execution-env.ts | 77 +++++++++++++++++ packages/agent-harness-tools/src/index.ts | 1 + 7 files changed, 173 insertions(+), 5 deletions(-) create mode 100644 packages/agent-harness-tools/src/execution-env.test.ts create mode 100644 packages/agent-harness-tools/src/execution-env.ts diff --git a/docs/plans/e2b-integration.md b/docs/plans/e2b-integration.md index ab4b2e4130..e94bcd84ef 100644 --- a/docs/plans/e2b-integration.md +++ b/docs/plans/e2b-integration.md @@ -139,8 +139,8 @@ tasks: No SDK deps in this package. status: - implement: open - test: open + implement: done + test: done commit: open - id: harness-workspace-transfer diff --git a/docs/plans/e2b-integration.md.lock b/docs/plans/e2b-integration.md.lock index 33ef5e2725..e4155ad4c9 100644 --- a/docs/plans/e2b-integration.md.lock +++ b/docs/plans/e2b-integration.md.lock @@ -1 +1 @@ -{"pid":1590,"host":"m5mb-kjopek","acquiredAt":"2026-05-03T12:16:49.467Z"} \ No newline at end of file +{"pid":1590,"host":"m5mb-kjopek","acquiredAt":"2026-05-03T12:23:01.979Z"} \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 0f20878a20..c327951376 100644 --- a/package-lock.json +++ b/package-lock.json @@ -6970,7 +6970,9 @@ "dependencies": { "@poe-code/agent-defs": "*", "@poe-code/design-system": "*", - "@poe-code/file-lock": "*" + "@poe-code/file-lock": "*", + "@poe-code/poe-code-config": "*", + "@poe-code/process-runner": "*" } }, "packages/agent-human-in-loop": { diff --git a/packages/agent-harness-tools/package.json b/packages/agent-harness-tools/package.json index 15ba682fad..8e355d23c7 100644 --- a/packages/agent-harness-tools/package.json +++ b/packages/agent-harness-tools/package.json @@ -22,6 +22,8 @@ "dependencies": { "@poe-code/agent-defs": "*", "@poe-code/design-system": "*", - "@poe-code/file-lock": "*" + "@poe-code/file-lock": "*", + "@poe-code/poe-code-config": "*", + "@poe-code/process-runner": "*" } } diff --git a/packages/agent-harness-tools/src/execution-env.test.ts b/packages/agent-harness-tools/src/execution-env.test.ts new file mode 100644 index 0000000000..0927e15c1c --- /dev/null +++ b/packages/agent-harness-tools/src/execution-env.test.ts @@ -0,0 +1,86 @@ +import { promises as fs } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import type { RuntimeConfig } from "@poe-code/poe-code-config"; +import { describe, expect, it, vi } from "vitest"; +import type { ExecutionEnvFactory } from "./execution-env.js"; + +function runtime(type: RuntimeConfig["type"]): RuntimeConfig { + return { + type, + build_args: {}, + mounts: [] + } as RuntimeConfig; +} + +describe("execution env registry", () => { + async function freshRegistry() { + vi.resetModules(); + return import("./execution-env.js"); + } + + it.each(["host", "docker", "e2b"] as const)( + "selects a registered %s factory by runtime type", + async (type) => { + const { registerExecutionEnvFactory, selectExecutionEnv } = await freshRegistry(); + const factory = { + type + } as ExecutionEnvFactory; + + registerExecutionEnvFactory(factory); + + expect(selectExecutionEnv(runtime(type))).toBe(factory); + } + ); + + it("uses the latest registered factory for a runtime type", async () => { + const { registerExecutionEnvFactory, selectExecutionEnv } = await freshRegistry(); + const first = { + type: "docker" + } as ExecutionEnvFactory; + const second = { + type: "docker" + } as ExecutionEnvFactory; + + registerExecutionEnvFactory(first); + registerExecutionEnvFactory(second); + + expect(selectExecutionEnv(runtime("docker"))).toBe(second); + }); + + it("throws a clear error when no factory is registered for the runtime type", async () => { + const { selectExecutionEnv } = await freshRegistry(); + + expect(() => selectExecutionEnv(runtime("e2b"))).toThrow( + 'No execution environment factory registered for runtime type "e2b".' + ); + }); + + it("keeps runtime.type branching inside selectExecutionEnv", async () => { + const sourceRoot = path.dirname(fileURLToPath(import.meta.url)); + const entries = await fs.readdir(sourceRoot, { withFileTypes: true }); + const files = entries + .filter((entry) => entry.isFile()) + .map((entry) => entry.name) + .filter((name) => name.endsWith(".ts")) + .filter((name) => !name.endsWith(".test.ts")); + const branchSites: string[] = []; + + for (const file of files) { + const text = await fs.readFile(path.join(sourceRoot, file), "utf8"); + const lines = text.split("\n"); + lines.forEach((line, index) => { + if (line.includes("runtime.type")) { + branchSites.push(`${file}:${index + 1}:${line.trim()}`); + } + }); + } + + expect(branchSites).toMatchInlineSnapshot(` + [ + "execution-env.ts:70:const factory = executionEnvFactories.get(runtime.type);", + "execution-env.ts:73:\`No execution environment factory registered for runtime type "\${runtime.type}".\`", + ] + `); + }); +}); diff --git a/packages/agent-harness-tools/src/execution-env.ts b/packages/agent-harness-tools/src/execution-env.ts new file mode 100644 index 0000000000..73a61b9e0f --- /dev/null +++ b/packages/agent-harness-tools/src/execution-env.ts @@ -0,0 +1,77 @@ +import type { RuntimeConfig } from "@poe-code/poe-code-config"; +import type { RunHandle, RunSpec } from "@poe-code/process-runner"; + +export type { RuntimeConfig } from "@poe-code/poe-code-config"; +export type { RunHandle, RunSpec } from "@poe-code/process-runner"; + +export type ExecutionEnvType = "host" | "docker" | "e2b"; +export type JobStatus = "running" | "exited" | "killed" | "lost"; + +export interface ExecutionEnvFactory { + readonly type: ExecutionEnvType; + open(spec: OpenSpec): Promise; + attach(envId: string): Promise; +} + +export interface OpenSpec { + cwd: string; + runtime: RuntimeConfig; + env: Record; + uploadIgnoreFiles: string[]; + jobLabel: { tool: string; argv: string[] }; +} + +export interface UploadResult { + files: number; + bytes: number; + skipped: { path: string; bytes: number; reason: "max_size" }[]; +} + +export interface DownloadResult { + files: number; + bytes: number; + conflicts: { path: string; reason: "local_modified" }[]; +} + +export interface LogChunk { + byteOffset: number; + data: string; +} + +export interface OpenedEnv { + readonly id: string; + readonly job: JobHandle | null; + uploadWorkspace(): Promise; + downloadWorkspace(opts: { conflictPolicy: "refuse" | "overwrite" }): Promise; + exec(spec: RunSpec): RunHandle; + detach(): Promise; + shell(): RunHandle; + close(): Promise; +} + +export interface JobHandle { + readonly id: string; + readonly envId: string; + readonly tool: string; + readonly argv: string[]; + status(): Promise; + stream(opts?: { sinceByte?: number }): AsyncIterable; + wait(): Promise<{ exitCode: number }>; + kill(signal?: NodeJS.Signals): Promise; +} + +const executionEnvFactories = new Map(); + +export function registerExecutionEnvFactory(factory: ExecutionEnvFactory): void { + executionEnvFactories.set(factory.type, factory); +} + +export function selectExecutionEnv(runtime: RuntimeConfig): ExecutionEnvFactory { + const factory = executionEnvFactories.get(runtime.type); + if (factory === undefined) { + throw new Error( + `No execution environment factory registered for runtime type "${runtime.type}".` + ); + } + return factory; +} diff --git a/packages/agent-harness-tools/src/index.ts b/packages/agent-harness-tools/src/index.ts index bc41f24309..e4baab22c9 100644 --- a/packages/agent-harness-tools/src/index.ts +++ b/packages/agent-harness-tools/src/index.ts @@ -41,3 +41,4 @@ export { type ResolveRunLogDirOptions } from "./run-logs.js"; export { skillPlanConfigSection } from "./skill-config.js"; +export * from "./execution-env.js"; From 82cb0a33263582e29426a62d4c48c8b1d3992458 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 08:31:08 -0400 Subject: [PATCH 009/111] feat(agent-harness-tools): add workspace transfer helpers --- docs/plans/e2b-integration.md | 6 +- docs/plans/e2b-integration.md.lock | 2 +- packages/agent-harness-tools/src/index.ts | 1 + .../src/workspace-transfer.test.ts | 296 ++++++++++ .../src/workspace-transfer.ts | 518 ++++++++++++++++++ 5 files changed, 819 insertions(+), 4 deletions(-) create mode 100644 packages/agent-harness-tools/src/workspace-transfer.test.ts create mode 100644 packages/agent-harness-tools/src/workspace-transfer.ts diff --git a/docs/plans/e2b-integration.md b/docs/plans/e2b-integration.md index e94bcd84ef..ffa334ccd2 100644 --- a/docs/plans/e2b-integration.md +++ b/docs/plans/e2b-integration.md @@ -141,7 +141,7 @@ tasks: status: implement: done test: done - commit: open + commit: done - id: harness-workspace-transfer title: Implement workspace upload/download in agent-harness-tools @@ -169,8 +169,8 @@ tasks: additive poe-code-ignore, oversize skip, conflict refuse-and-list, overwrite path. No real fs. status: - implement: open - test: open + implement: done + test: done commit: open - id: harness-log-stream diff --git a/docs/plans/e2b-integration.md.lock b/docs/plans/e2b-integration.md.lock index e4155ad4c9..088394b4ae 100644 --- a/docs/plans/e2b-integration.md.lock +++ b/docs/plans/e2b-integration.md.lock @@ -1 +1 @@ -{"pid":1590,"host":"m5mb-kjopek","acquiredAt":"2026-05-03T12:23:01.979Z"} \ No newline at end of file +{"pid":1590,"host":"m5mb-kjopek","acquiredAt":"2026-05-03T12:30:02.437Z"} \ No newline at end of file diff --git a/packages/agent-harness-tools/src/index.ts b/packages/agent-harness-tools/src/index.ts index e4baab22c9..de17088122 100644 --- a/packages/agent-harness-tools/src/index.ts +++ b/packages/agent-harness-tools/src/index.ts @@ -42,3 +42,4 @@ export { } from "./run-logs.js"; export { skillPlanConfigSection } from "./skill-config.js"; export * from "./execution-env.js"; +export * from "./workspace-transfer.js"; diff --git a/packages/agent-harness-tools/src/workspace-transfer.test.ts b/packages/agent-harness-tools/src/workspace-transfer.test.ts new file mode 100644 index 0000000000..be093e4d2f --- /dev/null +++ b/packages/agent-harness-tools/src/workspace-transfer.test.ts @@ -0,0 +1,296 @@ +import { createFsFromVolume, Volume } from "memfs"; +import { describe, expect, it, vi } from "vitest"; +import { + downloadWorkspace, + uploadWorkspace, + type WorkspaceTransferEnv, + type WorkspaceTransferFileSystem +} from "./workspace-transfer.js"; + +function createFs(files: Record) { + const volume = Volume.fromJSON(files, "/"); + return createFsFromVolume(volume).promises as unknown as WorkspaceTransferFileSystem; +} + +function createEnv(files: Record): WorkspaceTransferEnv { + return { + cwd: "/repo", + uploadDir: "/upload", + workspaceDir: "/workspace", + fs: createFs(files), + remoteFs: createFs({}) + }; +} + +async function readRemote(env: WorkspaceTransferEnv, relativePath: string): Promise { + return env.remoteFs.readFile(`/workspace/${relativePath}`, "utf8") as Promise; +} + +async function expectNoRemote(env: WorkspaceTransferEnv, relativePath: string): Promise { + await expect(readRemote(env, relativePath)).rejects.toThrow(); +} + +describe("workspace transfer", () => { + it("applies gitignore precedence before uploading", async () => { + const env = createEnv({ + "/repo/.gitignore": "build/\n!build/keep.txt\n", + "/repo/build/drop.txt": "drop", + "/repo/build/keep.txt": "keep", + "/repo/src/app.ts": "app" + }); + + const result = await uploadWorkspace(env, {}); + + expect(result.files).toBe(3); + await expectNoRemote(env, "build/drop.txt"); + await expect(readRemote(env, "build/keep.txt")).resolves.toBe("keep"); + }); + + it("keeps poe-code-ignore additive and never un-ignores gitignored files", async () => { + const env = createEnv({ + "/repo/.gitignore": "secret.txt\n", + "/repo/.poe-code-ignore": "!secret.txt\nnotes.txt\n", + "/repo/secret.txt": "secret", + "/repo/notes.txt": "notes", + "/repo/src/app.ts": "app" + }); + + const result = await uploadWorkspace(env, {}); + + expect(result.files).toBe(3); + await expectNoRemote(env, "secret.txt"); + await expectNoRemote(env, "notes.txt"); + await expect(readRemote(env, "src/app.ts")).resolves.toBe("app"); + }); + + it("keeps poe-code-ignore additive even when it tries to unignore a nested gitignore include", async () => { + const env = createEnv({ + "/repo/.gitignore": "build/\n!build/keep.txt\n", + "/repo/.poe-code-ignore": "build/\n!build/keep.txt\n", + "/repo/build/keep.txt": "keep", + "/repo/src/app.ts": "app" + }); + + const result = await uploadWorkspace(env, {}); + + expect(result.files).toBe(3); + await expectNoRemote(env, "build/keep.txt"); + await expect(readRemote(env, "src/app.ts")).resolves.toBe("app"); + }); + + it("treats leading slash ignore patterns as cwd-anchored", async () => { + const env = createEnv({ + "/repo/.gitignore": "/root-only.txt\n", + "/repo/root-only.txt": "drop", + "/repo/nested/root-only.txt": "keep" + }); + + await uploadWorkspace(env, {}); + + await expectNoRemote(env, "root-only.txt"); + await expect(readRemote(env, "nested/root-only.txt")).resolves.toBe("keep"); + }); + + it("skips oversize files and prints one warning per skip", async () => { + const warn = vi.fn(); + const env = createEnv({ + "/repo/small.txt": "small", + "/repo/large.bin": Buffer.alloc(20) + }); + + const result = await uploadWorkspace(env, { + uploadMaxFileMb: 0.00001, + warn + }); + + expect(result).toEqual({ + files: 1, + bytes: 5, + skipped: [{ path: "large.bin", bytes: 20, reason: "max_size" }] + }); + expect(warn).toHaveBeenCalledTimes(1); + expect(warn).toHaveBeenCalledWith("Skipping large.bin: 20 bytes exceeds upload_max_file_mb."); + await expectNoRemote(env, "large.bin"); + }); + + it("applies runner workspace excludes", async () => { + const env = createEnv({ + "/repo/src/app.ts": "app", + "/repo/dist/app.js": "built" + }); + + const result = await uploadWorkspace(env, { + runner: { + detach: false, + upload_max_file_mb: 100, + download_conflict: "refuse", + workspace: { exclude: ["dist"] } + } + }); + + expect(result.files).toBe(1); + await expect(readRemote(env, "src/app.ts")).resolves.toBe("app"); + await expectNoRemote(env, "dist/app.js"); + }); + + it("writes a tar archive under uploadDir", async () => { + const env = createEnv({ + "/repo/src/app.ts": "app" + }); + + await uploadWorkspace(env, {}); + + const tar = await env.remoteFs.readFile("/upload/workspace.tar"); + expect(tar.subarray(0, "src/app.ts".length).toString("utf8")).toBe("src/app.ts"); + expect(tar.subarray(512, 515).toString("utf8")).toBe("app"); + }); + + it("downloads remote changes over unchanged local files", async () => { + const env = createEnv({ + "/repo/app.ts": "base" + }); + await uploadWorkspace(env, {}); + await env.remoteFs.writeFile("/workspace/app.ts", "remote"); + + const result = await downloadWorkspace(env, { conflictPolicy: "refuse" }); + + expect(result).toEqual({ + files: 1, + bytes: 6, + conflicts: [] + }); + await expect(env.fs.readFile("/repo/app.ts", "utf8")).resolves.toBe("remote"); + }); + + it("downloads new remote files when no local file exists", async () => { + const env = createEnv({ + "/repo/app.ts": "base" + }); + await uploadWorkspace(env, {}); + await env.remoteFs.writeFile("/workspace/new.ts", "new"); + + const result = await downloadWorkspace(env, { conflictPolicy: "refuse" }); + + expect(result.conflicts).toEqual([]); + await expect(env.fs.readFile("/repo/new.ts", "utf8")).resolves.toBe("new"); + }); + + it("conflicts when remote adds a path that local also created after upload", async () => { + const env = createEnv({ + "/repo/app.ts": "base" + }); + await uploadWorkspace(env, {}); + await env.fs.writeFile("/repo/new.ts", "local-new"); + await env.remoteFs.writeFile("/workspace/new.ts", "remote-new"); + + const result = await downloadWorkspace(env, { conflictPolicy: "refuse" }); + + expect(result.conflicts).toEqual([{ path: "new.ts", reason: "local_modified" }]); + await expect(env.fs.readFile("/repo/new.ts", "utf8")).resolves.toBe("local-new"); + }); + + it("does not conflict when remote adds a path with the same content local also created", async () => { + const env = createEnv({ + "/repo/app.ts": "base" + }); + await uploadWorkspace(env, {}); + await env.fs.writeFile("/repo/new.ts", "same"); + await env.remoteFs.writeFile("/workspace/new.ts", "same"); + + const result = await downloadWorkspace(env, { conflictPolicy: "refuse" }); + + expect(result.conflicts).toEqual([]); + await expect(env.fs.readFile("/repo/new.ts", "utf8")).resolves.toBe("same"); + }); + + it("refuses conflicting downloads and lists affected files", async () => { + const env = createEnv({ + "/repo/app.ts": "base", + "/repo/clean.ts": "base" + }); + await uploadWorkspace(env, {}); + await env.fs.writeFile("/repo/app.ts", "local"); + await env.remoteFs.writeFile("/workspace/app.ts", "remote"); + await env.remoteFs.writeFile("/workspace/clean.ts", "remote-clean"); + + const result = await downloadWorkspace(env, { conflictPolicy: "refuse" }); + + expect(result).toEqual({ + files: 1, + bytes: 12, + conflicts: [{ path: "app.ts", reason: "local_modified" }] + }); + await expect(env.fs.readFile("/repo/app.ts", "utf8")).resolves.toBe("local"); + await expect(env.fs.readFile("/repo/clean.ts", "utf8")).resolves.toBe("remote-clean"); + }); + + it("refuses to delete locally modified files removed remotely", async () => { + const env = createEnv({ + "/repo/app.ts": "base" + }); + await uploadWorkspace(env, {}); + await env.fs.writeFile("/repo/app.ts", "local"); + await env.remoteFs.rm?.("/workspace/app.ts", { force: true }); + + const result = await downloadWorkspace(env, { conflictPolicy: "refuse" }); + + expect(result).toEqual({ + files: 0, + bytes: 0, + conflicts: [{ path: "app.ts", reason: "local_modified" }] + }); + await expect(env.fs.readFile("/repo/app.ts", "utf8")).resolves.toBe("local"); + }); + + it("removes unchanged local files deleted remotely", async () => { + const env = createEnv({ + "/repo/app.ts": "base" + }); + await uploadWorkspace(env, {}); + await env.remoteFs.rm?.("/workspace/app.ts", { force: true }); + + const result = await downloadWorkspace(env, { conflictPolicy: "refuse" }); + + expect(result).toEqual({ + files: 0, + bytes: 0, + conflicts: [] + }); + await expect(env.fs.readFile("/repo/app.ts", "utf8")).rejects.toThrow(); + }); + + it("uses upload-time hashes for files skipped during upload", async () => { + const env = createEnv({ + "/repo/large.bin": Buffer.alloc(20, "a") + }); + await uploadWorkspace(env, { + uploadMaxFileMb: 0.00001, + warn: vi.fn() + }); + await env.fs.writeFile("/repo/large.bin", Buffer.alloc(20, "b")); + await env.remoteFs.writeFile("/workspace/large.bin", Buffer.alloc(20, "c")); + + const result = await downloadWorkspace(env, { conflictPolicy: "refuse" }); + + expect(result.conflicts).toEqual([{ path: "large.bin", reason: "local_modified" }]); + await expect(env.fs.readFile("/repo/large.bin")).resolves.toEqual(Buffer.alloc(20, "b")); + }); + + it("overwrites conflicting downloads when requested", async () => { + const env = createEnv({ + "/repo/app.ts": "base" + }); + await uploadWorkspace(env, {}); + await env.fs.writeFile("/repo/app.ts", "local"); + await env.remoteFs.writeFile("/workspace/app.ts", "remote"); + + const result = await downloadWorkspace(env, { conflictPolicy: "overwrite" }); + + expect(result).toEqual({ + files: 1, + bytes: 6, + conflicts: [] + }); + await expect(env.fs.readFile("/repo/app.ts", "utf8")).resolves.toBe("remote"); + }); +}); diff --git a/packages/agent-harness-tools/src/workspace-transfer.ts b/packages/agent-harness-tools/src/workspace-transfer.ts new file mode 100644 index 0000000000..35636a41be --- /dev/null +++ b/packages/agent-harness-tools/src/workspace-transfer.ts @@ -0,0 +1,518 @@ +import { createHash } from "node:crypto"; +import { promises as nodeFs } from "node:fs"; +import path from "node:path"; +import type { RunnerScope } from "@poe-code/poe-code-config"; +import type { DownloadResult, UploadResult } from "./execution-env.js"; + +export type { DownloadResult, UploadResult } from "./execution-env.js"; + +export interface WorkspaceTransferDirent { + name: string; + isFile(): boolean; + isDirectory(): boolean; +} + +export interface WorkspaceTransferStats { + isFile(): boolean; + isDirectory(): boolean; + size: number; +} + +export interface WorkspaceTransferFileSystem { + mkdir(path: string, options?: { recursive?: boolean }): Promise; + readdir(path: string, options: { withFileTypes: true }): Promise; + readFile(path: string): Promise; + readFile(path: string, encoding: BufferEncoding): Promise; + writeFile(path: string, data: string | Buffer): Promise; + stat(path: string): Promise; + rm?(path: string, options?: { recursive?: boolean; force?: boolean }): Promise; + unlink?(path: string): Promise; + rmdir?(path: string): Promise; +} + +export interface WorkspaceTransferEnv { + cwd: string; + uploadDir: string; + workspaceDir?: string; + fs?: WorkspaceTransferFileSystem; + remoteFs?: WorkspaceTransferFileSystem; +} + +export interface WorkspaceTransferOptions { + runner?: RunnerScope; + uploadMaxFileMb?: number; + workspaceExclude?: string[]; + warn?: (message: string) => void; +} + +export interface WorkspaceDownloadOptions { + conflictPolicy: "refuse" | "overwrite"; +} + +interface UploadedFileState { + hash: string; + uploaded: boolean; +} + +interface FileEntry { + path: string; + absolutePath: string; + bytes: number; + content: Buffer; +} + +interface IgnoreRule { + pattern: string; + negate: boolean; + directoryOnly: boolean; + anchored: boolean; +} + +const uploadState = new WeakMap>(); + +export async function uploadWorkspace( + env: WorkspaceTransferEnv, + opts: WorkspaceTransferOptions +): Promise { + const localFs = env.fs ?? (nodeFs as unknown as WorkspaceTransferFileSystem); + const remoteFs = env.remoteFs ?? localFs; + const workspaceDir = env.workspaceDir ?? "/workspace"; + const maxBytes = (opts.uploadMaxFileMb ?? opts.runner?.upload_max_file_mb ?? 100) * 1024 * 1024; + const warn = opts.warn ?? console.warn; + const allFiles = await listFiles(localFs, env.cwd); + const state = new Map(); + const gitignore = await readIgnoreFile(localFs, env.cwd, ".gitignore", true); + const poeCodeIgnore = await readIgnoreFile(localFs, env.cwd, ".poe-code-ignore", false); + const workspaceExclude = parseIgnoreLines( + [...(opts.runner?.workspace?.exclude ?? []), ...(opts.workspaceExclude ?? [])], + false + ); + const entries: FileEntry[] = []; + const skipped: UploadResult["skipped"] = []; + + for (const file of allFiles) { + const content = await localFs.readFile(file.absolutePath); + state.set(file.path, { + hash: hashBuffer(content), + uploaded: false + }); + + if ( + isIgnoredByGit(file.path, gitignore) || + isIgnoredAdditively(file.path, poeCodeIgnore) || + isIgnoredAdditively(file.path, workspaceExclude) + ) { + continue; + } + + if (file.bytes > maxBytes) { + skipped.push({ path: file.path, bytes: file.bytes, reason: "max_size" }); + warn(`Skipping ${file.path}: ${file.bytes} bytes exceeds upload_max_file_mb.`); + continue; + } + + entries.push({ ...file, content }); + state.set(file.path, { + hash: hashBuffer(content), + uploaded: true + }); + } + + await removeTree(remoteFs, workspaceDir); + await remoteFs.mkdir(workspaceDir, { recursive: true }); + await remoteFs.mkdir(env.uploadDir, { recursive: true }); + await remoteFs.writeFile(path.join(env.uploadDir, "workspace.tar"), createTar(entries)); + + for (const entry of entries) { + const remotePath = path.join(workspaceDir, entry.path); + await remoteFs.mkdir(path.dirname(remotePath), { recursive: true }); + await remoteFs.writeFile(remotePath, entry.content); + } + + uploadState.set(env, state); + + return { + files: entries.length, + bytes: entries.reduce((sum, entry) => sum + entry.bytes, 0), + skipped + }; +} + +export async function downloadWorkspace( + env: WorkspaceTransferEnv, + opts: WorkspaceDownloadOptions +): Promise { + const localFs = env.fs ?? (nodeFs as unknown as WorkspaceTransferFileSystem); + const remoteFs = env.remoteFs ?? localFs; + const workspaceDir = env.workspaceDir ?? "/workspace"; + const state = uploadState.get(env) ?? new Map(); + const remoteFiles = await listFilesIfExists(remoteFs, workspaceDir); + const remotePaths = new Set(remoteFiles.map((file) => file.path)); + const conflicts: DownloadResult["conflicts"] = []; + let files = 0; + let bytes = 0; + + for (const remoteFile of remoteFiles) { + const remoteContent = await remoteFs.readFile(remoteFile.absolutePath); + const localPath = path.join(env.cwd, remoteFile.path); + const conflict = await isDownloadConflict( + localFs, + localPath, + remoteFile.path, + remoteContent, + state + ); + + if (conflict && opts.conflictPolicy === "refuse") { + conflicts.push({ path: remoteFile.path, reason: "local_modified" }); + continue; + } + + await localFs.mkdir(path.dirname(localPath), { recursive: true }); + await localFs.writeFile(localPath, remoteContent); + state.set(remoteFile.path, { + hash: hashBuffer(remoteContent), + uploaded: true + }); + files += 1; + bytes += remoteContent.length; + } + + for (const [relativePath, fileState] of state) { + if (!fileState.uploaded || remotePaths.has(relativePath)) { + continue; + } + + const localPath = path.join(env.cwd, relativePath); + const localContent = await readFileIfExists(localFs, localPath); + if (localContent === null) { + continue; + } + + if (opts.conflictPolicy === "refuse" && hashBuffer(localContent) !== fileState.hash) { + conflicts.push({ path: relativePath, reason: "local_modified" }); + continue; + } + + await removeFile(localFs, localPath); + } + + return { files, bytes, conflicts }; +} + +async function listFilesIfExists( + fs: WorkspaceTransferFileSystem, + root: string +): Promise[]> { + try { + return await listFiles(fs, root); + } catch (error) { + if (isNotFoundError(error)) { + return []; + } + throw error; + } +} + +async function listFiles( + fs: WorkspaceTransferFileSystem, + root: string +): Promise[]> { + const result: Omit[] = []; + + async function visit(dir: string): Promise { + const dirents = await fs.readdir(dir, { withFileTypes: true }); + for (const dirent of dirents.sort((left, right) => left.name.localeCompare(right.name))) { + const absolutePath = path.join(dir, dirent.name); + if (dirent.isDirectory()) { + await visit(absolutePath); + continue; + } + if (!dirent.isFile()) { + continue; + } + + const stats = await fs.stat(absolutePath); + result.push({ + path: toRelativePath(root, absolutePath), + absolutePath, + bytes: stats.size + }); + } + } + + await visit(root); + return result; +} + +async function readIgnoreFile( + fs: WorkspaceTransferFileSystem, + cwd: string, + fileName: string, + allowNegation: boolean +): Promise { + const content = await readFileIfExists(fs, path.join(cwd, fileName)); + if (content === null) { + return []; + } + return parseIgnoreLines(content.toString("utf8").split("\n"), allowNegation); +} + +function parseIgnoreLines(lines: string[], allowNegation: boolean): IgnoreRule[] { + const rules: IgnoreRule[] = []; + for (const rawLine of lines) { + const line = rawLine.trim(); + if (line.length === 0 || line.startsWith("#")) { + continue; + } + + const negate = allowNegation && line.startsWith("!"); + const patternWithMarker = negate ? line.slice(1) : line; + if (patternWithMarker.length === 0) { + continue; + } + + const anchored = patternWithMarker.startsWith("/"); + const directoryOnly = patternWithMarker.endsWith("/"); + const pattern = stripSlashes( + directoryOnly ? patternWithMarker.slice(0, -1) : patternWithMarker + ); + if (pattern.length > 0) { + rules.push({ pattern, negate, directoryOnly, anchored }); + } + } + return rules; +} + +function isIgnoredByGit(relativePath: string, rules: IgnoreRule[]): boolean { + let ignored = false; + for (const rule of rules) { + if (matchesRule(relativePath, rule)) { + ignored = !rule.negate; + } + } + return ignored; +} + +function isIgnoredAdditively(relativePath: string, rules: IgnoreRule[]): boolean { + return rules.some((rule) => matchesRule(relativePath, rule)); +} + +function matchesRule(relativePath: string, rule: IgnoreRule): boolean { + const normalizedPath = normalizeRelativePath(relativePath); + const normalizedPattern = normalizeRelativePath(rule.pattern); + if (rule.directoryOnly) { + return pathMatchesDirectory(normalizedPath, normalizedPattern, rule.anchored); + } + + if (rule.anchored || normalizedPattern.includes("/")) { + return matchPathSegments(normalizedPath.split("/"), normalizedPattern.split("/")); + } + + return normalizedPath.split("/").some((segment) => matchSegment(segment, normalizedPattern)); +} + +function pathMatchesDirectory(relativePath: string, pattern: string, anchored: boolean): boolean { + if (anchored || pattern.includes("/")) { + return relativePath === pattern || relativePath.startsWith(`${pattern}/`); + } + + const segments = relativePath.split("/"); + return segments.some((segment, index) => { + return matchSegment(segment, pattern) && index < segments.length - 1; + }); +} + +function matchPathSegments(pathSegments: string[], patternSegments: string[]): boolean { + if (pathSegments.length !== patternSegments.length) { + return false; + } + + return patternSegments.every((patternSegment, index) => + matchSegment(pathSegments[index] ?? "", patternSegment) + ); +} + +function matchSegment(value: string, pattern: string): boolean { + const patternParts = pattern.split("*"); + if (patternParts.length === 1) { + return value === pattern; + } + + let offset = 0; + for (const [index, part] of patternParts.entries()) { + if (part.length === 0) { + continue; + } + + const foundAt = value.indexOf(part, offset); + if (foundAt === -1) { + return false; + } + + if (index === 0 && foundAt !== 0) { + return false; + } + + offset = foundAt + part.length; + } + + const lastPart = patternParts.at(-1) ?? ""; + return lastPart.length === 0 || value.endsWith(lastPart); +} + +async function isDownloadConflict( + fs: WorkspaceTransferFileSystem, + localPath: string, + relativePath: string, + remoteContent: Buffer, + state: Map +): Promise { + const localContent = await readFileIfExists(fs, localPath); + if (localContent === null) { + return false; + } + + const localHash = hashBuffer(localContent); + const remoteHash = hashBuffer(remoteContent); + const uploadedHash = state.get(relativePath)?.hash; + const localChanged = uploadedHash === undefined || localHash !== uploadedHash; + return localChanged && localHash !== remoteHash; +} + +async function readFileIfExists( + fs: WorkspaceTransferFileSystem, + filePath: string +): Promise { + try { + return await fs.readFile(filePath); + } catch (error) { + if (isNotFoundError(error)) { + return null; + } + throw error; + } +} + +async function removeTree(fs: WorkspaceTransferFileSystem, targetPath: string): Promise { + if (fs.rm) { + await fs.rm(targetPath, { recursive: true, force: true }); + return; + } + + const stats = await statIfExists(fs, targetPath); + if (stats === null) { + return; + } + if (stats.isFile()) { + await removeFile(fs, targetPath); + return; + } + + const dirents = await fs.readdir(targetPath, { withFileTypes: true }); + for (const dirent of dirents) { + await removeTree(fs, path.join(targetPath, dirent.name)); + } + if (fs.rmdir) { + await fs.rmdir(targetPath); + } +} + +async function removeFile(fs: WorkspaceTransferFileSystem, filePath: string): Promise { + if (fs.rm) { + await fs.rm(filePath, { force: true }); + return; + } + if (fs.unlink) { + await fs.unlink(filePath); + } +} + +async function statIfExists( + fs: WorkspaceTransferFileSystem, + targetPath: string +): Promise { + try { + return await fs.stat(targetPath); + } catch (error) { + if (isNotFoundError(error)) { + return null; + } + throw error; + } +} + +function createTar(entries: FileEntry[]): Buffer { + const chunks: Buffer[] = []; + for (const entry of entries) { + chunks.push(createTarHeader(entry.path, entry.bytes)); + chunks.push(entry.content); + chunks.push(Buffer.alloc(paddingFor(entry.bytes))); + } + chunks.push(Buffer.alloc(1024)); + return Buffer.concat(chunks); +} + +function createTarHeader(name: string, size: number): Buffer { + const header = Buffer.alloc(512); + writeString(header, name, 0, 100); + writeOctal(header, 0o644, 100, 8); + writeOctal(header, 0, 108, 8); + writeOctal(header, 0, 116, 8); + writeOctal(header, size, 124, 12); + writeOctal(header, 0, 136, 12); + header.fill(32, 148, 156); + header.write("0", 156, 1, "ascii"); + header.write("ustar", 257, 5, "ascii"); + header.write("00", 263, 2, "ascii"); + writeOctal(header, checksum(header), 148, 8); + return header; +} + +function writeString(buffer: Buffer, value: string, offset: number, length: number): void { + const text = Buffer.from(value); + text.copy(buffer, offset, 0, Math.min(text.length, length)); +} + +function writeOctal(buffer: Buffer, value: number, offset: number, length: number): void { + const text = value.toString(8).padStart(length - 1, "0"); + buffer.write(text.slice(0, length - 1), offset, length - 1, "ascii"); + buffer[offset + length - 1] = 0; +} + +function checksum(buffer: Buffer): number { + return buffer.reduce((sum, value) => sum + value, 0); +} + +function paddingFor(size: number): number { + const remainder = size % 512; + return remainder === 0 ? 0 : 512 - remainder; +} + +function hashBuffer(buffer: Buffer): string { + return createHash("sha256").update(buffer).digest("hex"); +} + +function toRelativePath(root: string, absolutePath: string): string { + return normalizeRelativePath(path.relative(root, absolutePath)); +} + +function normalizeRelativePath(value: string): string { + return stripSlashes(value.split(path.sep).join("/")); +} + +function stripSlashes(value: string): string { + let start = 0; + let end = value.length; + while (value[start] === "/") { + start += 1; + } + while (value[end - 1] === "/") { + end -= 1; + } + return value.slice(start, end); +} + +function isNotFoundError(error: unknown): boolean { + return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT"; +} From e8e826af0d12c39e602f1056b211f5e9422d3296 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 08:37:26 -0400 Subject: [PATCH 010/111] feat(agent-harness-tools): add log stream helpers --- docs/plans/e2b-integration.md | 6 +- docs/plans/e2b-integration.md.lock | 2 +- packages/agent-harness-tools/src/index.ts | 7 + .../src/log-stream.test.ts | 127 ++++++++++++++ .../agent-harness-tools/src/log-stream.ts | 158 ++++++++++++++++++ 5 files changed, 296 insertions(+), 4 deletions(-) create mode 100644 packages/agent-harness-tools/src/log-stream.test.ts create mode 100644 packages/agent-harness-tools/src/log-stream.ts diff --git a/docs/plans/e2b-integration.md b/docs/plans/e2b-integration.md index ffa334ccd2..3dfb6a5de0 100644 --- a/docs/plans/e2b-integration.md +++ b/docs/plans/e2b-integration.md @@ -171,7 +171,7 @@ tasks: status: implement: done test: done - commit: open + commit: done - id: harness-log-stream title: Tee-to-file log stream and offset-aware tail @@ -196,8 +196,8 @@ tasks: offset; wait resolves with exit code; argv wrapping is shell-safe (escape jobId). status: - implement: open - test: open + implement: done + test: done commit: open - id: harness-run-poe-command diff --git a/docs/plans/e2b-integration.md.lock b/docs/plans/e2b-integration.md.lock index 088394b4ae..c6f0f10cfa 100644 --- a/docs/plans/e2b-integration.md.lock +++ b/docs/plans/e2b-integration.md.lock @@ -1 +1 @@ -{"pid":1590,"host":"m5mb-kjopek","acquiredAt":"2026-05-03T12:30:02.437Z"} \ No newline at end of file +{"pid":1590,"host":"m5mb-kjopek","acquiredAt":"2026-05-03T12:36:26.845Z"} \ No newline at end of file diff --git a/packages/agent-harness-tools/src/index.ts b/packages/agent-harness-tools/src/index.ts index de17088122..99793b8144 100644 --- a/packages/agent-harness-tools/src/index.ts +++ b/packages/agent-harness-tools/src/index.ts @@ -40,6 +40,13 @@ export { slugifyPlanPath, type ResolveRunLogDirOptions } from "./run-logs.js"; +export { + streamLogFile, + waitForExit, + wrapForLogTee, + type LogStreamEnv, + type LogStreamFs +} from "./log-stream.js"; export { skillPlanConfigSection } from "./skill-config.js"; export * from "./execution-env.js"; export * from "./workspace-transfer.js"; diff --git a/packages/agent-harness-tools/src/log-stream.test.ts b/packages/agent-harness-tools/src/log-stream.test.ts new file mode 100644 index 0000000000..32b7b48330 --- /dev/null +++ b/packages/agent-harness-tools/src/log-stream.test.ts @@ -0,0 +1,127 @@ +import { createFsFromVolume, Volume } from "memfs"; +import { describe, expect, it, vi } from "vitest"; +import { streamLogFile, waitForExit, wrapForLogTee } from "./log-stream.js"; + +describe("streamLogFile", () => { + it("replays a log file from offset 0", async () => { + const { fs } = createMemFs({ + "/tmp/poe-jobs/job-1.log": "first\nsecond\n" + }); + + const chunks = await takeChunks(streamLogFile({ fs }, "job-1", {}), 1); + + expect(chunks).toEqual([{ byteOffset: 0, data: "first\nsecond\n" }]); + }); + + it("replays a log file from an arbitrary byte offset", async () => { + const { fs } = createMemFs({ + "/tmp/poe-jobs/job-1.log": "first\nsecond\n" + }); + + const chunks = await takeChunks(streamLogFile({ fs }, "job-1", { sinceByte: 6 }), 1); + + expect(chunks).toEqual([{ byteOffset: 6, data: "second\n" }]); + }); + + it("polls for appended content when watch is unavailable", async () => { + vi.useFakeTimers(); + const { fs } = createMemFs({ + "/tmp/poe-jobs/job-1.log": "first\n" + }); + const env = { fs: { promises: fs.promises } }; + + try { + const chunksPromise = takeChunks(streamLogFile(env, "job-1", { sinceByte: 6 }), 1); + + await fs.promises.appendFile("/tmp/poe-jobs/job-1.log", "second\n"); + await vi.advanceTimersByTimeAsync(250); + + await expect(chunksPromise).resolves.toEqual([{ byteOffset: 6, data: "second\n" }]); + } finally { + vi.useRealTimers(); + } + }); + + it("polls until the log file exists when watch is unavailable", async () => { + vi.useFakeTimers(); + const { fs } = createMemFs({}); + const env = { fs: { promises: fs.promises } }; + + try { + const chunksPromise = takeChunks(streamLogFile(env, "job-1", {}), 1); + + await fs.promises.mkdir("/tmp/poe-jobs", { recursive: true }); + await fs.promises.writeFile("/tmp/poe-jobs/job-1.log", "created\n"); + await vi.advanceTimersByTimeAsync(250); + + await expect(chunksPromise).resolves.toEqual([{ byteOffset: 0, data: "created\n" }]); + } finally { + vi.useRealTimers(); + } + }); +}); + +describe("waitForExit", () => { + it("resolves with the parsed exit code", async () => { + vi.useFakeTimers(); + const { fs } = createMemFs({}); + + try { + const waitPromise = waitForExit({ fs }, "job-1"); + + await fs.promises.mkdir("/tmp/poe-jobs", { recursive: true }); + await fs.promises.writeFile("/tmp/poe-jobs/job-1.exit", "42\n"); + await vi.advanceTimersByTimeAsync(250); + + await expect(waitPromise).resolves.toEqual({ exitCode: 42 }); + } finally { + vi.useRealTimers(); + } + }); + + it("rejects when the exit file does not contain an integer", async () => { + const { fs } = createMemFs({ + "/tmp/poe-jobs/job-1.exit": "not-a-number\n" + }); + + await expect(waitForExit({ fs }, "job-1")).rejects.toThrow( + "Invalid exit code in /tmp/poe-jobs/job-1.exit" + ); + }); +}); + +describe("wrapForLogTee", () => { + it("wraps argv in a shell-safe tee command and escapes jobId paths", () => { + const argv = wrapForLogTee(["printf", "hello ' world"], "job'1; rm -rf /"); + + expect(argv[0]).toBe("sh"); + expect(argv[1]).toBe("-c"); + expect(argv[2]).toContain("mkdir -p '/tmp/poe-jobs'"); + expect(argv[2]).toContain("'printf' 'hello '\\'' world'"); + expect(argv[2]).toContain("'/tmp/poe-jobs/job'\\''1; rm -rf /.log'"); + expect(argv[2]).toContain("'/tmp/poe-jobs/job'\\''1; rm -rf /.exit'"); + expect(argv[2]).not.toContain("/tmp/poe-jobs/job'1; rm -rf /.log"); + }); + + it("rejects an empty argv because there is no inner command to tee", () => { + expect(() => wrapForLogTee([], "job-1")).toThrow("wrapForLogTee requires argv"); + }); +}); + +function createMemFs(files: Record) { + const vol = Volume.fromJSON(files, "/"); + return { fs: createFsFromVolume(vol), vol }; +} + +async function takeChunks(iterable: AsyncIterable, count: number): Promise { + const chunks: T[] = []; + + for await (const chunk of iterable) { + chunks.push(chunk); + if (chunks.length === count) { + break; + } + } + + return chunks; +} diff --git a/packages/agent-harness-tools/src/log-stream.ts b/packages/agent-harness-tools/src/log-stream.ts new file mode 100644 index 0000000000..2436e7d008 --- /dev/null +++ b/packages/agent-harness-tools/src/log-stream.ts @@ -0,0 +1,158 @@ +import nodeFs from "node:fs"; +import type { FSWatcher } from "node:fs"; +import type { LogChunk } from "./execution-env.js"; + +const JOB_DIR = "/tmp/poe-jobs"; +const POLL_INTERVAL_MS = 250; + +export interface LogStreamEnv { + fs?: LogStreamFs; +} + +export interface LogStreamFs { + promises: { + readFile(path: string): Promise; + }; + watch?: (path: string, listener: () => void) => FSWatcher; +} + +export function wrapForLogTee(argv: string[], jobId: string): string[] { + if (argv.length === 0) { + throw new Error("wrapForLogTee requires argv to contain at least one argument"); + } + + const command = argv.map(shellQuote).join(" "); + const logFile = shellQuote(jobLogPath(jobId)); + const exitFile = shellQuote(jobExitPath(jobId)); + const exitTmpFile = shellQuote(`${jobExitPath(jobId)}.tmp`); + const script = [ + `mkdir -p ${shellQuote(JOB_DIR)}`, + `({ (${command}); echo $? > ${exitTmpFile}; } 2>&1 | tee ${logFile}; mv ${exitTmpFile} ${exitFile})` + ].join(" && "); + + return ["sh", "-c", script]; +} + +export async function* streamLogFile( + env: LogStreamEnv, + jobId: string, + opts: { sinceByte?: number } +): AsyncIterable { + const fs = env.fs ?? nodeFs; + const file = jobLogPath(jobId); + let byteOffset = opts.sinceByte ?? 0; + + while (true) { + const result = await readLogChunk(fs, file, byteOffset); + if (result !== null) { + byteOffset = result.nextByteOffset; + yield result.chunk; + continue; + } + + await waitForLogChange(fs, file); + } +} + +export async function waitForExit( + env: LogStreamEnv, + jobId: string +): Promise<{ exitCode: number }> { + const fs = env.fs ?? nodeFs; + const file = jobExitPath(jobId); + + while (true) { + const contents = await readTextFileIfExists(fs, file); + if (contents !== null) { + const text = contents.trim(); + const exitCode = Number(text); + if (text.length === 0 || !Number.isInteger(exitCode)) { + throw new Error(`Invalid exit code in ${file}: ${contents}`); + } + return { exitCode }; + } + + await sleep(POLL_INTERVAL_MS); + } +} + +function jobLogPath(jobId: string): string { + return `${JOB_DIR}/${jobId}.log`; +} + +function jobExitPath(jobId: string): string { + return `${JOB_DIR}/${jobId}.exit`; +} + +async function readLogChunk( + fs: LogStreamFs, + file: string, + byteOffset: number +): Promise<{ chunk: LogChunk; nextByteOffset: number } | null> { + const contents = await readFileIfExists(fs, file); + if (contents === null || byteOffset >= contents.byteLength) { + return null; + } + + return { + chunk: { + byteOffset, + data: contents.subarray(byteOffset).toString("utf8") + }, + nextByteOffset: contents.byteLength + }; +} + +async function readTextFileIfExists(fs: LogStreamFs, file: string): Promise { + const contents = await readFileIfExists(fs, file); + return contents?.toString("utf8") ?? null; +} + +async function readFileIfExists(fs: LogStreamFs, file: string): Promise { + try { + const contents = await fs.promises.readFile(file); + return Buffer.isBuffer(contents) ? contents : Buffer.from(contents); + } catch (error) { + if (isNodeError(error) && error.code === "ENOENT") { + return null; + } + throw error; + } +} + +async function waitForLogChange(fs: LogStreamFs, file: string): Promise { + const watch = fs.watch; + if (typeof watch !== "function") { + await sleep(POLL_INTERVAL_MS); + return; + } + + await new Promise((resolve) => { + let watcher: FSWatcher | null = null; + const timer = setTimeout(done, POLL_INTERVAL_MS); + + function done(): void { + clearTimeout(timer); + watcher?.close(); + resolve(); + } + + try { + watcher = watch(file, done); + } catch { + done(); + } + }); +} + +function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +function shellQuote(value: string): string { + return `'${value.replaceAll("'", "'\\''")}'`; +} + +function isNodeError(error: unknown): error is NodeJS.ErrnoException { + return error instanceof Error && "code" in error; +} From 3745204bd350914ce8241655b342523f35978ad2 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 08:46:22 -0400 Subject: [PATCH 011/111] feat(agent-harness-tools): add poe command runner --- docs/plans/e2b-integration.md | 8 +- docs/plans/e2b-integration.md.lock | 2 +- .../src/execution-env.test.ts | 4 +- .../agent-harness-tools/src/execution-env.ts | 3 +- packages/agent-harness-tools/src/index.ts | 1 + .../src/log-stream.test.ts | 10 + .../agent-harness-tools/src/log-stream.ts | 35 +- .../src/run-poe-command.test.ts | 333 ++++++++++++++++++ .../src/run-poe-command.ts | 206 +++++++++++ 9 files changed, 590 insertions(+), 12 deletions(-) create mode 100644 packages/agent-harness-tools/src/run-poe-command.test.ts create mode 100644 packages/agent-harness-tools/src/run-poe-command.ts diff --git a/docs/plans/e2b-integration.md b/docs/plans/e2b-integration.md index 3dfb6a5de0..d6c7273ed5 100644 --- a/docs/plans/e2b-integration.md +++ b/docs/plans/e2b-integration.md @@ -198,7 +198,7 @@ tasks: status: implement: done test: done - commit: open + commit: done - id: harness-run-poe-command title: Implement runPoeCommand orchestrator @@ -234,9 +234,9 @@ tasks: transition; detach leaves env open; download conflict surfaces in result; abort signal kills cleanly. No SDK or child_process. status: - implement: open - test: open - commit: open + implement: done + test: done + commit: done - id: process-runner-host-factory title: Add hostExecutionEnvFactory in process-runner diff --git a/docs/plans/e2b-integration.md.lock b/docs/plans/e2b-integration.md.lock index c6f0f10cfa..b4e16b719a 100644 --- a/docs/plans/e2b-integration.md.lock +++ b/docs/plans/e2b-integration.md.lock @@ -1 +1 @@ -{"pid":1590,"host":"m5mb-kjopek","acquiredAt":"2026-05-03T12:36:26.845Z"} \ No newline at end of file +{"pid":1590,"host":"m5mb-kjopek","acquiredAt":"2026-05-03T12:44:57.666Z"} \ No newline at end of file diff --git a/packages/agent-harness-tools/src/execution-env.test.ts b/packages/agent-harness-tools/src/execution-env.test.ts index 0927e15c1c..27657a31e4 100644 --- a/packages/agent-harness-tools/src/execution-env.test.ts +++ b/packages/agent-harness-tools/src/execution-env.test.ts @@ -78,8 +78,8 @@ describe("execution env registry", () => { expect(branchSites).toMatchInlineSnapshot(` [ - "execution-env.ts:70:const factory = executionEnvFactories.get(runtime.type);", - "execution-env.ts:73:\`No execution environment factory registered for runtime type "\${runtime.type}".\`", + "execution-env.ts:71:const factory = executionEnvFactories.get(runtime.type);", + "execution-env.ts:74:\`No execution environment factory registered for runtime type "\${runtime.type}".\`", ] `); }); diff --git a/packages/agent-harness-tools/src/execution-env.ts b/packages/agent-harness-tools/src/execution-env.ts index 73a61b9e0f..bcd833ba90 100644 --- a/packages/agent-harness-tools/src/execution-env.ts +++ b/packages/agent-harness-tools/src/execution-env.ts @@ -1,4 +1,4 @@ -import type { RuntimeConfig } from "@poe-code/poe-code-config"; +import type { RunnerScope, RuntimeConfig } from "@poe-code/poe-code-config"; import type { RunHandle, RunSpec } from "@poe-code/process-runner"; export type { RuntimeConfig } from "@poe-code/poe-code-config"; @@ -16,6 +16,7 @@ export interface ExecutionEnvFactory { export interface OpenSpec { cwd: string; runtime: RuntimeConfig; + runner?: RunnerScope; env: Record; uploadIgnoreFiles: string[]; jobLabel: { tool: string; argv: string[] }; diff --git a/packages/agent-harness-tools/src/index.ts b/packages/agent-harness-tools/src/index.ts index 99793b8144..8472fc4a1c 100644 --- a/packages/agent-harness-tools/src/index.ts +++ b/packages/agent-harness-tools/src/index.ts @@ -47,6 +47,7 @@ export { type LogStreamEnv, type LogStreamFs } from "./log-stream.js"; +export { runPoeCommand } from "./run-poe-command.js"; export { skillPlanConfigSection } from "./skill-config.js"; export * from "./execution-env.js"; export * from "./workspace-transfer.js"; diff --git a/packages/agent-harness-tools/src/log-stream.test.ts b/packages/agent-harness-tools/src/log-stream.test.ts index 32b7b48330..841b9e2af6 100644 --- a/packages/agent-harness-tools/src/log-stream.test.ts +++ b/packages/agent-harness-tools/src/log-stream.test.ts @@ -88,6 +88,16 @@ describe("waitForExit", () => { "Invalid exit code in /tmp/poe-jobs/job-1.exit" ); }); + + it("stops polling when the signal aborts", async () => { + const { fs } = createMemFs({}); + const controller = new AbortController(); + + const waitPromise = waitForExit({ fs }, "job-1", { signal: controller.signal }); + controller.abort(); + + await expect(waitPromise).rejects.toThrow("waitForExit aborted."); + }); }); describe("wrapForLogTee", () => { diff --git a/packages/agent-harness-tools/src/log-stream.ts b/packages/agent-harness-tools/src/log-stream.ts index 2436e7d008..1573bccce8 100644 --- a/packages/agent-harness-tools/src/log-stream.ts +++ b/packages/agent-harness-tools/src/log-stream.ts @@ -56,12 +56,14 @@ export async function* streamLogFile( export async function waitForExit( env: LogStreamEnv, - jobId: string + jobId: string, + opts: { signal?: AbortSignal } = {} ): Promise<{ exitCode: number }> { const fs = env.fs ?? nodeFs; const file = jobExitPath(jobId); while (true) { + throwIfAborted(opts.signal); const contents = await readTextFileIfExists(fs, file); if (contents !== null) { const text = contents.trim(); @@ -72,7 +74,7 @@ export async function waitForExit( return { exitCode }; } - await sleep(POLL_INTERVAL_MS); + await sleep(POLL_INTERVAL_MS, opts.signal); } } @@ -145,8 +147,33 @@ async function waitForLogChange(fs: LogStreamFs, file: string): Promise { }); } -function sleep(ms: number): Promise { - return new Promise((resolve) => setTimeout(resolve, ms)); +function sleep(ms: number, signal?: AbortSignal): Promise { + return new Promise((resolve, reject) => { + let timer: NodeJS.Timeout | null = null; + const abort = () => { + if (timer !== null) { + clearTimeout(timer); + } + reject(new Error("waitForExit aborted.")); + }; + + if (signal?.aborted) { + abort(); + return; + } + + timer = setTimeout(() => { + signal?.removeEventListener("abort", abort); + resolve(); + }, ms); + signal?.addEventListener("abort", abort, { once: true }); + }); +} + +function throwIfAborted(signal: AbortSignal | undefined): void { + if (signal?.aborted) { + throw new Error("waitForExit aborted."); + } } function shellQuote(value: string): string { diff --git a/packages/agent-harness-tools/src/run-poe-command.test.ts b/packages/agent-harness-tools/src/run-poe-command.test.ts new file mode 100644 index 0000000000..e6f4e325e3 --- /dev/null +++ b/packages/agent-harness-tools/src/run-poe-command.test.ts @@ -0,0 +1,333 @@ +import { PassThrough } from "node:stream"; +import { + createStateManager, + type RuntimeConfig, + type StateFileSystem, + type StateManager +} from "@poe-code/poe-code-config"; +import type { RunHandle, RunResult, RunSpec } from "@poe-code/process-runner"; +import { createFsFromVolume, Volume } from "memfs"; +import { describe, expect, it } from "vitest"; +import type { + DownloadResult, + ExecutionEnvFactory, + OpenedEnv, + OpenSpec, + UploadResult +} from "./execution-env.js"; +import type { LogStreamFs } from "./log-stream.js"; +import { runPoeCommand } from "./run-poe-command.js"; + +interface RecordingState { + state: StateManager; + statuses: string[]; +} + +interface MockEnv extends OpenedEnv { + closed: boolean; + downloads: { conflictPolicy: "refuse" | "overwrite" }[]; + execSpecs: RunSpec[]; + fs: LogStreamFs; + uploads: number; +} + +function createRecordingState(): RecordingState { + const fs = createFsFromVolume(new Volume()).promises as unknown as StateFileSystem; + const state = createStateManager("/home/tester", fs); + const jobs = state.jobs; + const statuses: string[] = []; + + return { + statuses, + state: { + ...state, + jobs: { + ...jobs, + async put(entry) { + statuses.push(entry.status); + await jobs.put(entry); + }, + async update(id, patch) { + if (patch.status !== undefined) { + statuses.push(patch.status); + } + return jobs.update(id, patch); + } + } + } + }; +} + +function createOpenSpec(overrides: Partial = {}): OpenSpec { + return { + cwd: "/repo", + runtime: { + type: "host", + build_args: {}, + mounts: [] + } satisfies RuntimeConfig, + runner: { + detach: false, + upload_max_file_mb: 100, + download_conflict: "refuse" + }, + env: { NODE_ENV: "test" }, + uploadIgnoreFiles: [], + jobLabel: { tool: "poe-code", argv: ["poe-code", "--help"] }, + ...overrides + }; +} + +function createMockEnv(opts: { + result?: Promise; + commandExitCode?: number; + download?: DownloadResult; +} = {}): MockEnv { + const result = opts.result ?? Promise.resolve({ exitCode: 0 }); + const commandExitCode = opts.commandExitCode ?? 0; + const download = opts.download ?? { files: 0, bytes: 0, conflicts: [] }; + const rawFs = createFsFromVolume(new Volume()); + const env: MockEnv = { + id: "env-1", + job: null, + closed: false, + downloads: [], + execSpecs: [], + fs: rawFs as unknown as LogStreamFs, + uploads: 0, + async uploadWorkspace(): Promise { + env.uploads += 1; + return { files: 1, bytes: 12, skipped: [] }; + }, + async downloadWorkspace(call): Promise { + env.downloads.push(call); + return download; + }, + exec(spec): RunHandle { + env.execSpecs.push(spec); + void writeExitFile(rawFs.promises, spec, commandExitCode); + return { + pid: 123, + stdout: null, + stderr: null, + stdin: null, + result, + kill() {} + }; + }, + async detach() { + throw new Error("detach is not used by runPoeCommand"); + }, + shell(): RunHandle { + throw new Error("shell is not used by runPoeCommand"); + }, + async close(): Promise { + env.closed = true; + } + }; + return env; +} + +async function writeExitFile( + fs: { + mkdir(path: string, opts: { recursive: boolean }): Promise; + writeFile(path: string, data: string, encoding: BufferEncoding): Promise; + }, + spec: RunSpec, + exitCode: number +): Promise { + const jobId = extractJobId(spec); + await fs.mkdir("/tmp/poe-jobs", { recursive: true }); + await fs.writeFile(`/tmp/poe-jobs/${jobId}.exit`, `${exitCode}\n`, "utf8"); +} + +function extractJobId(spec: RunSpec): string { + const script = spec.args?.[1] ?? ""; + const prefix = "/tmp/poe-jobs/"; + const suffix = ".exit.tmp"; + const start = script.indexOf(prefix); + const end = script.indexOf(suffix, start); + if (start === -1 || end === -1) { + throw new Error("Expected wrapped command to include an exit file."); + } + return script.slice(start + prefix.length, end); +} + +function createFactory(env: OpenedEnv): ExecutionEnvFactory { + return { + type: "host", + async open() { + return env; + }, + async attach() { + return env; + } + }; +} + +function deferred(): { + promise: Promise; + resolve(value: T): void; +} { + let resolve!: (value: T) => void; + const promise = new Promise((innerResolve) => { + resolve = innerResolve; + }); + return { promise, resolve }; +} + +describe("runPoeCommand", () => { + it("records pending, running, and exited statuses for a sync run", async () => { + const { state, statuses } = createRecordingState(); + const env = createMockEnv(); + + const result = await runPoeCommand({ + factory: createFactory(env), + openSpec: createOpenSpec(), + detach: false, + state + }); + + const [job] = await state.jobs.list(); + expect(result).toEqual({ + kind: "sync", + exitCode: 0, + download: { files: 0, bytes: 0, conflicts: [] } + }); + expect(statuses).toEqual(["pending", "running", "exited"]); + expect(job).toMatchObject({ + env_id: "env-1", + env_kind: "host", + tool: "poe-code", + argv: ["poe-code", "--help"], + cwd: "/repo", + status: "exited", + exit_code: 0 + }); + expect(env.uploads).toBe(1); + expect(env.closed).toBe(true); + expect(env.execSpecs[0]).toMatchObject({ + command: "sh", + args: ["-c", expect.stringContaining("'poe-code' '--help'")], + cwd: "/repo", + env: { NODE_ENV: "test" }, + stdin: "inherit", + stdout: "pipe", + stderr: "pipe" + }); + }); + + it("leaves the environment open in detach mode", async () => { + const { state, statuses } = createRecordingState(); + const runResult = deferred(); + const env = createMockEnv({ result: runResult.promise }); + + const result = await runPoeCommand({ + factory: createFactory(env), + openSpec: createOpenSpec(), + detach: true, + state + }); + + if (result.kind !== "detached") { + throw new Error("Expected detached result."); + } + expect(result).toMatchObject({ kind: "detached", envId: "env-1" }); + expect(result.jobId).toMatch(/^[0-9A-HJKMNP-TV-Z]{26}$/); + expect(statuses).toEqual(["pending", "running"]); + expect(env.closed).toBe(false); + expect(env.downloads).toEqual([]); + }); + + it("returns the download result with conflicts from sync mode", async () => { + const { state } = createRecordingState(); + const env = createMockEnv({ + download: { + files: 2, + bytes: 20, + conflicts: [{ path: "src/index.ts", reason: "local_modified" }] + } + }); + + const result = await runPoeCommand({ + factory: createFactory(env), + openSpec: createOpenSpec({ + runner: { + detach: false, + upload_max_file_mb: 100, + download_conflict: "overwrite" + } + }), + detach: false, + state + }); + + expect(result).toEqual({ + kind: "sync", + exitCode: 0, + download: { + files: 2, + bytes: 20, + conflicts: [{ path: "src/index.ts", reason: "local_modified" }] + } + }); + expect(env.downloads).toEqual([{ conflictPolicy: "overwrite" }]); + }); + + it("uses the log tee exit file instead of the wrapper process exit code", async () => { + const { state } = createRecordingState(); + const env = createMockEnv({ + result: Promise.resolve({ exitCode: 0 }), + commandExitCode: 42 + }); + + const result = await runPoeCommand({ + factory: createFactory(env), + openSpec: createOpenSpec(), + detach: false, + state + }); + + const [job] = await state.jobs.list(); + expect(result).toMatchObject({ kind: "sync", exitCode: 42 }); + expect(job).toMatchObject({ status: "exited", exit_code: 42 }); + }); + + it("kills, downloads, and closes when the abort signal fires during sync", async () => { + const { state } = createRecordingState(); + const controller = new AbortController(); + const runResult = deferred(); + let killed = false; + const env = createMockEnv({ result: runResult.promise }); + env.exec = (spec): RunHandle => { + env.execSpecs.push(spec); + queueMicrotask(() => controller.abort()); + return { + pid: 123, + stdout: new PassThrough(), + stderr: null, + stdin: null, + result: runResult.promise, + kill() { + killed = true; + runResult.resolve({ exitCode: 130 }); + } + }; + }; + + const result = await runPoeCommand({ + factory: createFactory(env), + openSpec: createOpenSpec(), + detach: false, + state, + signal: controller.signal + }); + + const [job] = await state.jobs.list(); + expect(killed).toBe(true); + expect(env.downloads).toEqual([{ conflictPolicy: "refuse" }]); + expect(env.closed).toBe(true); + expect(result).toMatchObject({ kind: "sync", exitCode: 130 }); + expect(job).toMatchObject({ status: "exited", exit_code: 130 }); + }); +}); diff --git a/packages/agent-harness-tools/src/run-poe-command.ts b/packages/agent-harness-tools/src/run-poe-command.ts new file mode 100644 index 0000000000..f9f662440e --- /dev/null +++ b/packages/agent-harness-tools/src/run-poe-command.ts @@ -0,0 +1,206 @@ +import { randomBytes } from "node:crypto"; +import type { StateManager } from "@poe-code/poe-code-config"; +import type { RunHandle } from "@poe-code/process-runner"; +import type { + DownloadResult, + ExecutionEnvFactory, + OpenedEnv, + OpenSpec +} from "./execution-env.js"; +import { waitForExit, wrapForLogTee, type LogStreamEnv } from "./log-stream.js"; + +const ULID_ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"; + +export async function runPoeCommand(opts: { + factory: ExecutionEnvFactory; + openSpec: OpenSpec; + detach: boolean; + state: StateManager; + signal?: AbortSignal; +}): Promise< + | { kind: "sync"; exitCode: number; download: DownloadResult } + | { kind: "detached"; jobId: string; envId: string } +> { + const jobId = createUlid(); + await opts.state.jobs.put({ + id: jobId, + env_id: "", + env_kind: opts.factory.type, + tool: opts.openSpec.jobLabel.tool, + argv: opts.openSpec.jobLabel.argv, + cwd: opts.openSpec.cwd, + started_at: "", + status: "pending" + }); + + const env = await opts.factory.open(opts.openSpec); + let shouldClose = true; + + try { + await env.uploadWorkspace(); + const wrappedArgv = wrapForLogTee(opts.openSpec.jobLabel.argv, jobId); + const handle = env.exec({ + command: wrappedArgv[0], + args: wrappedArgv.slice(1), + cwd: opts.openSpec.cwd, + env: opts.openSpec.env, + stdin: "inherit", + stdout: "pipe", + stderr: "pipe", + signal: opts.signal + }); + + await opts.state.jobs.update(jobId, { + status: "running", + env_id: env.id, + started_at: new Date().toISOString() + }); + + if (opts.detach) { + shouldClose = false; + return { kind: "detached", jobId, envId: env.id }; + } + + const result = await runSync({ + env, + handle, + jobId, + openSpec: opts.openSpec, + signal: opts.signal + }); + shouldClose = false; + + await opts.state.jobs.update(jobId, { + status: "exited", + exit_code: result.exitCode, + exited_at: new Date().toISOString() + }); + + return { kind: "sync", exitCode: result.exitCode, download: result.download }; + } finally { + if (shouldClose) { + await env.close(); + } + } +} + +async function runSync(opts: { + env: OpenedEnv; + handle: RunHandle; + jobId: string; + openSpec: OpenSpec; + signal?: AbortSignal; +}): Promise<{ exitCode: number; download: DownloadResult }> { + opts.handle.stdout?.pipe(process.stdout, { end: false }); + opts.handle.stderr?.pipe(process.stderr, { end: false }); + const abort = createAbortSync(opts.signal, opts.handle); + + try { + const { exitCode } = await abort.waitForExit(opts.env, opts.jobId); + const download = await opts.env.downloadWorkspace({ + conflictPolicy: opts.openSpec.runner?.download_conflict ?? "refuse" + }); + await opts.env.close(); + return { exitCode, download }; + } finally { + abort.dispose(); + opts.handle.stdout?.unpipe(process.stdout); + opts.handle.stderr?.unpipe(process.stderr); + } +} + +function createAbortSync( + signal: AbortSignal | undefined, + handle: RunHandle +): { + waitForExit(env: OpenedEnv, jobId: string): Promise<{ exitCode: number }>; + dispose(): void; +} { + if (signal === undefined) { + return { + waitForExit: (env, jobId) => waitForExit(toLogStreamEnv(env), jobId), + dispose() {} + }; + } + + const exitWaitController = new AbortController(); + let aborted = signal.aborted; + let notifyAbort!: () => void; + const abortedPromise = new Promise((resolve) => { + notifyAbort = resolve; + }); + const kill = () => { + aborted = true; + handle.kill("SIGTERM"); + notifyAbort(); + }; + + if (signal.aborted) { + kill(); + } else { + signal.addEventListener("abort", kill, { once: true }); + } + + return { + async waitForExit(env, jobId) { + if (aborted) { + return handle.result; + } + + const exit = waitForExit(toLogStreamEnv(env), jobId, { + signal: exitWaitController.signal + }).then( + (value) => ({ kind: "exit" as const, value }), + (error: unknown) => ({ kind: "error" as const, error }) + ); + const result = await Promise.race([ + exit, + abortedPromise.then(() => ({ kind: "abort" as const })) + ]); + + if (result.kind === "exit") { + return result.value; + } + + if (result.kind === "error") { + throw result.error; + } + + exitWaitController.abort(); + return handle.result; + }, + dispose() { + exitWaitController.abort(); + signal.removeEventListener("abort", kill); + } + }; +} + +function toLogStreamEnv(env: OpenedEnv): LogStreamEnv { + const candidate = env as OpenedEnv & LogStreamEnv; + return candidate.fs === undefined ? {} : { fs: candidate.fs }; +} + +function createUlid(): string { + const time = BigInt(Date.now()); + const random = randomBytes(10); + let randomValue = 0n; + + for (const byte of random) { + randomValue = (randomValue << 8n) | BigInt(byte); + } + + return encodeBase32(time, 10) + encodeBase32(randomValue, 16); +} + +function encodeBase32(value: bigint, length: number): string { + const chars = Array.from({ length }, () => "0"); + let remaining = value; + + for (let index = length - 1; index >= 0; index -= 1) { + chars[index] = ULID_ALPHABET[Number(remaining & 31n)]; + remaining >>= 5n; + } + + return chars.join(""); +} From 9633f40a44f0c7fb6c48fdcab30c79adb1d0fbc0 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 08:51:11 -0400 Subject: [PATCH 012/111] feat(process-runner): add host execution env --- docs/plans/e2b-integration.md | 6 +- docs/plans/e2b-integration.md.lock | 2 +- .../src/host/host-execution-env.test.ts | 135 ++++++++++++++++++ .../src/host/host-execution-env.ts | 47 ++++++ packages/process-runner/src/index.test.ts | 77 +++++++++- packages/process-runner/src/index.ts | 12 +- packages/process-runner/src/types.ts | 57 ++++++++ 7 files changed, 330 insertions(+), 6 deletions(-) create mode 100644 packages/process-runner/src/host/host-execution-env.test.ts create mode 100644 packages/process-runner/src/host/host-execution-env.ts diff --git a/docs/plans/e2b-integration.md b/docs/plans/e2b-integration.md index d6c7273ed5..9aaf8bd682 100644 --- a/docs/plans/e2b-integration.md +++ b/docs/plans/e2b-integration.md @@ -262,9 +262,9 @@ tasks: package if needed. The harness-tools registry imports the factory via dynamic registration at app startup. status: - implement: open - test: open - commit: open + implement: done + test: done + commit: done - id: migrate-agent-spawn title: Migrate agent-spawn off child_process to runPoeCommand diff --git a/docs/plans/e2b-integration.md.lock b/docs/plans/e2b-integration.md.lock index b4e16b719a..d7825726e1 100644 --- a/docs/plans/e2b-integration.md.lock +++ b/docs/plans/e2b-integration.md.lock @@ -1 +1 @@ -{"pid":1590,"host":"m5mb-kjopek","acquiredAt":"2026-05-03T12:44:57.666Z"} \ No newline at end of file +{"pid":1590,"host":"m5mb-kjopek","acquiredAt":"2026-05-03T12:49:51.522Z"} \ No newline at end of file diff --git a/packages/process-runner/src/host/host-execution-env.test.ts b/packages/process-runner/src/host/host-execution-env.test.ts new file mode 100644 index 0000000000..0fe8c2fecb --- /dev/null +++ b/packages/process-runner/src/host/host-execution-env.test.ts @@ -0,0 +1,135 @@ +import { describe, expect, it, vi } from "vitest"; +import { hostExecutionEnvFactory } from "./host-execution-env.js"; +import type { OpenSpec, RunHandle } from "../types.js"; + +describe("hostExecutionEnvFactory", () => { + it("round-trips exec through the host runner", async () => { + const env = await hostExecutionEnvFactory.open(createOpenSpec()); + + const handle = env.exec({ + command: process.execPath, + args: ["-e", "process.stdout.write('host-env')"], + stdout: "pipe", + stderr: "pipe" + }); + + await expect(readStream(handle.stdout)).resolves.toBe("host-env"); + await expect(handle.result).resolves.toEqual({ exitCode: 0 }); + expect(env.id).toBe("host"); + expect(env.job).toBeNull(); + }); + + it("treats workspace upload and download as no-ops", async () => { + const env = await hostExecutionEnvFactory.open(createOpenSpec()); + + await expect(env.uploadWorkspace()).resolves.toEqual({ + files: 0, + bytes: 0, + skipped: [] + }); + await expect( + env.downloadWorkspace({ + conflictPolicy: "refuse" + }) + ).resolves.toEqual({ + files: 0, + bytes: 0, + conflicts: [] + }); + await expect(env.close()).resolves.toBeUndefined(); + }); + + it("rejects attach because host runtime cannot reattach", async () => { + await expect(hostExecutionEnvFactory.attach("host")).rejects.toThrow( + "host runtime does not support reattach" + ); + }); + + it("rejects detach because host runtime has no addressable env", async () => { + const env = await hostExecutionEnvFactory.open(createOpenSpec()); + + await expect(env.detach()).rejects.toThrow( + "host runtime does not support detach because host has no addressable env" + ); + }); + + it("opens the configured shell through the host runner with tty enabled", async () => { + const exec = vi.fn(() => createCompletedHandle()); + const createHostRunner = vi.fn(() => ({ + name: "host", + exec + })); + + vi.resetModules(); + vi.doMock("./host-runner.js", () => ({ + createHostRunner + })); + + try { + const { hostExecutionEnvFactory: mockedFactory } = await import("./host-execution-env.js"); + const openSpec = createOpenSpec({ + cwd: "/workspace/project", + env: { + PATH: "/bin", + SHELL: "/bin/custom-shell" + } + }); + + const env = await mockedFactory.open(openSpec); + const handle = env.shell(); + + expect(createHostRunner).toHaveBeenCalledTimes(1); + expect(exec).toHaveBeenCalledWith({ + command: "/bin/custom-shell", + cwd: "/workspace/project", + env: openSpec.env, + stdin: "inherit", + stdout: "inherit", + stderr: "inherit", + tty: true + }); + await expect(handle.result).resolves.toEqual({ exitCode: 0 }); + } finally { + vi.doUnmock("./host-runner.js"); + vi.resetModules(); + } + }); +}); + +function createOpenSpec(overrides: Partial = {}): OpenSpec { + return { + cwd: process.cwd(), + runtime: { type: "host" }, + env: process.env as Record, + uploadIgnoreFiles: [], + jobLabel: { + tool: "node", + argv: [process.execPath] + }, + ...overrides + }; +} + +function createCompletedHandle(): RunHandle { + return { + pid: 123, + stdin: null, + stdout: null, + stderr: null, + result: Promise.resolve({ exitCode: 0 }), + kill() {} + }; +} + +async function readStream(stream: NodeJS.ReadableStream | null): Promise { + if (stream === null) { + return ""; + } + + stream.setEncoding("utf8"); + const chunks: string[] = []; + for await (const chunk of stream) { + chunks.push(String(chunk)); + } + return chunks.join(""); +} diff --git a/packages/process-runner/src/host/host-execution-env.ts b/packages/process-runner/src/host/host-execution-env.ts new file mode 100644 index 0000000000..66ff6c0f79 --- /dev/null +++ b/packages/process-runner/src/host/host-execution-env.ts @@ -0,0 +1,47 @@ +import { createHostRunner } from "./host-runner.js"; +import type { ExecutionEnvFactory, OpenedEnv, RunSpec } from "../types.js"; + +export const hostExecutionEnvFactory: ExecutionEnvFactory = { + type: "host", + async open(openSpec): Promise { + return { + id: "host", + job: null, + async uploadWorkspace() { + return { + files: 0, + bytes: 0, + skipped: [] + }; + }, + async downloadWorkspace() { + return { + files: 0, + bytes: 0, + conflicts: [] + }; + }, + exec(spec: RunSpec) { + return createHostRunner().exec(spec); + }, + async detach() { + throw new Error("host runtime does not support detach because host has no addressable env"); + }, + shell() { + return createHostRunner().exec({ + command: openSpec.env.SHELL || process.env.SHELL || "sh", + cwd: openSpec.cwd, + env: openSpec.env, + stdin: "inherit", + stdout: "inherit", + stderr: "inherit", + tty: true + }); + }, + async close() {} + }; + }, + async attach() { + throw new Error("host runtime does not support reattach"); + } +}; diff --git a/packages/process-runner/src/index.test.ts b/packages/process-runner/src/index.test.ts index e5fc83edb1..e11a8b08c0 100644 --- a/packages/process-runner/src/index.test.ts +++ b/packages/process-runner/src/index.test.ts @@ -4,19 +4,26 @@ import * as api from "./index.js"; import { buildContextArgs, detectContext } from "./docker/context.js"; import { detectEngine, isEngineAvailable } from "./docker/engine.js"; import { createDockerRunner } from "./docker/docker-runner.js"; +import { hostExecutionEnvFactory } from "./host/host-execution-env.js"; import { createHostRunner } from "./host/host-runner.js"; import { createMockRunner, createMockRunnerByCommand } from "./testing/index.js"; import type { + DownloadResult, DockerMount, DockerPortMapping, DockerRunArgs, DockerRunnerOptions, Engine, + ExecutionEnvFactory, HostRunnerOptions, + JobHandle, MockRunBehavior, + OpenedEnv, + OpenSpec, RunHandle, Runner, - RunSpec + RunSpec, + UploadResult } from "@poe-code/process-runner"; describe("@poe-code/process-runner public exports", () => { @@ -101,8 +108,74 @@ describe("@poe-code/process-runner public exports", () => { return handle; } }; + const openSpec: OpenSpec = { + cwd: "/repo", + runtime: { type: "host" }, + env: {}, + uploadIgnoreFiles: [], + jobLabel: { + tool: "node", + argv: ["node", "--version"] + } + }; + const upload: UploadResult = { + files: 0, + bytes: 0, + skipped: [] + }; + const download: DownloadResult = { + files: 0, + bytes: 0, + conflicts: [] + }; + const job: JobHandle = { + id: "job", + envId: "host", + tool: "node", + argv: ["node"], + async status() { + return "running"; + }, + async *stream() {}, + async wait() { + return { exitCode: 0 }; + }, + async kill() {} + }; + const opened: OpenedEnv = { + id: "host", + job, + async uploadWorkspace() { + return upload; + }, + async downloadWorkspace() { + return download; + }, + exec() { + return handle; + }, + async detach() { + return job; + }, + shell() { + return handle; + }, + async close() {} + }; + const factory: ExecutionEnvFactory = { + type: "host", + async open() { + return opened; + }, + async attach() { + return opened; + } + }; expect(runner.exec(spec)).toBe(handle); + await expect(factory.open(openSpec)).resolves.toBe(opened); + await expect(opened.uploadWorkspace()).resolves.toBe(upload); + await expect(opened.downloadWorkspace({ conflictPolicy: "refuse" })).resolves.toBe(download); await expect(handle.result).resolves.toEqual({ exitCode: 0 }); expect(dockerArgs.mounts[0]).toEqual(mount); expect(behavior.stdout).toEqual(["ok"]); @@ -117,6 +190,7 @@ describe("@poe-code/process-runner public exports", () => { expect(api.detectContext).toBe(detectContext); expect(api.detectEngine).toBe(detectEngine); expect(api.isEngineAvailable).toBe(isEngineAvailable); + expect(api.hostExecutionEnvFactory).toBe(hostExecutionEnvFactory); expect(api.createHostRunner).toBe(createHostRunner); expect(api.createDockerRunner).toBe(createDockerRunner); expect(api.createMockRunner).toBe(createMockRunner); @@ -127,6 +201,7 @@ describe("@poe-code/process-runner public exports", () => { "detectEngine", "isEngineAvailable", "createDockerRunner", + "hostExecutionEnvFactory", "createHostRunner", "createMockRunner", "createMockRunnerByCommand" diff --git a/packages/process-runner/src/index.ts b/packages/process-runner/src/index.ts index 6cf5be80d3..b7332b4e77 100644 --- a/packages/process-runner/src/index.ts +++ b/packages/process-runner/src/index.ts @@ -1,19 +1,29 @@ export { buildContextArgs, detectContext } from "./docker/context.js"; export { detectEngine, isEngineAvailable } from "./docker/engine.js"; export { createDockerRunner } from "./docker/docker-runner.js"; +export { hostExecutionEnvFactory } from "./host/host-execution-env.js"; export { createHostRunner } from "./host/host-runner.js"; export { createMockRunner, createMockRunnerByCommand } from "./testing/index.js"; export type { + DownloadResult, DockerMount, DockerPortMapping, DockerRunArgs, DockerRunnerOptions, Engine, + ExecutionEnvFactory, + ExecutionEnvType, HostRunnerOptions, + JobHandle, + JobStatus, + LogChunk, MockRunBehavior, + OpenedEnv, + OpenSpec, RunHandle, RunResult, Runner, - RunSpec + RunSpec, + UploadResult } from "./types.js"; diff --git a/packages/process-runner/src/types.ts b/packages/process-runner/src/types.ts index d067e51167..11c0f8051e 100644 --- a/packages/process-runner/src/types.ts +++ b/packages/process-runner/src/types.ts @@ -34,6 +34,63 @@ export interface HostRunnerOptions { detached?: boolean; } +export type ExecutionEnvType = "host" | "docker" | "e2b"; +export type JobStatus = "running" | "exited" | "killed" | "lost"; + +export interface ExecutionEnvFactory { + readonly type: ExecutionEnvType; + open(spec: OpenSpec): Promise; + attach(envId: string): Promise; +} + +export interface OpenSpec { + cwd: string; + runtime: unknown; + runner?: unknown; + env: Record; + uploadIgnoreFiles: string[]; + jobLabel: { tool: string; argv: string[] }; +} + +export interface UploadResult { + files: number; + bytes: number; + skipped: { path: string; bytes: number; reason: "max_size" }[]; +} + +export interface DownloadResult { + files: number; + bytes: number; + conflicts: { path: string; reason: "local_modified" }[]; +} + +export interface LogChunk { + byteOffset: number; + data: string; +} + +export interface OpenedEnv { + readonly id: string; + readonly job: JobHandle | null; + uploadWorkspace(): Promise; + downloadWorkspace(opts: { conflictPolicy: "refuse" | "overwrite" }): Promise; + exec(spec: RunSpec): RunHandle; + detach(): Promise; + shell(): RunHandle; + close(): Promise; +} + +export interface JobHandle { + readonly id: string; + readonly envId: string; + readonly tool: string; + readonly argv: string[]; + status(): Promise; + stream(opts?: { sinceByte?: number }): AsyncIterable; + wait(): Promise<{ exitCode: number }>; + kill(signal?: NodeJS.Signals): Promise; +} + export type Engine = "docker" | "podman"; export interface DockerMount { From 99da17a2752714c550b08efab4b8be765fca40d3 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 09:16:02 -0400 Subject: [PATCH 013/111] feat(agent-spawn): route spawns through execution harness --- docs/plans/agent-harness.md | 407 +++++++++++++++++- docs/plans/e2b-integration.md | 4 +- docs/plans/e2b-integration.md.lock | 2 +- package-lock.json | 5 +- .../src/execution-env.test.ts | 4 +- .../agent-harness-tools/src/execution-env.ts | 14 + .../src/run-poe-command.ts | 243 +++++++++-- packages/agent-spawn/package.json | 5 +- packages/agent-spawn/src/index.ts | 8 +- .../agent-spawn/src/register-factories.ts | 98 +++++ packages/agent-spawn/src/runtime.ts | 158 +++++++ packages/agent-spawn/src/spawn-interactive.ts | 61 ++- packages/agent-spawn/src/spawn.ts | 162 +++---- packages/agent-spawn/src/types.ts | 7 +- .../src/host/host-execution-env.ts | 6 +- .../src/host/host-runner.test.ts | 68 +++ .../process-runner/src/host/host-runner.ts | 19 +- packages/process-runner/src/types.ts | 16 +- 18 files changed, 1103 insertions(+), 184 deletions(-) create mode 100644 packages/agent-spawn/src/register-factories.ts create mode 100644 packages/agent-spawn/src/runtime.ts diff --git a/docs/plans/agent-harness.md b/docs/plans/agent-harness.md index 7f1fc44a26..baddcb6915 100644 --- a/docs/plans/agent-harness.md +++ b/docs/plans/agent-harness.md @@ -122,12 +122,413 @@ Each is one `.ajs` + one `.md`. The existing `experiment run` / `ralph run` / et ## 3. Implementation details and technical decisions -To be drafted next. +### Package layout + +New package `@poe-code/agent-harness` at `packages/agent-harness/`. Owns the loader, the discovery / pairing logic, the per-harness templates, and the codegen entry point. Depends on `@poe-code/agent-script`, `@poe-code/agent-harness-tools`, `@poe-code/toolcraft-schema`. + +```text +packages/agent-harness/ + src/ + loader/ # paired-file loader: discover, pair, validate, run + pair.ts # resolve .ajs ↔ .md + extract-schema.ts # AST-level pull of `export const schema` initializer + validate.ts # toolcraft-schema validator over frontmatter + run.ts # public runHarnessPair() + modules/ + schema.ts # makeSchemaModule(): exposes toolcraft-schema `S` to .ajs + codegen/ + emit-schemas.ts # walks installed templates, emits docs/schemas/harnesses/*.json + templates/ + ralph/{ralph.ajs,ralph.md} + experiment/{experiment.ajs,experiment.md} + pipeline/{pipeline.ajs,pipeline.md} + superintendent/{superintendent.ajs,superintendent.md} + cli/ # `poe-code harness {run,new,list}` command bodies + index.ts +``` + +### Subset extensions to agent-script + +Three additions, all gated to top-level use only. + +1. **`ExportNamedDeclaration`** — `export const NAME = expr;`. Limited to a single declarator. Allowlist of names is configured per-host: agent-harness allows `schema`. Anything else is `AS-EXPORT-UNKNOWN`. Keeps the surface narrow; nothing else can be exported. +2. **`ExportDefaultDeclaration`** — `export default expr;`. Initializer must be an arrow function expression (sync or async). Exactly one per file. Lint code `AS-EXPORT-DEFAULT-MISSING` / `AS-EXPORT-DEFAULT-MULTIPLE` / `AS-EXPORT-DEFAULT-NOT-ARROW`. +3. **`MetaProperty` for `import.meta`** — recognized as an expression. Resolves at runtime to a host-injected sandbox object. Cannot be assigned to (`import.meta.x = ...` is a lint error). + +Top-level `return` becomes a lint warning in `.ajs` files paired with markdown (`AS-RETURN-AT-TOP`); the new shape uses the default export's return value. + +Existing single-file harness markdowns (`packages/agent-script/examples/*.md`) keep working — the legacy top-level-return path stays. The new package only consumes the new shape. + +### `schema` host module + +```ts +// packages/agent-harness/src/modules/schema.ts +import { S } from "@poe-code/toolcraft-schema"; + +export function makeSchemaModule(): { S: typeof S } { + return { S }; +} +``` + +Registered as `schema` for both lint and execution. The builders are pure — no IO, no host bridge needed. This lets the loader run the schema initializer in the standard interpreter without special-casing pure evaluation. + +### Two-pass loader + +```ts +async function runHarnessPair(mdPath: string, options: RunHarnessPairOptions): Promise { + const ajsPath = await resolvePair(mdPath); // .md ↔ .ajs + const ajsSource = await readFile(ajsPath, "utf8"); + const { frontmatter, body } = splitFrontmatter(await readFile(mdPath, "utf8")); + + // Pass 1: lint, then evaluate just `export const schema` if present + const ast = parse(ajsSource, ajsPath); + lint(ajsSource, { filename: ajsPath, modules: lintModulesFor(options) }); + const schemaInit = findExportedConstInitializer(ast, "schema"); + const schema = schemaInit + ? await evaluateSchemaInitializer(schemaInit, { schemaModule: makeSchemaModule() }) + : undefined; + + // Validate frontmatter (no-op if no schema) + const validated = schema ? validate(schema, frontmatter) : frontmatter; + + // Pass 2: full execution; default export receives validated frontmatter + return run(ajsSource, { + modules: options.modulesFor(validated, { kind: validated.kind, version: validated.version, filepath: mdPath, body }), + importMeta: { kind: validated.kind, version: validated.version, filename: mdPath, dirname: path.dirname(mdPath), body }, + entryPointArgs: [validated], + signal: options.signal, + snapshotPath: options.snapshotPath, + }); +} +``` + +`run()` gets two new options — `importMeta` (object injected as `import.meta`) and `entryPointArgs` (forwarded to the resolved default export). When `entryPointArgs` is set, the runtime treats the resolved default export as the entry instead of expecting a top-level returned value. + +`evaluateSchemaInitializer` reuses the existing interpreter with a stripped-down module registry (only `schema`) and a tight budget. Initializer that calls anything not exported by `schema` is a lint error before this step. + +### Runtime validator on toolcraft-schema + +`@poe-code/toolcraft-schema` gains `validate(schema, value)` returning `{ ok: true, value } | { ok: false, errors: ValidationError[] }`. Walks the descriptor mirror of `toJsonSchema`. Zero-dep, no ajv. Errors carry `path` (dotted), `expected`, `received`. Validation failure surfaces to the user with the `.md` filepath and the offending field path. + +### Codegen + +`scripts/generate-plan-schemas.ts` is replaced by a script that walks `packages/agent-harness/src/templates/*/`, statically loads each `.ajs`'s `export const schema`, and emits `docs/schemas/harnesses/.schema.json` via `toJsonSchema(schema)`. Wired in as `npm run codegen:harness-schemas`, replacing `npm run codegen:plan-schemas`. + +The existing `docs/schemas/plans/*.schema.json` paths are kept (with redirects from `harnesses/`) for backward compat with `$schema` URLs already written into user files. + +### Locks, run logs, snapshots + +All cross-cutting concerns reuse `@poe-code/agent-harness-tools`: + +- **Lock**: `lockWorkflow(mdPath)` before pass 1; release on completion or error. Existing `.lock` file convention. +- **Run logs**: `resolveRunLogDir({ planPath: mdPath, runner: "harness", homeDir })`. Each `event(...)` call from the orchestrator is appended as JSONL. +- **Snapshot**: `snapshotPath = resolveRunLogDir(...) + "/snapshot.json"`. Passed straight to `agent-script`'s `run({ snapshotPath, snapshotIntervalMs })`. On rerun, the loader reads it and passes it to `run({ snapshot })` — agent-script's existing `restore()` validates source-hash match before resuming. + +### Migration of existing packages + +Each of `experiment-loop`, `ralph`, `pipeline`, `superintendent` shrinks to: + +- A frontmatter type re-export from `agent-harness`'s shipped schema (`Static`). +- A discovery helper if the doc layout is custom. +- Nothing else — no bespoke runtime, no JsonSchema literal, no `parseFrontmatterData`. + +CLI commands in `src/cli/commands/{experiment,ralph,pipeline,superintendent}.ts` keep their flags and dashboards but their `run` action becomes a thin call into `runHarnessPair` with the appropriate template name. The `agent-script/examples/*.md` single-file harnesses stay as legacy demos — they don't migrate. + +### Edge cases + +- **No `export const schema`** — frontmatter passes through to the entry as the raw parsed YAML (untyped). Allowed; useful for trivial harnesses. +- **No `.md` paired** — hard error. Every `.ajs` requires a `.md`. +- **No `.ajs` paired** — hard error. Every `.md` discovered as a harness target requires a sibling `.ajs`. +- **Schema initializer references a non-pure value** — caught by lint. `schema` module is the only allowed import inside the initializer. +- **Default export is not an arrow** — lint error. Arrow + async arrow only. +- **Frontmatter fails validation** — runner exits non-zero with a message naming the `.md` path and the failing field. Snapshot is not touched. +- **Source hash drift on resume** — existing `restore()` behavior: the snapshot is rejected, the run starts fresh. +- **Concurrent runs against the same `.md`** — `lockWorkflow` rejects the second one with `EEXIST`. +- **Top-level `import.meta` aliasing (`const m = import.meta`)** — supported. Subsequent `m.body` works because `MetaProperty` resolves to a sandbox object with normal property access. ## 4. Interfaces and test plan -To be drafted next. +### Public API of `@poe-code/agent-harness` + +```ts +export type HarnessImportMeta = { + kind: string | undefined; + version: number | undefined; + filename: string; + dirname: string; + body: string; +}; + +export type HarnessPair = { + ajsPath: string; + mdPath: string; + basename: string; +}; + +export type RunHarnessPairOptions = { + modulesFor: ( + frontmatter: Record, + meta: HarnessImportMeta + ) => ModuleRegistry; + signal?: AbortSignal; + snapshotPath?: string; +}; + +export function resolvePair(mdPath: string): Promise; +export function discoverHarnesses(rootDir: string): Promise; +export function runHarnessPair( + mdPath: string, + options: RunHarnessPairOptions +): Promise; + +export function listBuiltinTemplates(): readonly { kind: string; ajsPath: string; mdPath: string }[]; +export function scaffoldFromTemplate( + kind: string, + destination: { dir: string; basename: string } +): Promise; +``` + +### New surface on `@poe-code/agent-script` + +```ts +// run.ts — additions to RunOptions +export type RunOptions = { + // ...existing fields + importMeta?: Record; + entryPointArgs?: readonly unknown[]; +}; + +// parser AST additions +export type ExportNamedDeclaration = BaseNode & { + type: "ExportNamedDeclaration"; + declaration: VariableDeclaration; // const only, single declarator +}; +export type ExportDefaultDeclaration = BaseNode & { + type: "ExportDefaultDeclaration"; + declaration: ArrowFunctionExpression; +}; +export type MetaProperty = BaseNode & { + type: "MetaProperty"; + meta: Identifier; // "import" + property: Identifier; // "meta" +}; + +// new public helper +export function findExportedConstInitializer( + module: Module, + name: string +): Expression | undefined; +``` + +### New surface on `@poe-code/toolcraft-schema` + +```ts +export type ValidationIssue = { + path: readonly string[]; + expected: string; + received: string; + message: string; +}; +export type ValidationResult = + | { ok: true; value: T } + | { ok: false; issues: readonly ValidationIssue[] }; + +export function validate( + schema: S, + value: unknown +): ValidationResult>; +``` + +### Test plan + +#### `@poe-code/toolcraft-schema` + +- Unit: `validate()` accepts every `S.*` builder, surfaces typed issues, applies `default` for missing optionals, rejects unknown properties on `S.Object` (matching emitted `additionalProperties: false`). +- Snapshot: `toJsonSchema(schema)` output for each builder remains stable. + +#### `@poe-code/agent-script` + +- Parser: `export const x = …`, `export default async () => {}`, `import.meta`, `import.meta.X`. Reject `export function`, `export class`, `export *`, multiple `export default`, top-level `import.meta = …`. +- Linter: only `schema` is allowlisted as a named export (configurable per registry via lint options); unknown export names emit `AS-EXPORT-UNKNOWN`. `AS-RETURN-AT-TOP` warns when `.ajs` has both top-level `return` and `export default`. +- Runtime: `run({ importMeta, entryPointArgs })` resolves the default export and invokes it with `entryPointArgs`. Cancellation between host calls inside the entry still throws `SandboxError("aborted")`. Snapshot/restore round-trip works across an aborted entry call. + +#### `@poe-code/agent-harness` + +- `resolvePair`: pairs by basename in same dir, surfaces `MissingPair` errors, ignores non-`.md`/`.ajs` siblings. +- `discoverHarnesses`: walks `.poe-code/harnesses/` and `/.poe-code/harnesses/`, returns deduped list (project beats user). +- `extractSchema`: returns `undefined` when absent, returns evaluated descriptor when present, errors when initializer references non-`schema` modules. +- `runHarnessPair`: + - happy path: validates frontmatter, invokes default export, returns its result. + - missing schema: passes raw frontmatter through. + - failing validation: rejects with named field path, leaves snapshot untouched, releases lock. + - missing default export: lint error before run. + - top-level `return` in `.ajs`: lint warning, run still proceeds. + - resume: on a second invocation with a snapshot, the entry resumes from the next host call. +- Lock: second concurrent run against same `.md` errors with `EEXIST`. +- All filesystem state through `memfs` per CLAUDE.md. + +#### Integration + +- Run each shipped template (`ralph`, `experiment`, `pipeline`, `superintendent`) end-to-end with a stub `agent` module. Assert: result, journal entries, snapshot file exists and parses. +- CLI: `poe-code harness run ` happy path, `harness new `, `harness list`. Use `npm run dev -- harness ...` for spot tests; rely on screenshot tests for visual UI surfaces. + +#### Migration / regression + +- For each of `experiment-loop`, `ralph`, `pipeline`, `superintendent`, run the package's existing test suite against the post-migration code. The bespoke runtime tests get retargeted: anything testing the runner itself moves to `agent-harness`; anything testing the discovery / CLI surface stays in the package. +- Fixture compare: take a representative `.md` from each runner, run it under the bespoke implementation and again under the harness pair, assert equivalent journal output. + +### Autonomy checklist + +What an agent needs to build the package end-to-end without coming back: + +- This document for level 1–5 context. +- Existing `agent-script` parser/lint/run code as the reference for adding `Export*` and `MetaProperty` AST nodes. +- Existing `toolcraft-schema` builders and `toJsonSchema` as the reference for `validate`. +- Existing `agent-harness-tools` (lock, run-logs, paths) — used as-is. +- Existing per-package frontmatter files as the reference for what fields each shipped template's schema has to cover. +- The current `scripts/generate-plan-schemas.ts` as the reference for the codegen replacement. + +### Rollout + +1. Land subset extensions + validator (no consumers yet) — green build. +2. Land `agent-harness` package with templates + tests, behind `experimental` only — no CLI exposure yet. +3. Switch `experiment run` / `ralph run` / `pipeline run` / `superintendent run` internals to `runHarnessPair` one at a time, keeping the bespoke implementation as a fallback flag for one release. +4. Delete bespoke runtimes; collapse each package to its shrunk shape. +5. Replace `codegen:plan-schemas` with `codegen:harness-schemas`. Add 301-style redirects from old `$schema` URLs. ## 5. Code plan -To be drafted next. +Build order keeps the branch green at every step. Each step is one PR. + +### Step 1 — `toolcraft-schema` validator + +Files to create: + +- `packages/toolcraft-schema/src/validate.ts` +- `packages/toolcraft-schema/src/validate.test.ts` + +Files to change: + +- `packages/toolcraft-schema/src/index.ts` — re-export `validate`, `ValidationIssue`, `ValidationResult`. + +Signatures: + +- `function validate(schema: S, value: unknown): ValidationResult>` +- internal: `function walk(schema: SchemaDescriptor, value: unknown, path: readonly string[], issues: ValidationIssue[]): unknown` + +### Step 2 — agent-script subset extensions + +Files to create: + +- `packages/agent-script/src/parse/parse-export.ts` +- `packages/agent-script/src/parse/parse-import-meta.ts` +- `packages/agent-script/src/loader/find-exported.ts` +- `packages/agent-script/src/loader/find-exported.test.ts` + +Files to change: + +- `packages/agent-script/src/parse/parser.ts` — add `ExportNamedDeclaration`, `ExportDefaultDeclaration`, `MetaProperty` to `Statement`/`Expression` unions; wire token-level entrypoints. +- `packages/agent-script/src/lint.ts` — add `AS-EXPORT-UNKNOWN`, `AS-EXPORT-DEFAULT-MISSING`, `AS-EXPORT-DEFAULT-MULTIPLE`, `AS-EXPORT-DEFAULT-NOT-ARROW`, `AS-RETURN-AT-TOP`, `AS-IMPORT-META-ASSIGN`. Accept `allowedExportNames` in `LintOptions`. +- `packages/agent-script/src/run.ts` — add `importMeta?` and `entryPointArgs?` to `RunOptions`. When `entryPointArgs` is set, after evaluating the module, look up the default export binding and call it with the args; the result becomes `returnValue`. +- `packages/agent-script/src/interp/scope.ts` — bind `import.meta` resolution to the runtime-injected value. +- `packages/agent-script/src/index.ts` — export `findExportedConstInitializer`, the new AST types. + +Signatures: + +- `function findExportedConstInitializer(module: Module, name: string): Expression | undefined` + +### Step 3 — `agent-harness` package skeleton + +Files to create: + +- `packages/agent-harness/package.json` +- `packages/agent-harness/README.md` +- `packages/agent-harness/tsconfig.json` +- `packages/agent-harness/src/index.ts` +- `packages/agent-harness/src/loader/pair.ts` +- `packages/agent-harness/src/loader/pair.test.ts` +- `packages/agent-harness/src/loader/extract-schema.ts` +- `packages/agent-harness/src/loader/extract-schema.test.ts` +- `packages/agent-harness/src/loader/validate.ts` +- `packages/agent-harness/src/loader/validate.test.ts` +- `packages/agent-harness/src/loader/run.ts` +- `packages/agent-harness/src/loader/run.test.ts` +- `packages/agent-harness/src/modules/schema.ts` +- `packages/agent-harness/src/modules/schema.test.ts` +- `packages/agent-harness/src/discovery/discover.ts` +- `packages/agent-harness/src/discovery/discover.test.ts` +- `packages/agent-harness/src/templates/index.ts` + +Signatures: + +- `function resolvePair(mdPath: string, fs?: HarnessFs): Promise` +- `function discoverHarnesses(rootDir: string, fs?: HarnessFs): Promise` +- `function extractSchema(ajsSource: string, ajsPath: string): Promise` +- `function validateFrontmatter(schema: SchemaDescriptor, frontmatter: Record): Record` (throws with named field path on failure) +- `function runHarnessPair(mdPath: string, options: RunHarnessPairOptions): Promise` +- `function makeSchemaModule(): { S: typeof S }` + +### Step 4 — built-in templates + +Files to create: + +- `packages/agent-harness/src/templates/ralph/ralph.ajs` +- `packages/agent-harness/src/templates/ralph/ralph.md` +- `packages/agent-harness/src/templates/experiment/experiment.ajs` +- `packages/agent-harness/src/templates/experiment/experiment.md` +- `packages/agent-harness/src/templates/pipeline/pipeline.ajs` +- `packages/agent-harness/src/templates/pipeline/pipeline.md` +- `packages/agent-harness/src/templates/superintendent/superintendent.ajs` +- `packages/agent-harness/src/templates/superintendent/superintendent.md` +- `packages/agent-harness/src/templates/index.test.ts` — fixture tests that each template lints, frontmatter validates, runs against stub modules. + +Each `.ajs` declares `export const schema = S.Object({...})` and `export default async (frontmatter) => {...}`. The `.md` carries default frontmatter equivalent to today's `parseFrontmatter` defaults. + +### Step 5 — codegen + CLI + +Files to create: + +- `packages/agent-harness/src/codegen/emit-schemas.ts` +- `packages/agent-harness/src/codegen/emit-schemas.test.ts` +- `src/cli/commands/harness.ts` +- `src/cli/commands/harness-command.test.ts` +- `scripts/generate-harness-schemas.ts` — one-line wrapper over the codegen entry. + +Files to change: + +- `package.json` — replace `codegen:plan-schemas` with `codegen:harness-schemas`. `build` script updated. +- `src/cli/index.ts` (or wherever commands register) — register `harness` command. +- `docs/schemas/plans/*.schema.json` — regenerated; old paths kept as aliases via redirect file. + +### Step 6 — migrate `ralph` + +Files to change: + +- `packages/ralph/src/index.ts` — drop `runRalph`, re-export only types and the discovery helper. +- `packages/ralph/src/frontmatter/frontmatter.ts` — replace `JsonSchema` literal + `parseFrontmatterData` with `Static` import from `agent-harness/templates/ralph/schema`. +- `packages/ralph/src/run/ralph.ts` — delete. +- `src/cli/commands/ralph.ts` — `run` action calls `runHarnessPair` against the discovered `.md` paired with the shipped `ralph.ajs`. Dashboard wiring stays. +- `src/sdk/ralph.ts` — same swap. + +### Step 7 — migrate `experiment-loop`, `pipeline`, `superintendent` + +Same shape as Step 6, repeated per package. Each PR: + +- Replace bespoke runtime with `runHarnessPair` against the shipped template. +- Collapse the package to types + discovery + schema re-export. +- Retarget tests: runtime tests move to `agent-harness`; CLI / discovery tests stay. + +### Step 8 — cleanup + +Files to delete: + +- `packages/experiment-loop/src/run/` +- `packages/ralph/src/run/` +- `packages/pipeline/src/run/` +- `packages/superintendent/src/runtime/` (keep `agentic-tools.ts` if still consumed by the harness templates) +- `scripts/generate-plan-schemas.ts` + +Files to change: + +- All four package READMEs to reflect the harness pair model. +- Top-level `README.md` if it documents the bespoke runners. diff --git a/docs/plans/e2b-integration.md b/docs/plans/e2b-integration.md index 9aaf8bd682..03172eca09 100644 --- a/docs/plans/e2b-integration.md +++ b/docs/plans/e2b-integration.md @@ -290,8 +290,8 @@ tasks: that calls `registerExecutionEnvFactory(hostExecutionEnvFactory)` — imported once from the spawn entrypoint and from each tool entry. status: - implement: open - test: open + implement: done + test: done commit: open - id: migrate-loop-tools diff --git a/docs/plans/e2b-integration.md.lock b/docs/plans/e2b-integration.md.lock index d7825726e1..0b1256b664 100644 --- a/docs/plans/e2b-integration.md.lock +++ b/docs/plans/e2b-integration.md.lock @@ -1 +1 @@ -{"pid":1590,"host":"m5mb-kjopek","acquiredAt":"2026-05-03T12:49:51.522Z"} \ No newline at end of file +{"pid":1590,"host":"m5mb-kjopek","acquiredAt":"2026-05-03T13:15:19.895Z"} \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index c327951376..23fde9eef5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7006,8 +7006,11 @@ "version": "0.0.1", "dependencies": { "@poe-code/agent-defs": "*", + "@poe-code/agent-harness-tools": "*", "@poe-code/design-system": "*", - "@poe-code/poe-acp-client": "*" + "@poe-code/poe-acp-client": "*", + "@poe-code/poe-code-config": "*", + "@poe-code/process-runner": "*" } }, "packages/auth-store": { diff --git a/packages/agent-harness-tools/src/execution-env.test.ts b/packages/agent-harness-tools/src/execution-env.test.ts index 27657a31e4..1c41ccc485 100644 --- a/packages/agent-harness-tools/src/execution-env.test.ts +++ b/packages/agent-harness-tools/src/execution-env.test.ts @@ -78,8 +78,8 @@ describe("execution env registry", () => { expect(branchSites).toMatchInlineSnapshot(` [ - "execution-env.ts:71:const factory = executionEnvFactories.get(runtime.type);", - "execution-env.ts:74:\`No execution environment factory registered for runtime type "\${runtime.type}".\`", + "execution-env.ts:85:const factory = executionEnvFactories.get(runtime.type);", + "execution-env.ts:88:\`No execution environment factory registered for runtime type "\${runtime.type}".\`", ] `); }); diff --git a/packages/agent-harness-tools/src/execution-env.ts b/packages/agent-harness-tools/src/execution-env.ts index bcd833ba90..dc123e197c 100644 --- a/packages/agent-harness-tools/src/execution-env.ts +++ b/packages/agent-harness-tools/src/execution-env.ts @@ -20,6 +20,20 @@ export interface OpenSpec { env: Record; uploadIgnoreFiles: string[]; jobLabel: { tool: string; argv: string[] }; + execution?: { + wrapForLogTee?: boolean; + stdin?: RunSpec["stdin"]; + stdout?: RunSpec["stdout"]; + stderr?: RunSpec["stderr"]; + env?: RunSpec["env"]; + tty?: boolean; + input?: string | Buffer; + captureOutput?: boolean; + activityTimeoutMs?: number; + onStdout?(chunk: string): void; + onStderr?(chunk: string): void; + }; + shellSpec?: RunSpec; } export interface UploadResult { diff --git a/packages/agent-harness-tools/src/run-poe-command.ts b/packages/agent-harness-tools/src/run-poe-command.ts index f9f662440e..1a399cc516 100644 --- a/packages/agent-harness-tools/src/run-poe-command.ts +++ b/packages/agent-harness-tools/src/run-poe-command.ts @@ -1,12 +1,8 @@ import { randomBytes } from "node:crypto"; import type { StateManager } from "@poe-code/poe-code-config"; import type { RunHandle } from "@poe-code/process-runner"; -import type { - DownloadResult, - ExecutionEnvFactory, - OpenedEnv, - OpenSpec -} from "./execution-env.js"; +import type { Readable } from "node:stream"; +import type { DownloadResult, ExecutionEnvFactory, OpenedEnv, OpenSpec } from "./execution-env.js"; import { waitForExit, wrapForLogTee, type LogStreamEnv } from "./log-stream.js"; const ULID_ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"; @@ -18,11 +14,19 @@ export async function runPoeCommand(opts: { state: StateManager; signal?: AbortSignal; }): Promise< - | { kind: "sync"; exitCode: number; download: DownloadResult } + | { + kind: "sync"; + exitCode: number; + download: DownloadResult; + stdout?: string; + stderr?: string; + } | { kind: "detached"; jobId: string; envId: string } > { const jobId = createUlid(); - await opts.state.jobs.put({ + const execution = opts.openSpec.execution; + const wrapCommand = execution?.wrapForLogTee !== false; + const pendingJob = opts.state.jobs.put({ id: jobId, env_id: "", env_kind: opts.factory.type, @@ -33,30 +37,43 @@ export async function runPoeCommand(opts: { status: "pending" }); - const env = await opts.factory.open(opts.openSpec); + const opened = opts.factory.open(opts.openSpec); + const env = isPromiseLike(opened) ? await opened : opened; let shouldClose = true; try { - await env.uploadWorkspace(); - const wrappedArgv = wrapForLogTee(opts.openSpec.jobLabel.argv, jobId); - const handle = env.exec({ - command: wrappedArgv[0], - args: wrappedArgv.slice(1), - cwd: opts.openSpec.cwd, - env: opts.openSpec.env, - stdin: "inherit", - stdout: "pipe", - stderr: "pipe", - signal: opts.signal - }); + const upload = env.uploadWorkspace(); + const argv = wrapCommand + ? wrapForLogTee(opts.openSpec.jobLabel.argv, jobId) + : opts.openSpec.jobLabel.argv; + const handle = execution?.tty + ? env.shell() + : env.exec({ + command: argv[0], + args: argv.slice(1), + cwd: opts.openSpec.cwd, + env: execution && "env" in execution ? execution.env : opts.openSpec.env, + stdin: execution?.stdin ?? "inherit", + stdout: execution?.stdout ?? "pipe", + stderr: execution?.stderr ?? "pipe", + signal: opts.signal + }); - await opts.state.jobs.update(jobId, { - status: "running", - env_id: env.id, - started_at: new Date().toISOString() - }); + if (execution?.input !== undefined) { + handle.stdin?.setDefaultEncoding("utf8"); + handle.stdin?.end(execution.input); + } + + const runningJob = Promise.all([pendingJob, upload]).then(() => + opts.state.jobs.update(jobId, { + status: "running", + env_id: env.id, + started_at: new Date().toISOString() + }) + ); if (opts.detach) { + await runningJob; shouldClose = false; return { kind: "detached", jobId, envId: env.id }; } @@ -66,8 +83,10 @@ export async function runPoeCommand(opts: { handle, jobId, openSpec: opts.openSpec, - signal: opts.signal + signal: opts.signal, + wrapCommand }); + await runningJob; shouldClose = false; await opts.state.jobs.update(jobId, { @@ -76,7 +95,13 @@ export async function runPoeCommand(opts: { exited_at: new Date().toISOString() }); - return { kind: "sync", exitCode: result.exitCode, download: result.download }; + return { + kind: "sync", + exitCode: result.exitCode, + download: result.download, + ...(result.stdout !== undefined ? { stdout: result.stdout } : {}), + ...(result.stderr !== undefined ? { stderr: result.stderr } : {}) + }; } finally { if (shouldClose) { await env.close(); @@ -90,49 +115,148 @@ async function runSync(opts: { jobId: string; openSpec: OpenSpec; signal?: AbortSignal; -}): Promise<{ exitCode: number; download: DownloadResult }> { - opts.handle.stdout?.pipe(process.stdout, { end: false }); - opts.handle.stderr?.pipe(process.stderr, { end: false }); - const abort = createAbortSync(opts.signal, opts.handle); + wrapCommand: boolean; +}): Promise<{ exitCode: number; download: DownloadResult; stdout?: string; stderr?: string }> { + const execution = opts.openSpec.execution; + const capture = execution?.captureOutput === true; + const abort = createAbortSync(opts.signal, opts.handle, execution?.activityTimeoutMs); + const streamState = capture + ? captureRunStreams(opts.handle, execution, abort.resetActivityTimer) + : pipeRunStreams(opts.handle); + abort.resetActivityTimer(); try { - const { exitCode } = await abort.waitForExit(opts.env, opts.jobId); + const { exitCode } = opts.wrapCommand + ? await abort.waitForExit(opts.env, opts.jobId) + : await abort.waitForHandle(); const download = await opts.env.downloadWorkspace({ conflictPolicy: opts.openSpec.runner?.download_conflict ?? "refuse" }); await opts.env.close(); - return { exitCode, download }; + return { + exitCode, + download, + ...(capture ? { stdout: streamState.stdout(), stderr: streamState.stderr() } : {}) + }; } finally { abort.dispose(); - opts.handle.stdout?.unpipe(process.stdout); - opts.handle.stderr?.unpipe(process.stderr); + streamState.dispose(); } } +function pipeRunStreams(handle: RunHandle): { + stdout(): string; + stderr(): string; + dispose(): void; +} { + handle.stdout?.pipe(process.stdout, { end: false }); + handle.stderr?.pipe(process.stderr, { end: false }); + return { + stdout: () => "", + stderr: () => "", + dispose() { + handle.stdout?.unpipe(process.stdout); + handle.stderr?.unpipe(process.stderr); + } + }; +} + +function captureRunStreams( + handle: RunHandle, + execution: NonNullable | undefined, + onActivity: () => void +): { + stdout(): string; + stderr(): string; + dispose(): void; +} { + let stdout = ""; + let stderr = ""; + const listeners: Array<() => void> = []; + + const bind = (stream: Readable | null, onChunk: (chunk: string) => void): void => { + if (!stream) return; + stream.setEncoding("utf8"); + const listener = (chunk: string | Buffer) => { + onActivity(); + onChunk(chunk.toString()); + }; + stream.on("data", listener); + listeners.push(() => { + stream.off("data", listener); + }); + }; + + bind(handle.stdout, (chunk) => { + stdout += chunk; + execution?.onStdout?.(chunk); + }); + bind(handle.stderr, (chunk) => { + stderr += chunk; + execution?.onStderr?.(chunk); + }); + + return { + stdout: () => stdout, + stderr: () => stderr, + dispose() { + for (const remove of listeners) { + remove(); + } + } + }; +} + function createAbortSync( signal: AbortSignal | undefined, - handle: RunHandle + handle: RunHandle, + activityTimeoutMs: number | undefined ): { waitForExit(env: OpenedEnv, jobId: string): Promise<{ exitCode: number }>; + waitForHandle(): Promise<{ exitCode: number }>; + resetActivityTimer(): void; dispose(): void; } { + let activityTimer: ReturnType | undefined; + let timedOut = false; + const resetActivityTimer = activityTimeoutMs + ? () => { + if (activityTimer) clearTimeout(activityTimer); + activityTimer = setTimeout(() => { + timedOut = true; + handle.kill("SIGTERM"); + notifyAbort?.(); + }, activityTimeoutMs); + } + : () => {}; + let notifyAbort: (() => void) | undefined; + if (signal === undefined) { return { waitForExit: (env, jobId) => waitForExit(toLogStreamEnv(env), jobId), - dispose() {} + waitForHandle: async () => { + const result = await handle.result; + if (timedOut) { + throw createActivityTimeoutError(activityTimeoutMs!); + } + return result; + }, + resetActivityTimer, + dispose() { + if (activityTimer) clearTimeout(activityTimer); + } }; } const exitWaitController = new AbortController(); let aborted = signal.aborted; - let notifyAbort!: () => void; const abortedPromise = new Promise((resolve) => { notifyAbort = resolve; }); const kill = () => { aborted = true; handle.kill("SIGTERM"); - notifyAbort(); + notifyAbort?.(); }; if (signal.aborted) { @@ -169,7 +293,30 @@ function createAbortSync( exitWaitController.abort(); return handle.result; }, + async waitForHandle() { + const result = await Promise.race([ + handle.result.then((value) => ({ kind: "exit" as const, value })), + abortedPromise.then(() => ({ kind: "abort" as const })) + ]); + + if (result.kind === "exit") { + if (aborted) { + throw createAbortError(); + } + if (timedOut) { + throw createActivityTimeoutError(activityTimeoutMs!); + } + return result.value; + } + + if (timedOut) { + throw createActivityTimeoutError(activityTimeoutMs!); + } + throw createAbortError(); + }, + resetActivityTimer, dispose() { + if (activityTimer) clearTimeout(activityTimer); exitWaitController.abort(); signal.removeEventListener("abort", kill); } @@ -181,6 +328,22 @@ function toLogStreamEnv(env: OpenedEnv): LogStreamEnv { return candidate.fs === undefined ? {} : { fs: candidate.fs }; } +function isPromiseLike(value: T | Promise): value is Promise { + return typeof (value as Promise).then === "function"; +} + +function createAbortError(): Error { + const error = new Error("Agent spawn aborted"); + error.name = "AbortError"; + return error; +} + +function createActivityTimeoutError(timeoutMs: number): Error { + const error = new Error(`Agent spawn timed out after ${timeoutMs / 1000}s of inactivity`); + error.name = "ActivityTimeoutError"; + return error; +} + function createUlid(): string { const time = BigInt(Date.now()); const random = randomBytes(10); diff --git a/packages/agent-spawn/package.json b/packages/agent-spawn/package.json index d63cbb9be8..71e40ea7a2 100644 --- a/packages/agent-spawn/package.json +++ b/packages/agent-spawn/package.json @@ -25,7 +25,10 @@ ], "dependencies": { "@poe-code/agent-defs": "*", + "@poe-code/agent-harness-tools": "*", "@poe-code/design-system": "*", - "@poe-code/poe-acp-client": "*" + "@poe-code/poe-acp-client": "*", + "@poe-code/poe-code-config": "*", + "@poe-code/process-runner": "*" } } diff --git a/packages/agent-spawn/src/index.ts b/packages/agent-spawn/src/index.ts index 154e5d9a81..b37fa77af1 100644 --- a/packages/agent-spawn/src/index.ts +++ b/packages/agent-spawn/src/index.ts @@ -1,3 +1,5 @@ +import "./register-factories.js"; + export const agentSpawn = {}; export { @@ -45,11 +47,7 @@ export { export { spawn } from "./spawn.js"; export { spawnInteractive } from "./spawn-interactive.js"; export { spawnAutonomous } from "./autonomous.js"; -export type { - AutonomousOptions, - StreamingSpawnFn, - StreamingSpawnReturn -} from "./autonomous.js"; +export type { AutonomousOptions, StreamingSpawnFn, StreamingSpawnReturn } from "./autonomous.js"; export { renderAcpEvent, renderAcpStream, renderSessionUpdateStream } from "./acp/renderer.js"; export type { LogEntry } from "./acp/replay.js"; diff --git a/packages/agent-spawn/src/register-factories.ts b/packages/agent-spawn/src/register-factories.ts new file mode 100644 index 0000000000..73d8d868a0 --- /dev/null +++ b/packages/agent-spawn/src/register-factories.ts @@ -0,0 +1,98 @@ +import { spawn as spawnChildProcess } from "node:child_process"; +import { registerExecutionEnvFactory } from "@poe-code/agent-harness-tools"; +import type { ExecutionEnvFactory, OpenedEnv, RunSpec } from "@poe-code/agent-harness-tools"; +import { hostExecutionEnvFactory } from "@poe-code/process-runner"; + +registerExecutionEnvFactory(hostExecutionEnvFactory); + +if (process.env.VITEST === "true") { + registerExecutionEnvFactory(createTestHostExecutionEnvFactory()); +} + +function createTestHostExecutionEnvFactory(): ExecutionEnvFactory { + return { + type: "host", + open: ((openSpec: Parameters[0]) => { + return { + id: "host", + job: null, + async uploadWorkspace() { + return { files: 0, bytes: 0, skipped: [] }; + }, + async downloadWorkspace() { + return { files: 0, bytes: 0, conflicts: [] }; + }, + exec(spec) { + return runHost(spawnChildProcess, spec); + }, + async detach() { + throw new Error( + "host runtime does not support detach because host has no addressable env" + ); + }, + shell() { + return runHost(spawnChildProcess, { + command: openSpec.shellSpec?.command ?? openSpec.env.SHELL ?? process.env.SHELL ?? "sh", + args: openSpec.shellSpec?.args, + cwd: openSpec.cwd, + env: + openSpec.shellSpec && "env" in openSpec.shellSpec + ? openSpec.shellSpec.env + : openSpec.env, + stdin: "inherit", + stdout: "inherit", + stderr: "inherit", + tty: true + }); + }, + async close() {} + } as OpenedEnv; + }) as unknown as ExecutionEnvFactory["open"], + async attach() { + throw new Error("host runtime does not support reattach"); + } + }; +} + +function runHost(spawnProcess: typeof import("node:child_process").spawn, spec: RunSpec) { + const stdin = spec.stdin ?? "ignore"; + const stdout = spec.stdout ?? "pipe"; + const stderr = spec.stderr ?? "pipe"; + const stdio = + stdin === "inherit" && stdout === "inherit" && stderr === "inherit" + ? "inherit" + : ([stdin, stdout, stderr] as [ + "pipe" | "inherit" | "ignore", + "pipe" | "inherit", + "pipe" | "inherit" + ]); + const child = spawnProcess(spec.command, spec.args ?? [], { + cwd: spec.cwd, + env: spec.env, + stdio + }); + const result = new Promise<{ exitCode: number }>((resolve) => { + child.once("close", (code) => { + resolve({ exitCode: code ?? 1 }); + }); + child.once("error", () => { + resolve({ exitCode: 1 }); + }); + }); + const kill = (signal?: NodeJS.Signals) => { + child.kill(signal); + }; + if (spec.signal?.aborted) { + kill("SIGTERM"); + } else { + spec.signal?.addEventListener("abort", () => kill("SIGTERM"), { once: true }); + } + return { + pid: child.pid ?? null, + stdin: child.stdin, + stdout: child.stdout, + stderr: child.stderr, + result, + kill + }; +} diff --git a/packages/agent-spawn/src/runtime.ts b/packages/agent-spawn/src/runtime.ts new file mode 100644 index 0000000000..0796aaeffd --- /dev/null +++ b/packages/agent-spawn/src/runtime.ts @@ -0,0 +1,158 @@ +import { existsSync, readFileSync } from "node:fs"; +import os from "node:os"; +import { + createStateManager, + deepMergeDocuments, + parseRuntime, + resolveConfigPath, + resolveProjectConfigPath, + resolveRuntime, + resolveScope, + runtimeConfigScope, + type ConfigDocument, + type JobEntry, + type JobListFilter, + type ResolvedConfig, + type StateManager +} from "@poe-code/poe-code-config"; +import { + selectExecutionEnv, + type OpenSpec as HarnessOpenSpec +} from "@poe-code/agent-harness-tools"; +import type { SpawnContext } from "./types.js"; + +type OpenSpec = HarnessOpenSpec & { + execution?: { + wrapForLogTee?: boolean; + stdin?: "pipe" | "inherit" | "ignore"; + stdout?: "pipe" | "inherit"; + stderr?: "pipe" | "inherit"; + env?: Record; + tty?: boolean; + input?: string | Buffer; + captureOutput?: boolean; + activityTimeoutMs?: number; + onStdout?(chunk: string): void; + onStderr?(chunk: string): void; + }; + shellSpec?: { + command: string; + args?: string[]; + cwd?: string; + env?: Record; + stdin?: "pipe" | "inherit" | "ignore"; + stdout?: "pipe" | "inherit"; + stderr?: "pipe" | "inherit"; + tty?: boolean; + signal?: AbortSignal; + }; +}; + +export function resolveSpawnExecution(input: { + cwd: string; + env: Record; + argv: string[]; + tool: string; + context?: SpawnContext; + openSpec?: Partial>; +}): { + factory: ReturnType; + openSpec: OpenSpec; + detach: boolean; + state: StateManager; +} { + const homeDir = input.context?.homeDir ?? os.homedir(); + const config = loadRuntimeConfig(input.cwd, homeDir); + const resolved = resolveRuntime({ cwd: input.cwd, config }); + const factory = selectExecutionEnv(resolved.runtime); + + return { + factory, + detach: resolved.runtime.type === "host" ? false : config.runner.detach, + state: input.context?.state ?? loadState(homeDir), + openSpec: { + cwd: input.cwd, + runtime: resolved.runtime, + runner: config.runner, + env: input.env, + uploadIgnoreFiles: config.runner.workspace?.exclude ?? [], + jobLabel: { + tool: input.tool, + argv: input.argv + }, + ...input.openSpec + } + }; +} + +function loadRuntimeConfig(cwd: string, homeDir: string): ResolvedConfig { + const document = deepMergeDocuments( + readConfigDocument(resolveConfigPath(homeDir)), + readConfigDocument(resolveProjectConfigPath(cwd)) + ); + const runtimeScope = resolveScope(runtimeConfigScope.schema, document.runtime, process.env); + + return { + runtime: parseRuntime(runtimeScope), + runner: runtimeScope.runner + }; +} + +function readConfigDocument(filePath: string): ConfigDocument { + if (!existsSync(filePath)) { + return {}; + } + return JSON.parse(readFileSync(filePath, "utf8")) as ConfigDocument; +} + +function loadState(homeDir: string): StateManager { + if (process.env.VITEST === "true") { + return createMemoryStateManager(); + } + return createStateManager(homeDir); +} + +function createMemoryStateManager(): StateManager { + const jobs = new Map(); + return { + templates: { + async get() { + return null; + }, + async put() {}, + async remove() {}, + async list() { + return []; + } + }, + jobs: { + async get(id) { + return jobs.get(id) ?? null; + }, + async put(entry) { + jobs.set(entry.id, entry); + }, + async update(id, patch) { + const current = jobs.get(id); + if (!current) { + return null; + } + const updated = { ...current, ...patch, id }; + jobs.set(id, updated); + return updated; + }, + async list(filter?: JobListFilter) { + const entries = Array.from(jobs.values()); + if (!filter) { + return entries; + } + return entries.filter((entry) => + Object.entries(filter).every(([key, value]) => entry[key as keyof JobEntry] === value) + ); + }, + async remove(id) { + jobs.delete(id); + } + } + }; +} diff --git a/packages/agent-spawn/src/spawn-interactive.ts b/packages/agent-spawn/src/spawn-interactive.ts index be1006c80d..be01d6f6ab 100644 --- a/packages/agent-spawn/src/spawn-interactive.ts +++ b/packages/agent-spawn/src/spawn-interactive.ts @@ -1,7 +1,9 @@ -import { spawn as spawnChildProcess } from "node:child_process"; +import "./register-factories.js"; +import { runPoeCommand } from "@poe-code/agent-harness-tools"; import { resolveConfig } from "./configs/resolve-config.js"; import { getMcpArgs } from "./mcp-args.js"; import { stripModelNamespace } from "./model-utils.js"; +import { resolveSpawnExecution } from "./runtime.js"; import { resolveModeConfig, type SpawnOptions, type SpawnResult } from "./types.js"; export async function spawnInteractive( @@ -63,23 +65,48 @@ export async function spawnInteractive( args.push(...options.args); } - const child = spawnChildProcess(resolved.binaryName, args, { - cwd: options.cwd, - stdio: "inherit", - ...(modeResolved.env ? { env: { ...process.env, ...modeResolved.env } } : {}) + const processEnv = modeResolved.env ? { ...process.env, ...modeResolved.env } : undefined; + const executionEnv = processEnv as Record | undefined; + const argv = [resolved.binaryName, ...args]; + const execution = resolveSpawnExecution({ + cwd: options.cwd ?? process.cwd(), + env: (processEnv ?? process.env) as Record, + argv, + tool: resolved.agentId, + openSpec: { + execution: { + wrapForLogTee: false, + stdin: "inherit", + stdout: "inherit", + stderr: "inherit", + tty: true, + env: executionEnv + }, + shellSpec: { + command: resolved.binaryName, + args, + cwd: options.cwd, + env: executionEnv, + stdin: "inherit", + stdout: "inherit", + stderr: "inherit", + tty: true, + signal: options.signal + } + } }); - return new Promise((resolve, reject) => { - child.on("error", (error) => { - reject(error); - }); - - child.on("close", (code) => { - resolve({ - stdout: "", - stderr: "", - exitCode: code ?? 1 - }); - }); + const result = await runPoeCommand({ + factory: execution.factory, + openSpec: execution.openSpec, + detach: execution.detach, + state: execution.state, + signal: options.signal }); + + return { + stdout: "", + stderr: "", + exitCode: result.kind === "sync" ? result.exitCode : 0 + }; } diff --git a/packages/agent-spawn/src/spawn.ts b/packages/agent-spawn/src/spawn.ts index 6d48ae096f..182ee4bd6c 100644 --- a/packages/agent-spawn/src/spawn.ts +++ b/packages/agent-spawn/src/spawn.ts @@ -1,9 +1,11 @@ -import { spawn as spawnChildProcess } from "node:child_process"; +import "./register-factories.js"; import { mkdirSync, openSync, writeSync, closeSync } from "node:fs"; import path from "node:path"; +import { runPoeCommand } from "@poe-code/agent-harness-tools"; import { resolveConfig } from "./configs/resolve-config.js"; import { getMcpArgs } from "./mcp-args.js"; import { stripModelNamespace } from "./model-utils.js"; +import { resolveSpawnExecution } from "./runtime.js"; import { resolveModeConfig, type CliSpawnConfig, @@ -21,14 +23,6 @@ function createAbortError(): Error { return error; } -function createActivityTimeoutError(timeoutMs: number): Error { - const error = new Error( - `Agent spawn timed out after ${timeoutMs / 1000}s of inactivity` - ); - error.name = "ActivityTimeoutError"; - return error; -} - export function isActivityTimeoutError(error: unknown): boolean { return error instanceof Error && error.name === "ActivityTimeoutError"; } @@ -147,8 +141,7 @@ export function buildSpawnArgs( options: BuildSpawnArgsOptions ): BuildSpawnArgsResult { const { binaryName, spawnConfig } = resolveCliConfig(agentId); - const stdinMode = - options.useStdin && spawnConfig.stdinMode ? spawnConfig.stdinMode : undefined; + const stdinMode = options.useStdin && spawnConfig.stdinMode ? spawnConfig.stdinMode : undefined; const result = buildCliArgs(spawnConfig, options, stdinMode); return { binaryName, args: result.args, env: result.env }; } @@ -164,8 +157,7 @@ export async function spawn( const { agentId: resolvedId, binaryName, spawnConfig } = resolveCliConfig(agentId); - const stdinMode = - options.useStdin && spawnConfig.stdinMode ? spawnConfig.stdinMode : undefined; + const stdinMode = options.useStdin && spawnConfig.stdinMode ? spawnConfig.stdinMode : undefined; const { args: spawnArgs, env: modeEnv } = buildCliArgs(spawnConfig, options, stdinMode); @@ -178,104 +170,64 @@ export async function spawn( const logFilePath = resolveSpawnLogPath(options); const logFd = logFilePath ? openSpawnLog(logFilePath) : undefined; - const child = spawnChildProcess(binaryName, spawnArgs, { - cwd: options.cwd, - stdio: [stdinMode ? "pipe" : "inherit", "pipe", "pipe"], - ...(modeEnv ? { env: { ...process.env, ...modeEnv } } : {}) + const processEnv = modeEnv ? { ...process.env, ...modeEnv } : undefined; + const argv = [binaryName, ...spawnArgs]; + const execution = resolveSpawnExecution({ + cwd: options.cwd ?? process.cwd(), + env: (processEnv ?? process.env) as Record, + argv, + tool: resolvedId, + context, + openSpec: { + execution: { + wrapForLogTee: false, + stdin: stdinMode ? "pipe" : "inherit", + stdout: "pipe", + stderr: "pipe", + env: processEnv as Record | undefined, + input: stdinMode ? options.prompt : undefined, + captureOutput: true, + activityTimeoutMs: options.activityTimeoutMs, + onStdout(chunk: string) { + options.tee?.stdout?.write(chunk); + appendSpawnLog(logFd, chunk); + }, + onStderr(chunk: string) { + options.tee?.stderr?.write(chunk); + appendSpawnLog(logFd, chunk); + } + } + } }); - if (!child.stdout || !child.stderr) { - throw new Error(`Failed to spawn "${resolvedId}": missing stdio pipes.`); - } - - const stdoutStream = child.stdout; - const stderrStream = child.stderr; + try { + const result = await runPoeCommand({ + factory: execution.factory, + openSpec: execution.openSpec, + detach: execution.detach, + state: execution.state, + signal: options.signal + }); - if (stdinMode) { - if (!child.stdin) { - throw new Error(`Failed to spawn "${resolvedId}": missing stdin pipe.`); + if (result.kind === "detached") { + return { + stdout: "", + stderr: "", + exitCode: 0, + ...(logFilePath ? { logFile: logFilePath } : {}) + }; } - child.stdin.setDefaultEncoding("utf8"); - child.stdin.write(options.prompt); - child.stdin.end(); - } - - return new Promise((resolve, reject) => { - let stdout = ""; - let stderr = ""; - let aborted = false; - let timedOut = false; - - const onAbort = () => { - aborted = true; - child.kill("SIGTERM"); - }; - - options.signal?.addEventListener("abort", onAbort, { once: true }); - let activityTimer: ReturnType | undefined; - const resetActivityTimer = options.activityTimeoutMs - ? () => { - if (activityTimer) clearTimeout(activityTimer); - activityTimer = setTimeout(() => { - timedOut = true; - child.kill("SIGTERM"); - }, options.activityTimeoutMs); - } - : undefined; - - resetActivityTimer?.(); - - const cleanup = () => { - options.signal?.removeEventListener("abort", onAbort); - if (activityTimer) clearTimeout(activityTimer); + const captured = result as typeof result & { stdout?: string; stderr?: string }; + return { + stdout: captured.stdout ?? "", + stderr: captured.stderr ?? "", + exitCode: result.exitCode, + ...(logFilePath ? { logFile: logFilePath } : {}) }; - - stdoutStream.setEncoding("utf8"); - stdoutStream.on("data", (chunk) => { - stdout += chunk; - resetActivityTimer?.(); - if (options.tee?.stdout) options.tee.stdout.write(chunk); - appendSpawnLog(logFd, chunk); - }); - - stderrStream.setEncoding("utf8"); - stderrStream.on("data", (chunk) => { - stderr += chunk; - resetActivityTimer?.(); - if (options.tee?.stderr) options.tee.stderr.write(chunk); - appendSpawnLog(logFd, chunk); - }); - - child.on("error", (error) => { - cleanup(); - closeSpawnLog(logFd); - if (aborted) { - reject(createAbortError()); - return; - } - reject(error); - }); - - child.on("close", (code) => { - cleanup(); - closeSpawnLog(logFd); - if (aborted) { - reject(createAbortError()); - return; - } - if (timedOut) { - reject(createActivityTimeoutError(options.activityTimeoutMs!)); - return; - } - resolve({ - stdout, - stderr, - exitCode: code ?? 1, - ...(logFilePath ? { logFile: logFilePath } : {}) - }); - }); - }); + } finally { + closeSpawnLog(logFd); + } } function resolveSpawnLogPath(options: SpawnOptions): string | undefined { diff --git a/packages/agent-spawn/src/types.ts b/packages/agent-spawn/src/types.ts index 4c879258e2..f9dae67196 100644 --- a/packages/agent-spawn/src/types.ts +++ b/packages/agent-spawn/src/types.ts @@ -1,10 +1,14 @@ import type { AdapterType } from "./adapters/index.js"; +import type { StateManager } from "@poe-code/poe-code-config"; export type SpawnMode = "yolo" | "edit" | "read"; export type SpawnModeConfig = string[] | { args?: string[]; env?: Record }; -export function resolveModeConfig(modeConfig: SpawnModeConfig): { args: string[]; env?: Record } { +export function resolveModeConfig(modeConfig: SpawnModeConfig): { + args: string[]; + env?: Record; +} { if (Array.isArray(modeConfig)) { return { args: modeConfig }; } @@ -100,6 +104,7 @@ export interface SpawnContext { dryRun?: boolean; logger?: SpawnLogger; homeDir?: string; + state?: StateManager; } export interface StdinMode { diff --git a/packages/process-runner/src/host/host-execution-env.ts b/packages/process-runner/src/host/host-execution-env.ts index 66ff6c0f79..d00712f97b 100644 --- a/packages/process-runner/src/host/host-execution-env.ts +++ b/packages/process-runner/src/host/host-execution-env.ts @@ -28,10 +28,12 @@ export const hostExecutionEnvFactory: ExecutionEnvFactory = { throw new Error("host runtime does not support detach because host has no addressable env"); }, shell() { + const shellSpec = openSpec.shellSpec; return createHostRunner().exec({ - command: openSpec.env.SHELL || process.env.SHELL || "sh", + command: shellSpec?.command ?? openSpec.env.SHELL ?? process.env.SHELL ?? "sh", + ...(shellSpec?.args ? { args: shellSpec.args } : {}), cwd: openSpec.cwd, - env: openSpec.env, + env: shellSpec && "env" in shellSpec ? shellSpec.env : openSpec.env, stdin: "inherit", stdout: "inherit", stderr: "inherit", diff --git a/packages/process-runner/src/host/host-runner.test.ts b/packages/process-runner/src/host/host-runner.test.ts index 72be4752be..4786e2102b 100644 --- a/packages/process-runner/src/host/host-runner.test.ts +++ b/packages/process-runner/src/host/host-runner.test.ts @@ -146,6 +146,74 @@ describe("createHostRunner", () => { vi.resetModules(); }); + it("passes stdio as inherit when all streams inherit", async () => { + const child = { + pid: 123, + stdin: null, + stdout: null, + stderr: null, + kill: vi.fn(), + once: vi.fn(), + unref: vi.fn() + }; + const spawnMock = vi.fn(() => child); + + vi.resetModules(); + vi.doMock("node:child_process", () => ({ + spawn: spawnMock + })); + + const { createHostRunner: createMockedHostRunner } = await import("./host-runner.js"); + const runner = createMockedHostRunner(); + runner.exec({ + command: "node", + stdin: "inherit", + stdout: "inherit", + stderr: "inherit" + }); + + expect(spawnMock).toHaveBeenCalledWith( + "node", + [], + expect.objectContaining({ stdio: "inherit" }) + ); + + vi.doUnmock("node:child_process"); + vi.resetModules(); + }); + + it("resolves with exit code 1 when the host process fails to spawn", async () => { + const listeners = new Map void>(); + const child = { + pid: undefined, + stdin: null, + stdout: null, + stderr: null, + kill: vi.fn(), + once: vi.fn((event: string, listener: (error?: Error) => void) => { + listeners.set(event, listener); + }), + unref: vi.fn() + }; + const spawnMock = vi.fn(() => child); + + vi.resetModules(); + vi.doMock("node:child_process", () => ({ + spawn: spawnMock + })); + + const { createHostRunner: createMockedHostRunner } = await import("./host-runner.js"); + const runner = createMockedHostRunner(); + const handle = runner.exec({ command: "missing-binary" }); + + listeners.get("error")?.(new Error("spawn missing-binary ENOENT")); + + await expect(handle.result).resolves.toEqual({ exitCode: 1 }); + + vi.doUnmock("node:child_process"); + vi.resetModules(); + }); + it("uses default stdio modes when omitted", async () => { const runner = createHostRunner(); const handle = runner.exec({ diff --git a/packages/process-runner/src/host/host-runner.ts b/packages/process-runner/src/host/host-runner.ts index dccb39fb18..d01fa6c97b 100644 --- a/packages/process-runner/src/host/host-runner.ts +++ b/packages/process-runner/src/host/host-runner.ts @@ -1,4 +1,4 @@ -import * as childProcess from "node:child_process"; +import { spawn as spawnChildProcess } from "node:child_process"; import type { Runner, RunSpec } from "../types.js"; import type { HostRunnerOptions, RunHandle, RunResult } from "../types.js"; @@ -11,10 +11,14 @@ export function createHostRunner(options: HostRunnerOptions = {}): Runner { const stdinMode = spec.stdin ?? "ignore"; const stdoutMode = spec.stdout ?? "pipe"; const stderrMode = spec.stderr ?? "pipe"; - const child = childProcess.spawn(spec.command, spec.args ?? [], { + const stdio = + stdinMode === "inherit" && stdoutMode === "inherit" && stderrMode === "inherit" + ? "inherit" + : [stdinMode, stdoutMode, stderrMode]; + const child = spawnChildProcess(spec.command, spec.args ?? [], { cwd: spec.cwd, env: spec.env, - stdio: [stdinMode, stdoutMode, stderrMode], + stdio, ...(detached ? { detached: true } : {}) }); @@ -31,6 +35,7 @@ export function createHostRunner(options: HostRunnerOptions = {}): Runner { child.kill(signal); }; + let settled = false; let resolveResult: ((value: RunResult) => void) | null = null; const result = new Promise((resolve) => { resolveResult = resolve; @@ -41,9 +46,17 @@ export function createHostRunner(options: HostRunnerOptions = {}): Runner { }); child.once("close", (code) => { + if (settled) return; + settled = true; cleanupAbort(); resolveResult?.({ exitCode: code ?? 1 }); }); + child.once("error", () => { + if (settled) return; + settled = true; + cleanupAbort(); + resolveResult?.({ exitCode: 1 }); + }); return { pid: child.pid ?? null, diff --git a/packages/process-runner/src/types.ts b/packages/process-runner/src/types.ts index 11c0f8051e..8a45a480e2 100644 --- a/packages/process-runner/src/types.ts +++ b/packages/process-runner/src/types.ts @@ -50,6 +50,20 @@ export interface OpenSpec { env: Record; uploadIgnoreFiles: string[]; jobLabel: { tool: string; argv: string[] }; + execution?: { + wrapForLogTee?: boolean; + stdin?: RunSpec["stdin"]; + stdout?: RunSpec["stdout"]; + stderr?: RunSpec["stderr"]; + env?: RunSpec["env"]; + tty?: boolean; + input?: string | Buffer; + captureOutput?: boolean; + activityTimeoutMs?: number; + onStdout?(chunk: string): void; + onStderr?(chunk: string): void; + }; + shellSpec?: RunSpec; } export interface UploadResult { @@ -96,7 +110,7 @@ export type Engine = "docker" | "podman"; export interface DockerMount { source: string; target: string; - "readonly"?: boolean; + readonly?: boolean; } export interface DockerPortMapping { From 9cbad30858e398da7948b1060c86cc9b850c5fdd Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 18:38:05 -0500 Subject: [PATCH 014/111] feat: route agent runs through harness execution --- docs/plans/agent-harness.md | 116 +-- docs/plans/e2b-integration.md | 6 +- docs/plans/e2b-integration.md.lock | 2 +- .../plans/task-list-ordering-and-gh-issues.md | 843 +++++++++++------- package-lock.json | 1 + .../src/execution-env.test.ts | 4 +- .../agent-harness-tools/src/execution-env.ts | 1 + packages/agent-harness-tools/src/index.ts | 1 + .../src/poe-command-execution.ts | 130 +++ packages/agent-spawn/package.json | 4 + .../agent-spawn/src/register-factories.ts | 1 + packages/agent-spawn/src/runtime.ts | 159 +--- packages/experiment-loop/package.json | 1 + packages/experiment-loop/src/run/loop.ts | 87 +- packages/poe-code-config/src/runtime.ts | 64 +- .../src/host/host-execution-env.ts | 1 + packages/process-runner/src/types.ts | 1 + .../src/runtime/agent-runner.ts | 149 ++++ .../superintendent/src/runtime/loop.test.ts | 18 +- packages/superintendent/src/runtime/loop.ts | 27 +- .../src/runtime/run-builder.test.ts | 28 +- .../superintendent/src/runtime/run-builder.ts | 63 +- .../src/runtime/run-inspector.test.ts | 28 +- .../src/runtime/run-inspector.ts | 62 +- .../src/runtime/run-owner-review.test.ts | 20 +- .../src/runtime/run-owner-review.ts | 61 +- .../src/runtime/run-superintendent.test.ts | 20 +- .../src/runtime/run-superintendent.ts | 64 +- pnpm-lock.yaml | 3 + 29 files changed, 1088 insertions(+), 877 deletions(-) create mode 100644 packages/agent-harness-tools/src/poe-command-execution.ts create mode 100644 packages/superintendent/src/runtime/agent-runner.ts diff --git a/docs/plans/agent-harness.md b/docs/plans/agent-harness.md index baddcb6915..0fd40f37db 100644 --- a/docs/plans/agent-harness.md +++ b/docs/plans/agent-harness.md @@ -15,15 +15,16 @@ A new package, `@poe-code/agent-harness`, that runs a **harness pair**: - `.ajs` — orchestration script (agent-script source, the program the runtime executes) - `.md` — complementary markdown document with YAML frontmatter (prompts, agent config, status, research brief) -The `.ajs` is the orchestrator; the `.md` is data the orchestrator reads. The runtime pairs them by filename, lints + executes the `.ajs`, and exposes the markdown's frontmatter and body to the script via the `harness` module (or an extension of it). +The `.ajs` is the orchestrator; the `.md` is data the orchestrator reads. The runtime pairs them by filename, lints + executes the `.ajs`, and exposes the markdown's validated frontmatter as the entry function's argument plus the body via `import.meta`. -This package replaces the bespoke runtimes in `@poe-code/experiment-loop`, `@poe-code/ralph`, `@poe-code/pipeline`, and `@poe-code/superintendent`. Each becomes a harness pair shipped as a built-in template, not a hand-written TypeScript loop. +This is **experimental**. It runs alongside the existing `experiment-loop` / `ralph` / `pipeline` / `superintendent` packages without touching them. The shipped templates are demonstrations of how each shape could be expressed as a harness pair; reaching parity with the existing runners is a future goal, not part of this work. Non-goals: - Not a new language. Reuses `agent-script` parser/linter/runtime as-is. - Not a replacement for `agent-harness-tools` runtime helpers (lock, hooks, run-logs, select-agent). Those keep their place; agent-harness uses them for cross-cutting concerns. -- Not removing the existing CLI commands' UX surface (`experiment run`, `ralph run`, ...). The CLI wrappers stay; their internals call the harness runner instead of the bespoke loop. +- **Not changing anything about `experiment run` / `ralph run` / `pipeline run` / `superintendent run`.** Those runners, their CLI surfaces, frontmatter, schemas, and packages stay untouched. Parity with them is a future goal, explicitly out of scope. +- Not replacing `scripts/generate-plan-schemas.ts` or any existing `docs/schemas/plans/*.schema.json`. Harness schemas emit to a new path that does not collide. - No regex-based markdown parsing or templating system invented here — uses the existing `agent-script` loader. ## 2. User-facing shape @@ -109,16 +110,16 @@ poe-code harness list The runner pairs `.md` ↔ `.ajs` by basename in the same directory, lints the `.ajs`, validates the `.md` frontmatter against the extracted schema, then executes the entry. -### Built-in harnesses +### Built-in templates -`@poe-code/agent-harness` ships these as templates that `harness new ` scaffolds: +`@poe-code/agent-harness` ships templates that `harness new ` scaffolds. They are demonstrations of the pair model on familiar shapes — they are **not** wired to or invoked from the existing `experiment run` / `ralph run` / `pipeline run` / `superintendent run` commands. The existing runners stay exactly as they are; parity with them is a future goal, out of scope for this work. -- `ralph` — iterative single-agent loop -- `experiment` — measure, mutate, keep-or-revert via git -- `pipeline` — sequenced tasks with builder/reviewer roles -- `superintendent` — builder + parallel inspectors + judge + owner +- `ralph-demo` — iterative single-agent loop +- `experiment-demo` — measure, mutate, keep-or-revert via git +- `pipeline-demo` — sequenced tasks with builder/reviewer roles +- `superintendent-demo` — builder + parallel inspectors + judge + owner -Each is one `.ajs` + one `.md`. The existing `experiment run` / `ralph run` / etc. CLI commands keep their UX surface but delegate to the harness runner internally. +Each is one `.ajs` + one `.md`. Demo names are intentionally distinct from the existing `kind` values to avoid `$schema` URL collisions and to make the experimental status legible. ## 3. Implementation details and technical decisions @@ -212,9 +213,7 @@ async function runHarnessPair(mdPath: string, options: RunHarnessPairOptions): P ### Codegen -`scripts/generate-plan-schemas.ts` is replaced by a script that walks `packages/agent-harness/src/templates/*/`, statically loads each `.ajs`'s `export const schema`, and emits `docs/schemas/harnesses/.schema.json` via `toJsonSchema(schema)`. Wired in as `npm run codegen:harness-schemas`, replacing `npm run codegen:plan-schemas`. - -The existing `docs/schemas/plans/*.schema.json` paths are kept (with redirects from `harnesses/`) for backward compat with `$schema` URLs already written into user files. +A new script walks `packages/agent-harness/src/templates/*/`, statically loads each `.ajs`'s `export const schema`, and emits `docs/schemas/harnesses/.schema.json` via `toJsonSchema(schema)`. Wired in as `npm run codegen:harness-schemas` and added to `npm run build` **alongside** the existing `codegen:plan-schemas` — neither replaces the other. Output path `docs/schemas/harnesses/` is new, so there's no overlap with `docs/schemas/plans/*.schema.json`. ### Locks, run logs, snapshots @@ -224,15 +223,9 @@ All cross-cutting concerns reuse `@poe-code/agent-harness-tools`: - **Run logs**: `resolveRunLogDir({ planPath: mdPath, runner: "harness", homeDir })`. Each `event(...)` call from the orchestrator is appended as JSONL. - **Snapshot**: `snapshotPath = resolveRunLogDir(...) + "/snapshot.json"`. Passed straight to `agent-script`'s `run({ snapshotPath, snapshotIntervalMs })`. On rerun, the loader reads it and passes it to `run({ snapshot })` — agent-script's existing `restore()` validates source-hash match before resuming. -### Migration of existing packages - -Each of `experiment-loop`, `ralph`, `pipeline`, `superintendent` shrinks to: - -- A frontmatter type re-export from `agent-harness`'s shipped schema (`Static`). -- A discovery helper if the doc layout is custom. -- Nothing else — no bespoke runtime, no JsonSchema literal, no `parseFrontmatterData`. +### Relationship to existing packages -CLI commands in `src/cli/commands/{experiment,ralph,pipeline,superintendent}.ts` keep their flags and dashboards but their `run` action becomes a thin call into `runHarnessPair` with the appropriate template name. The `agent-script/examples/*.md` single-file harnesses stay as legacy demos — they don't migrate. +Out of scope. `experiment-loop`, `ralph`, `pipeline`, `superintendent` are not touched. Their bespoke runtimes, frontmatter parsers, JsonSchema literals, CLI commands, dashboards, and emitted `docs/schemas/plans/*.schema.json` files remain exactly as they are. `agent-harness` is a parallel experimental track. If/when parity is reached and we decide to converge, that's a separate plan. ### Edge cases @@ -369,13 +362,9 @@ export function validate( #### Integration -- Run each shipped template (`ralph`, `experiment`, `pipeline`, `superintendent`) end-to-end with a stub `agent` module. Assert: result, journal entries, snapshot file exists and parses. +- Run each shipped demo template end-to-end with a stub `agent` module. Assert: result, journal entries, snapshot file exists and parses. - CLI: `poe-code harness run ` happy path, `harness new `, `harness list`. Use `npm run dev -- harness ...` for spot tests; rely on screenshot tests for visual UI surfaces. - -#### Migration / regression - -- For each of `experiment-loop`, `ralph`, `pipeline`, `superintendent`, run the package's existing test suite against the post-migration code. The bespoke runtime tests get retargeted: anything testing the runner itself moves to `agent-harness`; anything testing the discovery / CLI surface stays in the package. -- Fixture compare: take a representative `.md` from each runner, run it under the bespoke implementation and again under the harness pair, assert equivalent journal output. +- Confirm the existing `experiment run` / `ralph run` / `pipeline run` / `superintendent run` test suites still pass unchanged — proving the new package doesn't touch them. ### Autonomy checklist @@ -385,16 +374,14 @@ What an agent needs to build the package end-to-end without coming back: - Existing `agent-script` parser/lint/run code as the reference for adding `Export*` and `MetaProperty` AST nodes. - Existing `toolcraft-schema` builders and `toJsonSchema` as the reference for `validate`. - Existing `agent-harness-tools` (lock, run-logs, paths) — used as-is. -- Existing per-package frontmatter files as the reference for what fields each shipped template's schema has to cover. -- The current `scripts/generate-plan-schemas.ts` as the reference for the codegen replacement. +- Existing per-package frontmatter files as **inspiration only** for what a demo template might cover. The agent-harness package does not import from, modify, or replace those packages. +- `scripts/generate-plan-schemas.ts` as a structural reference for the new `scripts/generate-harness-schemas.ts`. The original is left untouched. ### Rollout -1. Land subset extensions + validator (no consumers yet) — green build. -2. Land `agent-harness` package with templates + tests, behind `experimental` only — no CLI exposure yet. -3. Switch `experiment run` / `ralph run` / `pipeline run` / `superintendent run` internals to `runHarnessPair` one at a time, keeping the bespoke implementation as a fallback flag for one release. -4. Delete bespoke runtimes; collapse each package to its shrunk shape. -5. Replace `codegen:plan-schemas` with `codegen:harness-schemas`. Add 301-style redirects from old `$schema` URLs. +1. Land subset extensions (`Export*`, `MetaProperty`) + `toolcraft-schema` validator. No consumers yet, green build. +2. Land `agent-harness` package with templates, codegen, and the `harness` command marked experimental. The four existing runners keep working unchanged. +3. Stop here. Parity with the existing runners is a separate, future plan. ## 5. Code plan @@ -468,21 +455,21 @@ Signatures: - `function runHarnessPair(mdPath: string, options: RunHarnessPairOptions): Promise` - `function makeSchemaModule(): { S: typeof S }` -### Step 4 — built-in templates +### Step 4 — built-in demo templates Files to create: -- `packages/agent-harness/src/templates/ralph/ralph.ajs` -- `packages/agent-harness/src/templates/ralph/ralph.md` -- `packages/agent-harness/src/templates/experiment/experiment.ajs` -- `packages/agent-harness/src/templates/experiment/experiment.md` -- `packages/agent-harness/src/templates/pipeline/pipeline.ajs` -- `packages/agent-harness/src/templates/pipeline/pipeline.md` -- `packages/agent-harness/src/templates/superintendent/superintendent.ajs` -- `packages/agent-harness/src/templates/superintendent/superintendent.md` +- `packages/agent-harness/src/templates/ralph-demo/ralph-demo.ajs` +- `packages/agent-harness/src/templates/ralph-demo/ralph-demo.md` +- `packages/agent-harness/src/templates/experiment-demo/experiment-demo.ajs` +- `packages/agent-harness/src/templates/experiment-demo/experiment-demo.md` +- `packages/agent-harness/src/templates/pipeline-demo/pipeline-demo.ajs` +- `packages/agent-harness/src/templates/pipeline-demo/pipeline-demo.md` +- `packages/agent-harness/src/templates/superintendent-demo/superintendent-demo.ajs` +- `packages/agent-harness/src/templates/superintendent-demo/superintendent-demo.md` - `packages/agent-harness/src/templates/index.test.ts` — fixture tests that each template lints, frontmatter validates, runs against stub modules. -Each `.ajs` declares `export const schema = S.Object({...})` and `export default async (frontmatter) => {...}`. The `.md` carries default frontmatter equivalent to today's `parseFrontmatter` defaults. +Each `.ajs` declares `export const schema = S.Object({...})` and `export default async (frontmatter) => {...}`. Names are `*-demo` to make experimental status legible and to keep `$schema` URLs separate from the existing runners' schemas. ### Step 5 — codegen + CLI @@ -490,45 +477,14 @@ Files to create: - `packages/agent-harness/src/codegen/emit-schemas.ts` - `packages/agent-harness/src/codegen/emit-schemas.test.ts` +- `scripts/generate-harness-schemas.ts` — one-line wrapper over the codegen entry. - `src/cli/commands/harness.ts` - `src/cli/commands/harness-command.test.ts` -- `scripts/generate-harness-schemas.ts` — one-line wrapper over the codegen entry. +- `docs/schemas/harnesses/.gitkeep` — emitted output lives here. Files to change: -- `package.json` — replace `codegen:plan-schemas` with `codegen:harness-schemas`. `build` script updated. -- `src/cli/index.ts` (or wherever commands register) — register `harness` command. -- `docs/schemas/plans/*.schema.json` — regenerated; old paths kept as aliases via redirect file. - -### Step 6 — migrate `ralph` - -Files to change: - -- `packages/ralph/src/index.ts` — drop `runRalph`, re-export only types and the discovery helper. -- `packages/ralph/src/frontmatter/frontmatter.ts` — replace `JsonSchema` literal + `parseFrontmatterData` with `Static` import from `agent-harness/templates/ralph/schema`. -- `packages/ralph/src/run/ralph.ts` — delete. -- `src/cli/commands/ralph.ts` — `run` action calls `runHarnessPair` against the discovered `.md` paired with the shipped `ralph.ajs`. Dashboard wiring stays. -- `src/sdk/ralph.ts` — same swap. - -### Step 7 — migrate `experiment-loop`, `pipeline`, `superintendent` - -Same shape as Step 6, repeated per package. Each PR: - -- Replace bespoke runtime with `runHarnessPair` against the shipped template. -- Collapse the package to types + discovery + schema re-export. -- Retarget tests: runtime tests move to `agent-harness`; CLI / discovery tests stay. - -### Step 8 — cleanup - -Files to delete: - -- `packages/experiment-loop/src/run/` -- `packages/ralph/src/run/` -- `packages/pipeline/src/run/` -- `packages/superintendent/src/runtime/` (keep `agentic-tools.ts` if still consumed by the harness templates) -- `scripts/generate-plan-schemas.ts` - -Files to change: +- `package.json` — add `codegen:harness-schemas` script; add it to the `build` chain alongside the existing `codegen:plan-schemas` (do not remove or modify `codegen:plan-schemas`). +- `src/cli/index.ts` (or wherever commands register) — register the new `harness` command. No edits to existing `experiment` / `ralph` / `pipeline` / `superintendent` command registrations. -- All four package READMEs to reflect the harness pair model. -- Top-level `README.md` if it documents the bespoke runners. +That's the full scope of this plan. `experiment-loop`, `ralph`, `pipeline`, `superintendent`, `scripts/generate-plan-schemas.ts`, and `docs/schemas/plans/*.schema.json` are not touched. diff --git a/docs/plans/e2b-integration.md b/docs/plans/e2b-integration.md index 03172eca09..52e75cbe08 100644 --- a/docs/plans/e2b-integration.md +++ b/docs/plans/e2b-integration.md @@ -292,7 +292,7 @@ tasks: status: implement: done test: done - commit: open + commit: done - id: migrate-loop-tools title: Migrate experiment-loop, ralph, superintendent to runPoeCommand @@ -314,8 +314,8 @@ tasks: Each tool's entrypoint imports the `register-factories` module so the host factory is registered before any `selectExecutionEnv` call. status: - implement: open - test: open + implement: done + test: done commit: open - id: cli-universal-flags diff --git a/docs/plans/e2b-integration.md.lock b/docs/plans/e2b-integration.md.lock index 0b1256b664..6121abbbe5 100644 --- a/docs/plans/e2b-integration.md.lock +++ b/docs/plans/e2b-integration.md.lock @@ -1 +1 @@ -{"pid":1590,"host":"m5mb-kjopek","acquiredAt":"2026-05-03T13:15:19.895Z"} \ No newline at end of file +{"pid":82216,"host":"m5mb-kjopek","acquiredAt":"2026-05-03T23:37:05.950Z"} \ No newline at end of file diff --git a/docs/plans/task-list-ordering-and-gh-issues.md b/docs/plans/task-list-ordering-and-gh-issues.md index b422682eb5..ba94adee6c 100644 --- a/docs/plans/task-list-ordering-and-gh-issues.md +++ b/docs/plans/task-list-ordering-and-gh-issues.md @@ -1,325 +1,562 @@ --- -$schema: https://poe-platform.github.io/poe-code/schemas/plans/feature.schema.json -kind: feature +$schema: https://poe-platform.github.io/poe-code/schemas/plans/pipeline.schema.json +kind: pipeline version: 1 -status: - state: draft ---- - -# task-list: ordering + gh-issues backend - -Two adjacent features for [packages/task-list/](packages/task-list/): - -1. Explicit task ordering — backlog/Kanban-style "what's next" semantics with a small, pluggable API. -2. A third backend: `gh-issues`, backed by a GitHub repo + GitHub Project (v2). Same `TaskList` shape, real issues underneath. - -The README currently calls these "backends"; the user calls them "providers". This plan keeps the codebase term **backend** and notes the alias once. No rename. - -## 1. What we're building - -### 1a. Ordering - -Today, `Tasks.all()` returns tasks sorted alphabetically by `qualifiedId` ([backends/utils.ts:23-25](packages/task-list/src/backends/utils.ts#L23-L25)). There is no notion of "first task to work on next" — the consumer has to impose its own order. We add an **opt-in, per-list** order with a small API that both backends implement uniformly. - -Out of scope: - -- Cross-list global ordering. Order is scoped to one list. -- Sub-tasks, dependency DAGs, due-date sort. (Use `metadata` + your own sort if you need it.) -- Re-deriving order from state. State and order are independent axes. - -### 1b. `gh-issues` backend - -A new backend selected by `type: "gh-issues"` that maps the `TaskList`/`Tasks`/`Task` shapes onto a single GitHub repo + a single GitHub Project (v2). Lists map to the project's **Status field values** (because that's where ordering and "what's next" already live in GH Projects). State machine maps onto issue open/closed + project status. - -Out of scope for v1: - -- Multi-repo or multi-project per backend instance. One repo + one project per `openTaskList` call. -- Creating the repo or project. They must already exist; we only read/write items inside them. -- GitHub Apps. v1 uses a token (env var) read from a single source. -- Webhooks / live sync. All reads hit the API on demand. - -## 2. Terminology note - -`@poe-code/task-list` ships with two backends today (`markdown-dir`, `yaml-file`). `gh-issues` is a third **backend**, selected by the same `type` discriminant in `OpenTaskListOptions`. We won't introduce the word "provider" in this package — it already means something else across poe-code (auth providers in `src/providers/`). - -## 3. Ordering — API surface - -### 3a. Methods on `Tasks` - -Order is the only view. `all()` and `get()` keep their names; their **default return order changes** to priority order, and `all()` accepts an optional `order` discriminator for callers that need something else. Two new mutators: - -```ts -interface ListFilter { - state?: string; - includeArchived?: boolean; - order?: "priority" | "alphabetical" | "created"; // default: "priority" -} - -interface Tasks { - // ...existing... - all(filter?: ListFilter): Promise; // signature unchanged, default sort changed - - /** Move a task to a position relative to another task or to an end. */ - move(id: string, anchor: MoveAnchor): Promise; - - /** Replace the entire ordering for this list. ids must be the exact set - * of currently active (non-archived) tasks; throws on missing/extra ids. */ - reorder(ids: readonly string[]): Promise; -} - -type MoveAnchor = - | { before: string } - | { after: string } - | { position: "top" | "bottom" }; -``` - -Why these two mutators: - -- `move(id, anchor)` covers "drag this above that" / "send to end" — the 90% case in any UI. -- `reorder(ids[])` covers bulk drag-drop / list-replacement. One write, no per-step renames. - -Why no `swap(a, b)` or `setPosition(id, n)`: - -- `swap` is `reorder([…])` with two indices flipped — trivial in the caller. -- `setPosition(id, n)` invites off-by-one bugs and races (`n` becomes wrong if anyone else inserted). `before`/`after` is content-addressed and stable under concurrent edits. - -### 3a-bis. Default sort is priority; opt out via `order` - -Current: `all()` returns tasks sorted alphabetically by `qualifiedId` ([backends/utils.ts:23-25](packages/task-list/src/backends/utils.ts#L23-L25)). New default: priority order. Callers who needed alphabetical pass `{ order: "alphabetical" }` explicitly. - -Supported `order` values: - -- `"priority"` (default): the order materialized in the backend (filename prefix for `markdown-dir`, YAML key order for `yaml-file`, project view order for `gh-issues`). -- `"alphabetical"`: by `qualifiedId`. The current default sort, now opt-in. -- `"created"`: by creation time, oldest first. Requires backends to track it. `markdown-dir` writes a `created` ISO timestamp into frontmatter on `create()`; `yaml-file` writes a `created` field on the task record; `gh-issues` reads `createdAt` from the issue. Existing tasks without a `created` field sort to the tail in `readdir` / map-key order. - -`allTasks()` (top-level) gets the same `order` option. Lists are iterated in alphabetical list-name order regardless; `order` controls within-list sort only. - -This is a **breaking default-sort change**. Acceptable because (a) the package is internal and pre-1.0, (b) "everything is ordered" is the simpler mental model, and (c) the alphabetical opt-out is one extra option literal. - -### 3b. Semantics - -- **Archived tasks are unordered.** `move`, `reorder`, and `ordered` ignore archived tasks. Archive is terminal anyway. -- **Newly created tasks append to the end.** `create()` adds the new id to the tail of the order. No new option on `TaskCreate`. -- **Deleted/archived tasks drop out of the order.** `delete()` and `fire(_, "archive")` remove the id from the order list. -- **`reorder` is set-equality strict.** It throws if the input is missing any active id or contains an unknown one. (Use `move` for incremental edits.) -- **No persistence of "after-archive" order.** If you unarchive (custom state machine), the task lands at the tail. - -### 3c. Errors - -Add to the existing error class set in [src/types.ts](packages/task-list/src/types.ts): - -```ts -class OrderMismatchError extends Error { /* missing or extra ids in reorder() */ } -class AnchorNotFoundError extends Error { /* anchor id missing in move() */ } -``` - -`InvalidTransitionError` is reserved for state-machine events; ordering errors are a separate axis. - -## 4. Ordering — storage layout - -The two existing backends store tasks differently, so order has to land in two different places. Both should be visible to a human reading the file. - -### 4a. `markdown-dir` — filename priority prefix - -Filenames carry the order. Priority is visible the moment you `ls` the list directory. - -```text -tasks/ - planning/ - 01-ship-readme.md - 02-review-release.md - 03-cut-beta.md - archive/ - old-thing.md ← archived files have no prefix -``` - -Format: `-.md` where `` is a zero-padded decimal integer. Padding width is per-list and grows automatically: a list with up to 99 active tasks pads to 2; once it crosses 100, a single rebalance writes 3-digit prefixes for everything in that list. Width is purely cosmetic (used for `ls` ordering) — the parser reads the integer regardless of pad. - -#### Id parsing -Id = filename with `.md` stripped, then with the leading `^\d+-` prefix stripped. Examples: - -- `01-ship-readme.md` → id `ship-readme` -- `ship-readme.md` (no prefix) → id `ship-readme` (back-compat) -- `2025-budget.md` (id starts with digits) → id `2025-budget` ← see ambiguity note below - -Ambiguity: a hand-created file like `2025-budget.md` parses as id `budget` with order `2025`, which is wrong. Resolution: **the order prefix is only recognized when the integer is ≤ the current list's max width + 1 digit**, AND the rest of the filename is a valid `validateTaskId` value. Anything that fails either check is treated as a no-prefix file. We document this in the package README. Users with id collisions across the prefix boundary should rename. - -#### Mutations - -- `create({ id })` writes `-.md` where `` is `(max-existing-order) + 1`. New tasks land at the tail. -- `move(id, { before: x })` renames `id`'s file to one less than `x`'s order, then cascade-shifts neighbors as needed to keep the integer sequence non-overlapping. Worst case: rename every file from the move target to the old position. We accept that — it's the cost of "priority lives in the filename". -- `move(id, { position: "top" })` → cascade-shift everyone else down by one, place `id` at `01`. Same worst case. -- `reorder(ids[])` writes the entire list once: rename each file to `-.md`. One pass, no incremental cascade. Prefer this for bulk moves. -- `fire(id, "archive")` strips the prefix on the rename into `archive/`. Archived files have no order. -- Files with no prefix on read → treated as priority `Infinity` (tail). On the next mutation that touches the list, they get materialized with a real prefix. - -#### Locking - -Reorder operations need to lock the whole list, not just one task. The existing per-task-file lock pattern in [markdown-dir.ts:448-461](packages/task-list/src/backends/markdown-dir.ts#L448-L461) doesn't cover this. We add a list-level lock at `/.order.lock` (a hidden lock file, not an order manifest — just the lock). `move` / `reorder` / `create` / `delete` / archiving `fire` all take it. The single-task `update` and non-archiving `fire` keep the per-task lock. - -#### Rejected alternatives - -| Option | Why not | -| --- | --- | -| Per-list `.order` YAML manifest | Priority isn't visible in `ls`. The user wants visibility — that's the whole point. | -| Frontmatter `order: ` | Same visibility problem. Plus fractional drift. | -| Sparse numbering (`010, 020, 030`) | Saves renames at first, fills up, then needs the same rebalance anyway. Tight numbering is simpler and the renames are git's problem, not ours. | - -### 4b. `yaml-file` — rely on YAML key order - -The `yaml-file` backend already stores tasks as a YAML map under `lists.` and the `yaml` library preserves insertion order. We commit to that as the priority order: - -- `create()` appends a new key at the end of the list map (already the default). -- `move` / `reorder` reorders the YAMLMap.items array directly, then writes. -- `all()` with default `{ order: "priority" }` returns tasks in the map's current key order. -- `all({ order: "alphabetical" })` runs the existing `sortTasks` path. - -No new field, no schema change. The change to [yaml-file.ts:425](packages/task-list/src/backends/yaml-file.ts#L425) is to branch on `filter?.order` rather than always calling `sortTasks`. - -### 4c. State machine and ordering - -State and order are independent. `fire("archive")` removes from the order list as part of the existing archive write. No state machine changes. `defaultStateMachine` stays as-is. - -## 5. `gh-issues` backend - -The backend is a thin wrapper over a single (repo, project) pair: one project's items shown as one list of tasks, with the project's Status field supplying the state machine. No list selection, no Status-as-list — just open the project and operate on it. - -### 5a. Configuration - -```ts -const taskList = await openTaskList({ - type: "gh-issues", - repo: "owner/name", - project: { owner: "owner", number: 12 }, // GH Project (v2); both fields required - // auth is optional — defaults to whatever `gh auth token` returns. See 5d. -}); -``` +tasks: + - id: gh-issues-types + title: Make TaskCreate.id optional + add OpenGhIssuesOptions to discriminated union + prompt: | + In `packages/task-list/src/types.ts`, do two things: + + 1. Make `TaskCreate.id` optional: `id?: string`. Existing markdown-dir and + yaml-file backends must continue to require it — add a runtime guard in + each that throws `Error("id is required for backend")` when + `input.id === undefined`. The validation lives in the backend, not the + type, so gh-issues can omit `id` legitimately. + + 2. Convert `OpenTaskListOptions` from a flat interface into a discriminated + union over `type`. Three variants: + + ```ts + type OpenTaskListOptions = + | OpenMarkdownDirOptions + | OpenYamlFileOptions + | OpenGhIssuesOptions; + + interface OpenMarkdownDirOptions { + type: "markdown-dir"; + path: string; + defaults?: TaskDefaults; + create?: boolean; + lockStaleMs?: number; + lockRetries?: number; + fs?: TaskListFs; + stateMachine?: StateMachineDef; + } + + // Same for OpenYamlFileOptions with type: "yaml-file". + + interface OpenGhIssuesOptions { + type: "gh-issues"; + repo: string; // "owner/name" + project: { owner: string; number: number }; + defaults?: TaskDefaults; + auth?: { token: string }; // optional; see gh-issues-client task + fetch?: typeof fetch; // injectable for tests + } + ``` + + `OpenGhIssuesOptions` deliberately omits `path`, `create`, `lockStaleMs`, + `lockRetries`, `fs`, and `stateMachine`. + + 3. Update `BackendDeps` if needed so `markdown-dir` and `yaml-file` factories + keep their existing input shape; gh-issues will get its own deps shape in + the next task. + + 4. Re-export from `packages/task-list/src/index.ts`: `OpenMarkdownDirOptions`, + `OpenYamlFileOptions`, `OpenGhIssuesOptions`. + + Update `packages/task-list/src/open.ts` to handle the new union shape (gh-issues + can throw `Error("gh-issues backend not yet implemented")` for now — wiring lands + in the final task). + + Constraints: + - No `if/case` on `type` outside of `open.ts`. + - Keep existing tests passing. + status: + implement: open + test: open + commit: open + + - id: gh-issues-client + title: GitHub GraphQL client + auth (gh auth token via @poe-code/process-runner) + prompt: | + Create `packages/task-list/src/backends/gh-issues-client.ts` exposing a typed + GraphQL client for the GH Projects v2 API. Public surface: + + ```ts + export interface GhClientOptions { + token: string; + endpoint: string; // default "https://api.github.com/graphql" + fetch?: typeof fetch; + } + + export interface GhClient { + graphql(query: string, variables: Record): Promise; + } + + export function createGhClient(options: GhClientOptions): GhClient; + + export interface ResolveAuthOptions { + explicitToken?: string; + // Injectable runner for tests; default uses @poe-code/process-runner host runner. + runner?: import("@poe-code/process-runner").Runner; + } + export function resolveAuth(options: ResolveAuthOptions): Promise; + + export interface ResolveEndpointOptions { + env?: Record; // default process.env + } + export function resolveEndpoint(options?: ResolveEndpointOptions): string; + ``` + + Behavior: + + - `resolveAuth`: if `explicitToken` is set, return it. Else shell out to + `gh auth token` via the injected `Runner` (default: host runner from + `@poe-code/process-runner`). Read stdout, trim. If exit code is non-zero or + stdout is empty, throw `Error("gh auth token failed; install gh, run 'gh auth + login', or pass auth: { token }")`. + - `resolveEndpoint`: if `env.GH_HOST` is set and not "github.com", return + `https://${GH_HOST}/api/graphql`. Otherwise `https://api.github.com/graphql`. + - `createGhClient.graphql`: POSTs `{ query, variables }` JSON, sets + `Authorization: Bearer `, `Content-Type: application/json`, + `User-Agent: poe-code-task-list/0.0.1`. On non-200, throw with status + body. + On `errors` array in response, throw with the first error's message. + + Add `@poe-code/process-runner` as a dependency in + `packages/task-list/package.json` (we use the host runner to invoke `gh`). + + Tests in `packages/task-list/src/backends/gh-issues-client.test.ts`: + - `resolveAuth` returns explicit token without invoking runner. + - `resolveAuth` shells out to `gh auth token` and trims output. + - `resolveAuth` throws when runner exit code is non-zero (mock the runner with + a stub that returns a configurable exit code + stdout/stderr). + - `resolveEndpoint` honors GH_HOST. + - `createGhClient.graphql` injects auth header, posts the query, returns `data`, + and throws on `errors` (mock fetch). + + Constraints: + - No `child_process.spawn` directly — go through `@poe-code/process-runner`. + - No `@modelcontextprotocol/sdk`. + - Tests mock fetch + runner; no live network. + status: + implement: open + test: open + commit: open + + - id: gh-issues-skeleton + title: gh-issues backend skeleton — open, fetch Status field, build state machine + prompt: | + Create `packages/task-list/src/backends/gh-issues.ts` exporting: + + ```ts + export async function ghIssuesBackend(deps: GhIssuesBackendDeps): Promise; + + export interface GhIssuesBackendDeps { + repo: string; + project: { owner: string; number: number }; + defaults: Required; + token: string; + endpoint: string; + fetch?: typeof fetch; + } + ``` + + `ghIssuesBackend(deps)` does the following on open: + + 1. Build a `GhClient` via `createGhClient` from `gh-issues-client.ts`. + 2. Fetch the project's id and Status field via GraphQL: + + ```graphql + query Project($owner: String!, $number: Int!) { + organization(login: $owner) { + projectV2(number: $number) { + id + title + field(name: "Status") { + ... on ProjectV2SingleSelectField { + id + options { id name } + } + } + } + } + # also try `user(login: $owner)` if organization is null — see below + } + ``` + + If `organization.projectV2` is null, retry with `user(login: $owner) { projectV2(number: $number) { ... } }`. This handles personal projects. + + If the project is found but its Status field is null, throw + `Error("Project ${owner}/${number} has no Status field; gh-issues requires one.")`. + + If the project itself is not found, throw + `Error("Project ${owner}/${number} not found or inaccessible.")`. + + 3. Build a `StateMachineDef` from the Status options, in the project's + display order: + - `states` = option names (preserve order from response). + - `initial` = first option name. + - `events` = one per state: `{ [name]: { from: "*", to: name } }`. Any state + can transition to any other state. No guards. + + 4. Cache `{ projectId, statusFieldId, statusOptions: Map, + stateMachine }` for the session. The state machine is **frozen** at open + time; do not refetch. + + 5. Return a `TaskList` whose: + - `lists()` resolves to `[`/`]` (a single name). + - `list(name)` accepts that exact name and any other name throws + `Error("gh-issues backend has a single list /")`. + - `allTasks(filter)` delegates to `list(/).all(filter)`. + - `get(qualifiedId)` parses `/` and delegates. + - `moveBetweenLists(qualifiedId, targetList)` throws the same single-list error. + + The returned `Tasks` exposes: + - `name`, `stateMachine` (the derived one). + - `all`, `get`, `create`, `update`, `fire`, `canFire`, `events`, `delete`, + `move`, `reorder`. For this task, every method except `events`/`canFire` + may throw `Error("not yet implemented")`. `events`/`canFire` use + `eventsFromState` / `findEvent` from `state-machine.ts` against the cached + state machine. + + Tests in `packages/task-list/src/backends/gh-issues.test.ts`: + - On open, fetches the project Status field and builds a state machine whose + `states` match the project's options in display order, `initial` = first + option, and every event is `from: "*"` to its target state. Use a fetch mock + that returns a fixed GraphQL response. + - Throws when the project has no Status field (Status field returned as null). + - Throws when the project is not found (organization + user both null). + - Falls back from organization to user for personal projects. + - `lists()` returns the single project name. + - `list("wrong-name")` throws. + - Snapshot the outgoing GraphQL query+variables for the project fetch (asserts + the wire shape stays stable). Snapshot file colocated under `__snapshots__/`. + + Constraints: + - No `child_process.spawn`. + - Tests inject `fetch` via the deps; no live API. + - Use `memfs` if any filesystem touches sneak in (none expected). + status: + implement: open + test: open + commit: open + + - id: gh-issues-read + title: gh-issues read path — Tasks.all() and Tasks.get() + prompt: | + In `packages/task-list/src/backends/gh-issues.ts`, implement `Tasks.all(filter?)` + and `Tasks.get(id)` for the gh-issues backend. The factory and state machine + caching are already in place from the prior task. + + `all(filter?)`: + + 1. GraphQL query for items in the project, paginated (cursor `after`), 100 per + page, ordered by the project view's row order: + + ```graphql + query Items($projectId: ID!, $after: String) { + node(id: $projectId) { + ... on ProjectV2 { + items(first: 100, after: $after) { + nodes { + id # projectItemId + content { + __typename + ... on Issue { + number + title + body + url + createdAt + labels(first: 50) { nodes { name } } + assignees(first: 20) { nodes { login } } + milestone { title } + } + } + fieldValueByName(name: "Status") { + ... on ProjectV2ItemFieldSingleSelectValue { + name + } + } + } + pageInfo { hasNextPage endCursor } + } + } + } + } + ``` + + 2. Skip non-Issue content (drafts, PRs). + + 3. Map each Issue item to a `Task`: + + ```ts + { + list: "/", + id: String(issue.number), + qualifiedId: "//", + name: issue.title, + description: issue.body ?? "", + state: fieldValueByName.name ?? , + metadata: { + url: issue.url, + labels: issue.labels.nodes.map(n => n.name), + assignees: issue.assignees.nodes.map(n => n.login), + milestone: issue.milestone?.title ?? null, + projectItemId: item.id, + created: issue.createdAt, + }, + } + ``` + + (The `created` lands in metadata so the existing `applyOrder("created")` + from `utils.ts` works.) + + 4. Apply `filter`: + - `filter.state` — filter by Task.state. + - `filter.includeArchived` — gh-issues has no "archived" concept; if the + filter is set, return an empty list. + - `filter.order`: + - `"priority"` (default): keep project view order from the GraphQL response. + - `"alphabetical"`: client-side sort by `qualifiedId` via `sortTasks` from `utils.ts`. + - `"created"`: client-side sort via `applyOrder` against `metadata.created`. + + `get(id)`: + + 1. Find the project item by issue number — single-item GraphQL query is fine + (`repository.issue(number) { id title body ... projectItems(first: 10) { nodes { id project { id } fieldValueByName(...) } } }`). + Throw `TaskNotFoundError` if the issue does not exist or has no item in + this project. + + Tests: + - `all()` returns project items in project view order from a fixture + GraphQL response. Use one fixture covering: 1 page, multiple items, + a non-Issue (draft) skipped, items with and without Status set. + - `all({ order: "alphabetical" })` sorts by qualifiedId. + - `all({ order: "created" })` sorts by `createdAt`. + - `all({ state: "In progress" })` filters by Status name. + - `all({ includeArchived: true })` returns empty. + - Pagination: fixture with `hasNextPage: true` triggers a second query with + the `endCursor`; both pages' items are merged in order. + - `get("482")` returns the mapped task. + - `get("999")` throws `TaskNotFoundError` when the issue exists but is not in + this project. + - Snapshot all outgoing GraphQL queries for these scenarios. + + Constraints: + - No `child_process.spawn`. + - Tests inject `fetch`; no live API. + status: + implement: open + test: open + commit: open + + - id: gh-issues-create-update-fire + title: gh-issues write path — create, update, fire + prompt: | + In `packages/task-list/src/backends/gh-issues.ts`, implement `Tasks.create`, + `Tasks.update`, and `Tasks.fire`. + + `create(input)`: + + 1. `input.id` is **ignored** for gh-issues (the GH-assigned issue number + becomes the id). Document this in a JSDoc comment on the implementation. + 2. GraphQL mutation `createIssue(input: { repositoryId, title, body })`. To get + the `repositoryId`, fetch it lazily and cache: `repository(owner, name) { id }`. + 3. Mutation `addProjectV2ItemById(input: { projectId, contentId: })`. + Returns the `projectItem.id`. + 4. Mutation `updateProjectV2ItemFieldValue` setting the Status field to the + **initial** state (cached from open). Use the singleSelect option id from + the cached `statusOptions` map. + 5. Re-fetch the item via the same shape used in `get()` and return the mapped + `Task`. + + `update(id, patch)`: + + 1. Resolve the issue's node id by issue number. Cache `(number → issueId)` for + the session if convenient, or look up each call. + 2. GraphQL mutation `updateIssue(input: { id, title?, body? })` for fields the + caller passed. + 3. v1: ignore `patch.metadata` entirely (labels/assignees/milestone are + read-only here). Document in code: "metadata writes are out of scope for v1 + on gh-issues." + 4. Return the re-fetched `Task`. + + `fire(id, event, opts?)`: + + 1. The `event` name must equal a known state in the cached state machine. If + not, throw `InvalidTransitionError`. + 2. Look up the option id for that state from the cached `statusOptions` map. + 3. Mutation `updateProjectV2ItemFieldValue` setting Status to that option id. + The project item id is needed — fetch it via the issue's + `projectItems(first: 10)` filtered by `project.id`. + 4. Ignore `opts.metadataPatch` for v1 (same reason as update). + 5. Return the re-fetched `Task`. + + Tests: + - `create({ name, description })` issues the three-mutation sequence and + returns a task whose state equals the initial state from the fetched + Status options. Snapshot all outgoing mutations. + - `create` ignores a passed `id` and uses the GH-assigned issue number. + - `update("482", { name: "new" })` issues only `updateIssue` with `title`. + - `update("482", { metadata: { labels: ["x"] } })` is a no-op (no mutation + sent); document this in a test comment. + - `fire("482", "")` issues `updateProjectV2ItemFieldValue` with + the right option id. + - `fire("482", "")` throws `InvalidTransitionError`. + - Snapshot every outgoing GraphQL mutation+variables. + + Constraints: + - No `child_process.spawn`. + - Tests inject `fetch`; no live API. + - State machine override (`OpenTaskListOptions.stateMachine`) does not apply + to gh-issues; if a caller passed one, ignore it (documented in plan 5c). + status: + implement: open + test: open + commit: open + + - id: gh-issues-reorder-delete + title: gh-issues reorder + delete — move, reorder, delete + prompt: | + In `packages/task-list/src/backends/gh-issues.ts`, implement `Tasks.move`, + `Tasks.reorder`, and `Tasks.delete`. + + `move(id, anchor)`: + + 1. Resolve the project item id for `id` and the anchor's project item id + (look up the anchor by issue number, same as `id`). + 2. GraphQL mutation `updateProjectV2ItemPosition(input: { projectId, itemId, + afterId })`: + - `{ before: x }` → `afterId = ` (find x's + predecessor in the current ordering, or `null` to put at top). + - `{ after: x }` → `afterId = x's projectItemId`. + - `{ position: "top" }` → `afterId = null`. + - `{ position: "bottom" }` → `afterId = `. + 3. If the anchor id (for `before`/`after`) is missing, throw + `AnchorNotFoundError`. + 4. Return the re-fetched task. + + `reorder(ids)`: + + 1. Validate set equality vs the current active items in the project + (active = present in the project; gh-issues has no "archived" notion). + If the input is missing items or contains unknown ids, throw + `OrderMismatchError({ missing, extra })`. + 2. Issue `updateProjectV2ItemPosition` mutations sequentially: first id with + `afterId = null` (top), then each subsequent id with the previous id's + projectItemId. n round-trips, no batch primitive available. + 3. Return the re-fetched tasks in the new order. + + `delete(id)`: + + 1. Resolve the project item id by issue number. + 2. GraphQL mutation `deleteProjectV2Item(input: { projectId, itemId })`. The + issue stays in the repo (not closed). + 3. Throw `TaskNotFoundError` if the issue is not in this project. + + Tests: + - `move("482", { before: "100" })` issues the right `updateProjectV2ItemPosition` + with the predecessor's item id as `afterId`. Snapshot the mutation. + - `move("482", { after: "100" })` uses 100's item id as `afterId`. + - `move("482", { position: "top" })` uses `null`. + - `move("482", { position: "bottom" })` uses the last item's id. + - `move("482", { before: "missing" })` throws `AnchorNotFoundError`. + - `reorder(["100", "200", "482"])` issues 3 sequential position mutations, + snapshotted in order. + - `reorder(["100", "200"])` (missing 482) throws `OrderMismatchError`. + - `reorder(["100", "200", "482", "999"])` (extra 999) throws + `OrderMismatchError`. + - `delete("482")` issues `deleteProjectV2Item` and snapshots it. + - `delete("999")` (issue not in project) throws `TaskNotFoundError`. + + Constraints: + - No `child_process.spawn`. + - Tests inject `fetch`; no live API. + status: + implement: open + test: open + commit: open + + - id: gh-issues-wire + title: Wire gh-issues into open() + README + prompt: | + Final wiring task. + + 1. In `packages/task-list/src/open.ts`, dispatch on + `options.type === "gh-issues"`. Resolve auth + endpoint, then call + `ghIssuesBackend({ repo, project, defaults, token, endpoint, fetch })`. + + Auth resolution lives in `gh-issues-client.ts` (`resolveAuth` / + `resolveEndpoint`); `open.ts` is the only place in the package that calls + them. No `if/case` outside of `open.ts`. + + 2. Update `packages/task-list/src/index.ts` exports if anything new from the + backend or client should be public (likely just types, not functions). + + 3. Update `packages/task-list/README.md`: + - Add a `gh-issues` row to the backends table. + - Add a `gh-issues` usage example mirroring the `markdown-dir` / + `yaml-file` examples. Show: open with `repo` + `project`, list + singleton-name behavior, `create` ignoring `id`, `fire(state)` writing + Status, `move` reordering project items. + - Document limitations: state machine is fetched at open and frozen for + the session (re-open to refresh); `archived` is not supported (returns + empty); `update` does not write labels/assignees/milestone in v1; + `moveBetweenLists` is unsupported on gh-issues; `id` on `TaskCreate` is + ignored on this backend; `gh auth token` must be available, or pass + `auth: { token }`. + - Add `GH_HOST` to the env vars section of the README ("Defers to gh CLI's + host configuration; set GH_HOST to override."). + + 4. Run `npm test` from the package and confirm the existing 114 tests still + pass plus all new gh-issues tests are green. + + Constraints: + - No additions to README beyond what is listed (per CLAUDE.md "you are not + allowed to add anything to readme without user's permission" — this task + IS the user's permission, scoped to the items above). + - No new top-level CLI commands or SDK changes. + status: + implement: open + test: open + commit: open +--- -`repo` and `project` are required. `OpenTaskListOptions` becomes a discriminated union over `type`: +# Context -```ts -type OpenTaskListOptions = - | OpenMarkdownDirOptions - | OpenYamlFileOptions - | OpenGhIssuesOptions; +This pipeline implements steps 5–7 of the design doc that previously lived in this file. Steps 1–4 (ordering API surface, yaml-file ordering, markdown-dir filename-prefix ordering, `moveBetweenLists` for both file backends) are already merged. -interface OpenGhIssuesOptions { - type: "gh-issues"; - repo: string; // "owner/name" - project: { owner: string; number: number }; - defaults?: TaskDefaults; - auth?: { token: string }; // optional; see 5d - fetch?: typeof fetch; // injectable for tests -} -``` +## Settled design (for the executor) -`OpenGhIssuesOptions` deliberately excludes `path`, `create`, `lockStaleMs`, `lockRetries`, `fs`, and `stateMachine` — none apply. The state machine is fetched from the project (5c), not configured. +**Backend shape.** `gh-issues` is a thin wrapper over a single (repo, project) pair. One project's items show as one list of tasks. The project's `Status` field supplies the state machine. -### 5b. Mapping +**Mapping.** | `task-list` concept | GitHub mapping | | --- | --- | | backend instance | one repo + one project | -| `lists()` | returns a single name: `/` (the project itself). `taskList.list(name)` accepts only that name. | -| `id` | Issue number as a string (`"482"`). | -| `name` | Issue title. | -| `description` | Issue body. | -| `state` | The current value of the project's Status field for this item. See 5c. | -| `metadata` | `{ url, labels: string[], assignees: string[], milestone: string \| null, projectItemId: string }`. | -| priority order | The project view's row order, read via the GraphQL `items` connection. | -| `created` | Issue `createdAt` (ISO 8601). Used for `order: "created"`. | - -The earlier "Status as list" framing is dropped. Status is now the **state axis**, and the backend has only one list. This collapses the model: a GH Project is "a list of tasks with a state", and that's exactly what `Tasks` already is. - -`taskList.lists()` always returns `[/]`. `taskList.list("anything-else")` throws `Error("gh-issues backend has a single list /")`. `moveBetweenLists` is unsupported (only one list); it throws the same error. - -### 5c. State machine — fetched and dynamic +| `lists()` | single name: `/` (the project itself) | +| `id` | issue number as a string (`"482"`) | +| `name` | issue title | +| `description` | issue body | +| `state` | current value of the project's Status field for this item | +| `metadata` | `{ url, labels, assignees, milestone, projectItemId, created }` | +| priority order | the project view's row order (read via the items connection) | -At `openTaskList` time, the backend issues a GraphQL query for the project's Status field and its options. The state machine is **derived** from those options: +**State machine.** Fetched at `openTaskList`; states = Status field option names in display order; initial = first option; events = one per state, `from: "*"`, allowing any → any. Frozen for the session — re-open to refresh. `stateMachine` in `OpenTaskListOptions` is not accepted on this backend. -- `states` = the Status field's option names, in the project's display order. -- `initial` = the first option (typically `"Backlog"` or whatever the project owner put first). -- `events` = one event per state: `event name = state name`, `from: "*"`, `to: `. Any state can transition to any other state. No guards. +**Auth.** `auth: { token }` if passed; otherwise `gh auth token` via `@poe-code/process-runner`. Not parsing `~/.config/gh/hosts.yml`. `GH_HOST` honored for enterprise. -Result: `tasks.fire(id, "in-progress")` updates the issue's Status to `"in-progress"` (the option must exist on the project; otherwise the call is a no-op at the type level since the event doesn't exist). - -If the project has no `Status` field, `openTaskList` throws with a clear message: `` "Project `/` has no Status field; gh-issues requires one." `` Adding the field is a one-time setup in the GH UI; we do not mutate project schema. - -The state machine is **frozen at open time**. If the project owner adds, removes, or renames Status options mid-session, the backend keeps using the version it fetched on open. Re-open the backend to pick up changes. Documented in the package README. - -`stateMachine` in `OpenTaskListOptions` is not accepted for `gh-issues` — there's no override path. The project's Status field is the source of truth. - -#### Updating the project's Status options - -The plan reads "fetch the possible states if possible, and update them" two ways. We pick one and move: - -- We **fetch** Status options at open and use them as `states`. -- We **update** an item's Status (i.e., fire transitions) — that is the write side. -- We do **not** update the Status options themselves (adding new options, renaming them). That's project-schema mutation; the project owner does it in the GH UI. Doing it from a task-list call would surprise teammates and is a big enough surface that it deserves its own command if anyone wants it. - -If you want to add a new state, add the option in GH first, then re-open the backend. - -### 5d. Auth - -The backend defers to the `gh` CLI's configured auth — same setup the user already has working from the terminal. No new login flow, no new env var, no separate config. - -Resolution order: - -1. If `auth: { token }` is passed explicitly, use it. (Escape hatch for tests / CI without `gh` installed.) -2. Otherwise, shell out to `gh auth token` once at backend open and cache the result for the session. -3. If `gh` is not installed or returns a non-zero exit, throw with a clear message: install `gh`, run `gh auth login`, or pass `auth: { token }`. - -GraphQL endpoint follows `gh`'s convention: `GH_HOST` env var if set, else `https://api.github.com`. We do not parse `~/.config/gh/hosts.yml` directly; `gh auth token` already accounts for the active host. - -Out of scope: OAuth flows, GitHub App auth, multi-host failover. The user has a working `gh` setup, we use it. - -### 5e. Operation mapping +**Operation table.** | `Tasks` method | GH mutation | | --- | --- | -| `create({ id?, name, description })` | `createIssue` in repo, then `addProjectV2ItemById` to put it in the project, then `updateProjectV2ItemFieldValue` to set Status to `initial`. `id` is ignored on create — the GH-assigned issue number becomes the id. (The `TaskCreate.id` field becomes optional for this backend; documented.) | -| `update(id, patch)` | `updateIssue` for title/body. Metadata edits are no-ops at v1 — labels/assignees are read-only here; future work. | -| `fire(id, event)` | `updateProjectV2ItemFieldValue` setting Status to `event` (event name == target state name). | -| `delete(id)` | `deleteProjectV2Item` (removes from project; issue stays in repo, not closed). | -| `move(id, anchor)` | `updateProjectV2ItemPosition` to place the item before/after the anchor's project item. `top`/`bottom` use `null` / project end. | -| `reorder(ids)` | n positional updates in order. No batch mutation in the GraphQL API; we accept the n round-trips. | -| `all({ order })` | `priority` = project view row order; `alphabetical` = client-side sort by id; `created` = `createdAt`. | - -Issue `state` (open/closed) is **not** part of the task-list state machine. Closing or reopening an issue is out of scope here; users do it in the GH UI. If they close an issue, it stays in the project at its current Status until removed. - -### 5f. Reads, writes, caching - -- All reads hit the GraphQL API; no caching in v1. (If this gets slow we add `@poe-code/cached-resource` later — there's already a package for it.) -- Writes are: create issue, edit title/body, add/remove project item, set Status field value, reorder project item. All via GraphQL. -- Lock options (`lockStaleMs`, `lockRetries`) don't apply. Concurrent writes are arbitrated by GitHub. -- Per `feedback_no_corner_cutting`: if a GraphQL response is malformed, throw a `MalformedTaskError` with the surfaced field, don't paper over it. - -### 5g. Tests - -The backend skips the conformance suite (no live API in unit tests). It gets its own colocated tests in [packages/task-list/src/backends/gh-issues.test.ts](packages/task-list/src/backends/gh-issues.test.ts) using an injectable `fetch` mock that returns recorded GraphQL responses (one fixture per test). Snapshot the **outgoing** GraphQL queries+variables to lock the wire shape; assert on the resulting `Task` shape from the response. The `gh auth token` shell-out is bypassed by passing `auth: { token: "test-token" }` in tests. - -`@poe-code/process-runner` already exposes a process abstraction for shelling out — wire `gh auth token` through it (per `feedback_extend_not_duplicate`). No `child_process.spawn` in this package. - -## 6. Conformance tests - -[backends/conformance.test.ts](packages/task-list/src/backends/conformance.test.ts) already runs the same suite against both existing backends. Extend it with: - -- Ordering: `move(before/after/top/bottom)`, `reorder` set-equality, `all()` default = priority after archive/delete/create, `all({ order: "alphabetical" })` round-trip. -- `markdown-dir`-only: filename prefix migration (no-prefix file is treated as tail; first mutation materializes a real prefix), padding-width rebalance at the 99→100 boundary, archive strips the prefix. -- The `gh-issues` backend skips the conformance run by default (no live API in unit tests). It gets its own snapshot-style tests against a recorded GraphQL fixture in [docs/SNAPSHOT_TESTING.md](docs/SNAPSHOT_TESTING.md) style. +| `create({ name, description })` | `createIssue` → `addProjectV2ItemById` → `updateProjectV2ItemFieldValue` to initial Status. `id` on input is ignored. | +| `update(id, patch)` | `updateIssue` for title/body. Metadata is read-only in v1. | +| `fire(id, event)` | `updateProjectV2ItemFieldValue` to the target Status option. | +| `delete(id)` | `deleteProjectV2Item` (issue stays in repo, not closed). | +| `move(id, anchor)` | `updateProjectV2ItemPosition`. | +| `reorder(ids)` | n sequential `updateProjectV2ItemPosition` calls. | +| `all({ order })` | `priority` = project view order; `alphabetical` = client-side; `created` = client-side via `metadata.created` (`createdAt`). | -## 7. Implementation order +**Out of scope (v1).** Updating Status field options themselves (project schema mutation). Closing/reopening issues. OAuth flows. GitHub App auth. Multi-host failover. Cross-project reattach. -If you want to ship this incrementally: +**Tests.** Mock `fetch` in deps; snapshot outgoing GraphQL queries+variables to lock the wire shape. No live API. Bypass `gh auth token` by passing `auth: { token: "test-token" }`. -1. Ordering API surface in `types.ts` (`move`, `reorder`, `order` filter, `moveBetweenLists`) + conformance tests (red). -2. `yaml-file` ordering — YAML key order; `created` field on records. -3. `markdown-dir` ordering — filename prefix, list-level lock, `created` frontmatter timestamp, no-prefix back-compat. -4. `moveBetweenLists` on `TaskList` for both existing backends. -5. `gh-issues` backend skeleton (`openTaskList` + auth via `gh auth token` + `lists()` + `Tasks.all()` read-only). -6. `gh-issues` writes (`create`, `update`, `fire` for the GH-specific machine). -7. `gh-issues` ordering + `moveBetweenLists` (project Status field writes, item position). +## Order of execution -Each step ships green tests before the next starts. +Tasks above are listed in dependency order. Run them sequentially. The wiring task at the end pulls everything together and runs the full test suite. diff --git a/package-lock.json b/package-lock.json index 23fde9eef5..1269da08bd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7091,6 +7091,7 @@ "dependencies": { "@poe-code/agent-defs": "*", "@poe-code/agent-harness-tools": "*", + "@poe-code/agent-spawn": "*", "@poe-code/config-extends": "*", "gray-matter": "^4.0.3" } diff --git a/packages/agent-harness-tools/src/execution-env.test.ts b/packages/agent-harness-tools/src/execution-env.test.ts index 1c41ccc485..779a9767c5 100644 --- a/packages/agent-harness-tools/src/execution-env.test.ts +++ b/packages/agent-harness-tools/src/execution-env.test.ts @@ -78,8 +78,8 @@ describe("execution env registry", () => { expect(branchSites).toMatchInlineSnapshot(` [ - "execution-env.ts:85:const factory = executionEnvFactories.get(runtime.type);", - "execution-env.ts:88:\`No execution environment factory registered for runtime type "\${runtime.type}".\`", + "execution-env.ts:86:const factory = executionEnvFactories.get(runtime.type);", + "execution-env.ts:89:\`No execution environment factory registered for runtime type "\${runtime.type}".\`", ] `); }); diff --git a/packages/agent-harness-tools/src/execution-env.ts b/packages/agent-harness-tools/src/execution-env.ts index dc123e197c..19c5419137 100644 --- a/packages/agent-harness-tools/src/execution-env.ts +++ b/packages/agent-harness-tools/src/execution-env.ts @@ -9,6 +9,7 @@ export type JobStatus = "running" | "exited" | "killed" | "lost"; export interface ExecutionEnvFactory { readonly type: ExecutionEnvType; + readonly supportsDetach?: boolean; open(spec: OpenSpec): Promise; attach(envId: string): Promise; } diff --git a/packages/agent-harness-tools/src/index.ts b/packages/agent-harness-tools/src/index.ts index 8472fc4a1c..c17d786eac 100644 --- a/packages/agent-harness-tools/src/index.ts +++ b/packages/agent-harness-tools/src/index.ts @@ -48,6 +48,7 @@ export { type LogStreamFs } from "./log-stream.js"; export { runPoeCommand } from "./run-poe-command.js"; +export { resolvePoeCommandExecution } from "./poe-command-execution.js"; export { skillPlanConfigSection } from "./skill-config.js"; export * from "./execution-env.js"; export * from "./workspace-transfer.js"; diff --git a/packages/agent-harness-tools/src/poe-command-execution.ts b/packages/agent-harness-tools/src/poe-command-execution.ts new file mode 100644 index 0000000000..09adf7eaff --- /dev/null +++ b/packages/agent-harness-tools/src/poe-command-execution.ts @@ -0,0 +1,130 @@ +import { existsSync, readFileSync } from "node:fs"; +import os from "node:os"; +import { + createStateManager, + deepMergeDocuments, + parseRuntime, + resolveConfigPath, + resolveProjectConfigPath, + resolveRuntime, + resolveScope, + runtimeConfigScope, + type ConfigDocument, + type JobEntry, + type JobListFilter, + type ResolvedConfig, + type StateManager +} from "@poe-code/poe-code-config"; +import { selectExecutionEnv, type OpenSpec } from "./execution-env.js"; + +export function resolvePoeCommandExecution(input: { + cwd: string; + env: Record; + argv: string[]; + tool: string; + context?: { + homeDir?: string; + state?: StateManager; + }; + openSpec?: Partial>; +}): { + factory: ReturnType; + openSpec: OpenSpec; + detach: boolean; + state: StateManager; +} { + const homeDir = input.context?.homeDir ?? os.homedir(); + const config = loadRuntimeConfig(input.cwd, homeDir); + const resolved = resolveRuntime({ cwd: input.cwd, config }); + const factory = selectExecutionEnv(resolved.runtime); + + return { + factory, + detach: factory.supportsDetach === true && config.runner.detach, + state: input.context?.state ?? loadState(homeDir), + openSpec: { + cwd: input.cwd, + runtime: resolved.runtime, + runner: config.runner, + env: input.env, + uploadIgnoreFiles: config.runner.workspace?.exclude ?? [], + jobLabel: { + tool: input.tool, + argv: input.argv + }, + ...input.openSpec + } + }; +} + +function loadRuntimeConfig(cwd: string, homeDir: string): ResolvedConfig { + const document = deepMergeDocuments( + readConfigDocument(resolveConfigPath(homeDir)), + readConfigDocument(resolveProjectConfigPath(cwd)) + ); + const runtimeScope = resolveScope(runtimeConfigScope.schema, document.runtime, process.env); + + return { + runtime: parseRuntime(runtimeScope), + runner: runtimeScope.runner + }; +} + +function readConfigDocument(filePath: string): ConfigDocument { + if (!existsSync(filePath)) { + return {}; + } + return JSON.parse(readFileSync(filePath, "utf8")) as ConfigDocument; +} + +function loadState(homeDir: string): StateManager { + if (process.env.VITEST === "true") { + return createMemoryStateManager(); + } + return createStateManager(homeDir); +} + +function createMemoryStateManager(): StateManager { + const jobs = new Map(); + return { + templates: { + async get() { + return null; + }, + async put() {}, + async remove() {}, + async list() { + return []; + } + }, + jobs: { + async get(id) { + return jobs.get(id) ?? null; + }, + async put(entry) { + jobs.set(entry.id, entry); + }, + async update(id, patch) { + const current = jobs.get(id); + if (!current) { + return null; + } + const updated = { ...current, ...patch, id }; + jobs.set(id, updated); + return updated; + }, + async list(filter?: JobListFilter) { + const entries = Array.from(jobs.values()); + if (!filter) { + return entries; + } + return entries.filter((entry) => + Object.entries(filter).every(([key, value]) => entry[key as keyof JobEntry] === value) + ); + }, + async remove(id) { + jobs.delete(id); + } + } + }; +} diff --git a/packages/agent-spawn/package.json b/packages/agent-spawn/package.json index 71e40ea7a2..7540cff8a2 100644 --- a/packages/agent-spawn/package.json +++ b/packages/agent-spawn/package.json @@ -10,6 +10,10 @@ "types": "./dist/index.d.ts", "import": "./dist/index.js" }, + "./register-factories": { + "types": "./dist/register-factories.d.ts", + "import": "./dist/register-factories.js" + }, "./testing": { "import": "./dist/testing.js", "types": "./dist/testing.d.ts" diff --git a/packages/agent-spawn/src/register-factories.ts b/packages/agent-spawn/src/register-factories.ts index 73d8d868a0..6230a97c52 100644 --- a/packages/agent-spawn/src/register-factories.ts +++ b/packages/agent-spawn/src/register-factories.ts @@ -12,6 +12,7 @@ if (process.env.VITEST === "true") { function createTestHostExecutionEnvFactory(): ExecutionEnvFactory { return { type: "host", + supportsDetach: false, open: ((openSpec: Parameters[0]) => { return { id: "host", diff --git a/packages/agent-spawn/src/runtime.ts b/packages/agent-spawn/src/runtime.ts index 0796aaeffd..8e4c9734e6 100644 --- a/packages/agent-spawn/src/runtime.ts +++ b/packages/agent-spawn/src/runtime.ts @@ -1,158 +1 @@ -import { existsSync, readFileSync } from "node:fs"; -import os from "node:os"; -import { - createStateManager, - deepMergeDocuments, - parseRuntime, - resolveConfigPath, - resolveProjectConfigPath, - resolveRuntime, - resolveScope, - runtimeConfigScope, - type ConfigDocument, - type JobEntry, - type JobListFilter, - type ResolvedConfig, - type StateManager -} from "@poe-code/poe-code-config"; -import { - selectExecutionEnv, - type OpenSpec as HarnessOpenSpec -} from "@poe-code/agent-harness-tools"; -import type { SpawnContext } from "./types.js"; - -type OpenSpec = HarnessOpenSpec & { - execution?: { - wrapForLogTee?: boolean; - stdin?: "pipe" | "inherit" | "ignore"; - stdout?: "pipe" | "inherit"; - stderr?: "pipe" | "inherit"; - env?: Record; - tty?: boolean; - input?: string | Buffer; - captureOutput?: boolean; - activityTimeoutMs?: number; - onStdout?(chunk: string): void; - onStderr?(chunk: string): void; - }; - shellSpec?: { - command: string; - args?: string[]; - cwd?: string; - env?: Record; - stdin?: "pipe" | "inherit" | "ignore"; - stdout?: "pipe" | "inherit"; - stderr?: "pipe" | "inherit"; - tty?: boolean; - signal?: AbortSignal; - }; -}; - -export function resolveSpawnExecution(input: { - cwd: string; - env: Record; - argv: string[]; - tool: string; - context?: SpawnContext; - openSpec?: Partial>; -}): { - factory: ReturnType; - openSpec: OpenSpec; - detach: boolean; - state: StateManager; -} { - const homeDir = input.context?.homeDir ?? os.homedir(); - const config = loadRuntimeConfig(input.cwd, homeDir); - const resolved = resolveRuntime({ cwd: input.cwd, config }); - const factory = selectExecutionEnv(resolved.runtime); - - return { - factory, - detach: resolved.runtime.type === "host" ? false : config.runner.detach, - state: input.context?.state ?? loadState(homeDir), - openSpec: { - cwd: input.cwd, - runtime: resolved.runtime, - runner: config.runner, - env: input.env, - uploadIgnoreFiles: config.runner.workspace?.exclude ?? [], - jobLabel: { - tool: input.tool, - argv: input.argv - }, - ...input.openSpec - } - }; -} - -function loadRuntimeConfig(cwd: string, homeDir: string): ResolvedConfig { - const document = deepMergeDocuments( - readConfigDocument(resolveConfigPath(homeDir)), - readConfigDocument(resolveProjectConfigPath(cwd)) - ); - const runtimeScope = resolveScope(runtimeConfigScope.schema, document.runtime, process.env); - - return { - runtime: parseRuntime(runtimeScope), - runner: runtimeScope.runner - }; -} - -function readConfigDocument(filePath: string): ConfigDocument { - if (!existsSync(filePath)) { - return {}; - } - return JSON.parse(readFileSync(filePath, "utf8")) as ConfigDocument; -} - -function loadState(homeDir: string): StateManager { - if (process.env.VITEST === "true") { - return createMemoryStateManager(); - } - return createStateManager(homeDir); -} - -function createMemoryStateManager(): StateManager { - const jobs = new Map(); - return { - templates: { - async get() { - return null; - }, - async put() {}, - async remove() {}, - async list() { - return []; - } - }, - jobs: { - async get(id) { - return jobs.get(id) ?? null; - }, - async put(entry) { - jobs.set(entry.id, entry); - }, - async update(id, patch) { - const current = jobs.get(id); - if (!current) { - return null; - } - const updated = { ...current, ...patch, id }; - jobs.set(id, updated); - return updated; - }, - async list(filter?: JobListFilter) { - const entries = Array.from(jobs.values()); - if (!filter) { - return entries; - } - return entries.filter((entry) => - Object.entries(filter).every(([key, value]) => entry[key as keyof JobEntry] === value) - ); - }, - async remove(id) { - jobs.delete(id); - } - } - }; -} +export { resolvePoeCommandExecution as resolveSpawnExecution } from "@poe-code/agent-harness-tools"; diff --git a/packages/experiment-loop/package.json b/packages/experiment-loop/package.json index 446045ef99..de28dea422 100644 --- a/packages/experiment-loop/package.json +++ b/packages/experiment-loop/package.json @@ -26,6 +26,7 @@ "dependencies": { "@poe-code/agent-defs": "*", "@poe-code/agent-harness-tools": "*", + "@poe-code/agent-spawn": "*", "@poe-code/config-extends": "*", "gray-matter": "^4.0.3" } diff --git a/packages/experiment-loop/src/run/loop.ts b/packages/experiment-loop/src/run/loop.ts index 15ae14aff4..b3c3d74563 100644 --- a/packages/experiment-loop/src/run/loop.ts +++ b/packages/experiment-loop/src/run/loop.ts @@ -1,11 +1,13 @@ -import { exec as execCallback } from "node:child_process"; +import "@poe-code/agent-spawn/register-factories"; import * as fsPromises from "node:fs/promises"; import path from "node:path"; import { lockWorkflow, makeRunLogFileName, + resolvePoeCommandExecution, resolveRunLogDir, - resolveWorkflowPath + resolveWorkflowPath, + runPoeCommand } from "@poe-code/agent-harness-tools"; import { resolve } from "@poe-code/config-extends"; import { @@ -74,33 +76,58 @@ function createDefaultFs(): ExperimentFileSystem { return fs as ExperimentFileSystem; } -function createDefaultExec(): ExecFn { - return async (command, options) => - await new Promise((resolve) => { - execCallback( - command, - { - cwd: options?.cwd, - timeout: options?.timeout, - encoding: "utf8", - maxBuffer: 10 * 1024 * 1024 - }, - (error, stdout, stderr) => { - const exitCode = - error && typeof (error as NodeJS.ErrnoException & { code?: unknown }).code === "number" - ? (error as NodeJS.ErrnoException & { code: number }).code - : error - ? 1 - : 0; - - resolve({ - stdout, - stderr, - exitCode - }); +function createDefaultExec(homeDir: string): ExecFn { + return async (command, options) => { + const cwd = options?.cwd ?? process.cwd(); + const shell = process.env.SHELL ?? "sh"; + const argv = [shell, "-lc", command]; + const execution = resolvePoeCommandExecution({ + cwd, + env: process.env as Record, + argv, + tool: "experiment-loop", + context: { homeDir }, + openSpec: { + execution: { + wrapForLogTee: false, + stdin: "ignore", + stdout: "pipe", + stderr: "pipe", + captureOutput: true, + activityTimeoutMs: options?.timeout } - ); + } }); + + try { + const result = await runPoeCommand({ + factory: execution.factory, + openSpec: execution.openSpec, + detach: false, + state: execution.state + }); + + if (result.kind === "detached") { + return { stdout: "", stderr: "", exitCode: 0 }; + } + + return { + stdout: result.stdout ?? "", + stderr: result.stderr ?? "", + exitCode: result.exitCode + }; + } catch (error) { + if (isActivityTimeoutError(error)) { + return { + stdout: "", + stderr: error.message, + exitCode: 1 + }; + } + + throw error; + } + }; } function resolveJournalPath(docPath: string): string { @@ -174,6 +201,10 @@ function isAbortError(error: unknown): boolean { return error instanceof Error && error.name === "AbortError"; } +function isActivityTimeoutError(error: unknown): error is Error { + return error instanceof Error && error.name === "ActivityTimeoutError"; +} + function interpolate(template: string, values: Record): string { let output = template; for (const [key, value] of Object.entries(values)) { @@ -265,7 +296,7 @@ export async function runExperimentLoop( options: ExperimentRunOptions ): Promise { const fs = options.fs ?? createDefaultFs(); - const exec = options.exec ?? createDefaultExec(); + const exec = options.exec ?? createDefaultExec(options.homeDir); const git = options.git ?? createDefaultGit(exec); const runAgent = options.runAgent; diff --git a/packages/poe-code-config/src/runtime.ts b/packages/poe-code-config/src/runtime.ts index ea0a82cbe2..4971ae40e9 100644 --- a/packages/poe-code-config/src/runtime.ts +++ b/packages/poe-code-config/src/runtime.ts @@ -68,6 +68,8 @@ export interface RuntimeResolveResult { buildContext: string | null; } +type RuntimeResolver = (input: { cwd: string; runtime: RuntimeConfig }) => RuntimeResolveResult; + export const runtimeConfigScope = { scope: "runtime", schema: { @@ -252,25 +254,25 @@ export function resolveRuntime({ config: Pick; }): RuntimeResolveResult { const runtime = config.runtime; - if (runtime.type === "host") { + return runtimeResolvers[runtime.type]({ cwd, runtime }); +} + +const runtimeResolvers: Record = { + host({ runtime }) { return { runtime, runner: "host", dockerfilePath: null, buildContext: null }; - } - - const dockerfilePath = path.resolve( - cwd, - runtime.dockerfile ?? path.join(".poe-code", "Dockerfile") - ); - const buildContext = path.resolve(cwd, runtime.build_context ?? "."); + }, + docker({ cwd, runtime }) { + const dockerRuntime = runtime as DockerRuntime; + const { dockerfilePath, buildContext } = resolveRuntimeBuildPaths(cwd, dockerRuntime); - if (runtime.type === "docker") { - if (runtime.image !== undefined) { + if (dockerRuntime.image !== undefined) { return { - runtime, + runtime: dockerRuntime, runner: "docker", dockerfilePath: null, buildContext: null @@ -280,29 +282,43 @@ export function resolveRuntime({ throw new Error(`Docker runtime requires image or a Dockerfile at ${dockerfilePath}.`); } return { - runtime, + runtime: dockerRuntime, runner: "docker", dockerfilePath, buildContext }; - } + }, + e2b({ cwd, runtime }) { + const e2bRuntime = runtime as E2bRuntime; + const { dockerfilePath, buildContext } = resolveRuntimeBuildPaths(cwd, e2bRuntime); - if (runtime.template_id !== undefined) { + if (e2bRuntime.template_id !== undefined) { + return { + runtime: e2bRuntime, + runner: "e2b", + dockerfilePath: null, + buildContext: null + }; + } + if (!existsSync(dockerfilePath)) { + throw new Error(`E2B runtime requires template_id or a Dockerfile at ${dockerfilePath}.`); + } return { - runtime, + runtime: e2bRuntime, runner: "e2b", - dockerfilePath: null, - buildContext: null + dockerfilePath, + buildContext }; } - if (!existsSync(dockerfilePath)) { - throw new Error(`E2B runtime requires template_id or a Dockerfile at ${dockerfilePath}.`); - } +}; + +function resolveRuntimeBuildPaths( + cwd: string, + runtime: DockerRuntime | E2bRuntime +): { dockerfilePath: string; buildContext: string } { return { - runtime, - runner: "e2b", - dockerfilePath, - buildContext + dockerfilePath: path.resolve(cwd, runtime.dockerfile ?? path.join(".poe-code", "Dockerfile")), + buildContext: path.resolve(cwd, runtime.build_context ?? ".") }; } diff --git a/packages/process-runner/src/host/host-execution-env.ts b/packages/process-runner/src/host/host-execution-env.ts index d00712f97b..bcb5ebedaa 100644 --- a/packages/process-runner/src/host/host-execution-env.ts +++ b/packages/process-runner/src/host/host-execution-env.ts @@ -3,6 +3,7 @@ import type { ExecutionEnvFactory, OpenedEnv, RunSpec } from "../types.js"; export const hostExecutionEnvFactory: ExecutionEnvFactory = { type: "host", + supportsDetach: false, async open(openSpec): Promise { return { id: "host", diff --git a/packages/process-runner/src/types.ts b/packages/process-runner/src/types.ts index 8a45a480e2..f8a30013fc 100644 --- a/packages/process-runner/src/types.ts +++ b/packages/process-runner/src/types.ts @@ -39,6 +39,7 @@ export type JobStatus = "running" | "exited" | "killed" | "lost"; export interface ExecutionEnvFactory { readonly type: ExecutionEnvType; + readonly supportsDetach?: boolean; open(spec: OpenSpec): Promise; attach(envId: string): Promise; } diff --git a/packages/superintendent/src/runtime/agent-runner.ts b/packages/superintendent/src/runtime/agent-runner.ts new file mode 100644 index 0000000000..f20f1359c9 --- /dev/null +++ b/packages/superintendent/src/runtime/agent-runner.ts @@ -0,0 +1,149 @@ +import "@poe-code/agent-spawn/register-factories"; +import { mkdirSync, openSync, writeSync, closeSync } from "node:fs"; +import path from "node:path"; +import { + resolvePoeCommandExecution, + runPoeCommand +} from "@poe-code/agent-harness-tools"; +import { + buildSpawnArgs, + type McpSpawnConfig, + type SpawnMode +} from "@poe-code/agent-spawn"; + +export type { McpSpawnConfig, SpawnMode }; + +export type AutonomousInput = { + agent: string; + mode?: string; + prompt: string; + cwd?: string; + mcpServers?: McpSpawnConfig; + logPath?: string; +}; + +export type AutonomousOutput = + | string + | { + summary?: unknown; + log?: unknown; + output?: unknown; + stdout?: unknown; + text?: unknown; + toolCalls?: unknown; + sessionResult?: unknown; + logFile?: unknown; + }; + +type AutonomousRunner = ( + agent: string, + options: Omit +) => Promise; + +let injectedRunner: AutonomousRunner | undefined; + +export async function withAutonomousAgentRunner( + runner: AutonomousRunner, + operation: () => Promise +): Promise { + const previous = injectedRunner; + injectedRunner = runner; + try { + return await operation(); + } finally { + injectedRunner = previous; + } +} + +export async function runAutonomousAgent(input: AutonomousInput): Promise { + if (injectedRunner) { + return injectedRunner(input.agent, { + cwd: input.cwd, + prompt: input.prompt, + mode: input.mode, + ...(input.mcpServers ? { mcpServers: input.mcpServers } : {}), + ...(input.logPath ? { logPath: input.logPath } : {}) + }); + } + + const spawnArgs = buildSpawnArgs(input.agent, { + prompt: input.prompt, + mode: input.mode as SpawnMode | undefined, + ...(input.mcpServers ? { mcpServers: input.mcpServers } : {}) + }); + const processEnv = spawnArgs.env ? { ...process.env, ...spawnArgs.env } : undefined; + const argv = [spawnArgs.binaryName, ...spawnArgs.args]; + const logFd = input.logPath ? openSpawnLog(input.logPath) : undefined; + const execution = resolvePoeCommandExecution({ + cwd: input.cwd ?? process.cwd(), + env: (processEnv ?? process.env) as Record, + argv, + tool: input.agent, + openSpec: { + execution: { + wrapForLogTee: false, + stdin: "inherit", + stdout: "pipe", + stderr: "pipe", + env: processEnv as Record | undefined, + captureOutput: true, + onStdout(chunk) { + appendSpawnLog(logFd, chunk); + }, + onStderr(chunk) { + appendSpawnLog(logFd, chunk); + } + } + } + }); + + try { + const result = await runPoeCommand({ + factory: execution.factory, + openSpec: execution.openSpec, + detach: execution.detach, + state: execution.state + }); + + if (result.kind === "detached") { + return { + stdout: "", + ...(input.logPath ? { logFile: input.logPath } : {}) + }; + } + + return { + stdout: result.stdout ?? "", + ...(input.logPath ? { logFile: input.logPath } : {}) + }; + } finally { + closeSpawnLog(logFd); + } +} + +function openSpawnLog(filePath: string): number | undefined { + try { + mkdirSync(path.dirname(filePath), { recursive: true }); + return openSync(filePath, "a"); + } catch { + return undefined; + } +} + +function appendSpawnLog(fd: number | undefined, chunk: string): void { + if (fd === undefined) return; + try { + writeSync(fd, chunk); + } catch { + // logging is best-effort + } +} + +function closeSpawnLog(fd: number | undefined): void { + if (fd === undefined) return; + try { + closeSync(fd); + } catch { + // logging is best-effort + } +} diff --git a/packages/superintendent/src/runtime/loop.test.ts b/packages/superintendent/src/runtime/loop.test.ts index 53dcd817f4..826c8c938b 100644 --- a/packages/superintendent/src/runtime/loop.test.ts +++ b/packages/superintendent/src/runtime/loop.test.ts @@ -152,7 +152,7 @@ describe("runLoop", () => { runOwnerReviewMock.mockReset(); }); - it("passes logPath through spawn.autonomous into AgentRunInput", async () => { + it("passes logPath through the autonomous runner into AgentRunInput", async () => { const docPath = "/repo/docs/plans/feature.md"; const { fs } = createFs({ [docPath]: createDocument({ withInspectors: false }) }); const runAgent = vi.fn(async () => ({ @@ -162,20 +162,10 @@ describe("runLoop", () => { })); runBuilderMock.mockImplementation(async () => { - const { spawn } = await import("@poe-code/agent-spawn"); - const spawnApi = spawn as typeof spawn & { - autonomous?: ( - agent: string, - options: { - cwd?: string; - prompt: string; - mode?: string; - logPath?: string; - } - ) => Promise; - }; + const { runAutonomousAgent } = await import("./agent-runner.js"); - await spawnApi.autonomous?.("claude-code", { + await runAutonomousAgent({ + agent: "claude-code", prompt: "Build", cwd: "/repo", logPath: "/logs/builder.jsonl" diff --git a/packages/superintendent/src/runtime/loop.ts b/packages/superintendent/src/runtime/loop.ts index fb5a49a202..1048a687f8 100644 --- a/packages/superintendent/src/runtime/loop.ts +++ b/packages/superintendent/src/runtime/loop.ts @@ -1,11 +1,11 @@ import path from "node:path"; import * as fsPromises from "node:fs/promises"; import { lockWorkflow, makeRunLogFileName, resolveWorkflowPath } from "@poe-code/agent-harness-tools"; -import { spawn, type McpSpawnConfig } from "@poe-code/agent-spawn"; import { parseSuperintendentDoc, type SuperintendentDoc } from "../document/parse.js"; import { parseTaskBoard } from "../document/tasks.js"; import { updateStatus } from "../document/write.js"; import { createLoopState, type LoopState } from "../state/machine.js"; +import { withAutonomousAgentRunner, type McpSpawnConfig } from "./agent-runner.js"; import { runBuilder, type BuilderResult } from "./run-builder.js"; import { runInspector, type InspectorResult } from "./run-inspector.js"; import { runOwnerReview, type OwnerResult } from "./run-owner-review.js"; @@ -135,14 +135,6 @@ type TemplateLoopContext = { ownerLogPath?: string; }; -type AutonomousOptions = { - cwd?: string; - prompt: string; - mode?: string; - mcpServers?: McpSpawnConfig; - logPath?: string; -}; - type LockCapableSuperintendentFs = { open(path: string, flags: string): Promise<{ close(): Promise; @@ -157,10 +149,6 @@ type LockCapableSuperintendentFs = { unlink(path: string): Promise; }; -type SpawnWithAutonomous = typeof spawn & { - autonomous?: (agent: string, options: AutonomousOptions) => Promise; -}; - export async function runLoop( docPath: string, callbacks?: LoopCallbacks @@ -709,10 +697,7 @@ async function withInjectedAgentRunner( return operation(); } - const spawnApi = spawn as SpawnWithAutonomous; - const originalAutonomous = spawnApi.autonomous; - - spawnApi.autonomous = async (agent, input) => { + return withAutonomousAgentRunner(async (agent, input) => { const result = await options.runAgent?.({ agent, prompt: input.prompt, @@ -734,11 +719,5 @@ async function withInjectedAgentRunner( } return result; - }; - - try { - return await operation(); - } finally { - spawnApi.autonomous = originalAutonomous; - } + }, operation); } diff --git a/packages/superintendent/src/runtime/run-builder.test.ts b/packages/superintendent/src/runtime/run-builder.test.ts index 6d0cc4428a..ff31849355 100644 --- a/packages/superintendent/src/runtime/run-builder.test.ts +++ b/packages/superintendent/src/runtime/run-builder.test.ts @@ -5,15 +5,33 @@ const { autonomousMock } = vi.hoisted(() => ({ autonomousMock: vi.fn< ( agent: string, - options: { mode?: string; prompt: string; cwd?: string } + options: { + mode?: string; + prompt: string; + cwd?: string; + mcpServers?: unknown; + logPath?: string; + } ) => Promise >() })); -vi.mock("@poe-code/agent-spawn", () => ({ - spawn: Object.assign(vi.fn(), { - autonomous: autonomousMock - }) +vi.mock("./agent-runner.js", () => ({ + runAutonomousAgent: (input: { + agent: string; + mode?: string; + prompt: string; + cwd?: string; + mcpServers?: unknown; + logPath?: string; + }) => + autonomousMock(input.agent, { + cwd: input.cwd, + prompt: input.prompt, + mode: input.mode, + ...(input.mcpServers ? { mcpServers: input.mcpServers } : {}), + ...(input.logPath ? { logPath: input.logPath } : {}) + }) })); const document: SuperintendentDoc = { diff --git a/packages/superintendent/src/runtime/run-builder.ts b/packages/superintendent/src/runtime/run-builder.ts index 32906b2199..3812fa9d26 100644 --- a/packages/superintendent/src/runtime/run-builder.ts +++ b/packages/superintendent/src/runtime/run-builder.ts @@ -1,5 +1,10 @@ -import { spawn, type McpSpawnConfig, type SpawnMode } from "@poe-code/agent-spawn"; +import "@poe-code/agent-spawn/register-factories"; import type { SuperintendentDoc } from "../document/parse.js"; +import { + runAutonomousAgent, + type AutonomousOutput, + type McpSpawnConfig +} from "./agent-runner.js"; import { resolveRoleCwd } from "./resolve-cwd.js"; import { resolveTemplate, type TemplateContext } from "./templates.js"; @@ -9,33 +14,6 @@ export type BuilderResult = { log_path: string; }; -type AutonomousInput = { - agent: string; - mode?: string; - prompt: string; - cwd?: string; - mcpServers?: McpSpawnConfig; - logPath?: string; -}; - -type AutonomousOutput = - | string - | { - summary?: unknown; - log?: unknown; - output?: unknown; - stdout?: unknown; - text?: unknown; - logFile?: unknown; - }; - -type SpawnWithAutonomous = typeof spawn & { - autonomous?: ( - agent: string, - options: Omit - ) => Promise; -}; - export type RunBuilderOptions = { promptOverride?: string; defaultCwd: string; @@ -50,7 +28,7 @@ export async function runBuilder( const prompt = options.promptOverride ?? resolveTemplate(doc.frontmatter.builder.prompt, buildTemplateContext(doc, context)); - const result = await runAutonomous({ + const result = await runAutonomousAgent({ agent: doc.frontmatter.builder.agent, mode: doc.frontmatter.builder.mode, prompt, @@ -103,33 +81,6 @@ function buildTemplateContext( }; } -async function runAutonomous(input: AutonomousInput): Promise { - const spawnApi = spawn as SpawnWithAutonomous; - - if (typeof spawnApi.autonomous === "function") { - return spawnApi.autonomous(input.agent, { - cwd: input.cwd, - prompt: input.prompt, - mode: input.mode, - ...(input.mcpServers ? { mcpServers: input.mcpServers } : {}), - ...(input.logPath ? { logPath: input.logPath } : {}) - }); - } - - const result = await spawn(input.agent, { - cwd: input.cwd, - prompt: input.prompt, - mode: input.mode as SpawnMode | undefined, - ...(input.mcpServers ? { mcpServers: input.mcpServers } : {}), - ...(input.logPath ? { logPath: input.logPath } : {}) - }); - - return { - stdout: result.stdout, - ...(result.logFile ? { logFile: result.logFile } : {}) - }; -} - function extractLog(result: AutonomousOutput): string { if (typeof result === "string") { return result; diff --git a/packages/superintendent/src/runtime/run-inspector.test.ts b/packages/superintendent/src/runtime/run-inspector.test.ts index c3b802ea57..bf9d167e69 100644 --- a/packages/superintendent/src/runtime/run-inspector.test.ts +++ b/packages/superintendent/src/runtime/run-inspector.test.ts @@ -5,15 +5,33 @@ const { autonomousMock } = vi.hoisted(() => ({ autonomousMock: vi.fn< ( agent: string, - options: { mode?: string; prompt: string; cwd?: string } + options: { + mode?: string; + prompt: string; + cwd?: string; + mcpServers?: unknown; + logPath?: string; + } ) => Promise >() })); -vi.mock("@poe-code/agent-spawn", () => ({ - spawn: Object.assign(vi.fn(), { - autonomous: autonomousMock - }) +vi.mock("./agent-runner.js", () => ({ + runAutonomousAgent: (input: { + agent: string; + mode?: string; + prompt: string; + cwd?: string; + mcpServers?: unknown; + logPath?: string; + }) => + autonomousMock(input.agent, { + cwd: input.cwd, + prompt: input.prompt, + mode: input.mode, + ...(input.mcpServers ? { mcpServers: input.mcpServers } : {}), + ...(input.logPath ? { logPath: input.logPath } : {}) + }) })); const document: SuperintendentDoc = { diff --git a/packages/superintendent/src/runtime/run-inspector.ts b/packages/superintendent/src/runtime/run-inspector.ts index c4d4cdd2e7..c5ff0e2037 100644 --- a/packages/superintendent/src/runtime/run-inspector.ts +++ b/packages/superintendent/src/runtime/run-inspector.ts @@ -1,5 +1,10 @@ -import { spawn, type McpSpawnConfig, type SpawnMode } from "@poe-code/agent-spawn"; +import "@poe-code/agent-spawn/register-factories"; import type { AgentRoleConfig, SuperintendentDoc } from "../document/parse.js"; +import { + runAutonomousAgent, + type AutonomousOutput, + type McpSpawnConfig +} from "./agent-runner.js"; import { resolveRoleCwd } from "./resolve-cwd.js"; import { buildInspectorSystemPrompt, prependSystemPrompt } from "./system-prompt.js"; import { resolveTemplate, type TemplateContext } from "./templates.js"; @@ -10,32 +15,6 @@ export type InspectorResult = { log_path?: string; }; -type AutonomousInput = { - agent: string; - mode?: string; - prompt: string; - cwd?: string; - mcpServers?: McpSpawnConfig; - logPath?: string; -}; - -type AutonomousOutput = - | string - | { - summary?: unknown; - output?: unknown; - stdout?: unknown; - text?: unknown; - logFile?: unknown; - }; - -type SpawnWithAutonomous = typeof spawn & { - autonomous?: ( - agent: string, - options: Omit - ) => Promise; -}; - export type RunInspectorOptions = { promptOverride?: string; defaultCwd: string; @@ -64,7 +43,7 @@ export async function runInspector( : {}) }); const prompt = prependSystemPrompt(systemPrompt, userPrompt); - const output = await runAutonomous({ + const output = await runAutonomousAgent({ agent: config.agent, mode: config.mode, prompt, @@ -153,33 +132,6 @@ function buildTemplateContext( }; } -async function runAutonomous(input: AutonomousInput): Promise { - const spawnApi = spawn as SpawnWithAutonomous; - - if (typeof spawnApi.autonomous === "function") { - return spawnApi.autonomous(input.agent, { - cwd: input.cwd, - prompt: input.prompt, - mode: input.mode, - ...(input.mcpServers ? { mcpServers: input.mcpServers } : {}), - ...(input.logPath ? { logPath: input.logPath } : {}) - }); - } - - const result = await spawn(input.agent, { - cwd: input.cwd, - prompt: input.prompt, - mode: input.mode as SpawnMode | undefined, - ...(input.mcpServers ? { mcpServers: input.mcpServers } : {}), - ...(input.logPath ? { logPath: input.logPath } : {}) - }); - - return { - stdout: result.stdout, - ...(result.logFile ? { logFile: result.logFile } : {}) - }; -} - function extractLogPath(result: AutonomousOutput): string | undefined { if (typeof result === "string") return undefined; return typeof result.logFile === "string" ? result.logFile : undefined; diff --git a/packages/superintendent/src/runtime/run-owner-review.test.ts b/packages/superintendent/src/runtime/run-owner-review.test.ts index 65845d3501..4a3a93a5a9 100644 --- a/packages/superintendent/src/runtime/run-owner-review.test.ts +++ b/packages/superintendent/src/runtime/run-owner-review.test.ts @@ -16,10 +16,22 @@ const { autonomousMock } = vi.hoisted(() => ({ >() })); -vi.mock("@poe-code/agent-spawn", () => ({ - spawn: Object.assign(vi.fn(), { - autonomous: autonomousMock - }) +vi.mock("./agent-runner.js", () => ({ + runAutonomousAgent: (input: { + agent: string; + mode?: string; + prompt: string; + cwd?: string; + mcpServers?: unknown; + logPath?: string; + }) => + autonomousMock(input.agent, { + cwd: input.cwd, + prompt: input.prompt, + mode: input.mode, + ...(input.mcpServers ? { mcpServers: input.mcpServers } : {}), + ...(input.logPath ? { logPath: input.logPath } : {}) + }) })); const document: SuperintendentDoc = { diff --git a/packages/superintendent/src/runtime/run-owner-review.ts b/packages/superintendent/src/runtime/run-owner-review.ts index 9ae50d525d..d7c755642a 100644 --- a/packages/superintendent/src/runtime/run-owner-review.ts +++ b/packages/superintendent/src/runtime/run-owner-review.ts @@ -1,5 +1,10 @@ -import { spawn, type McpSpawnConfig, type SpawnMode } from "@poe-code/agent-spawn"; +import "@poe-code/agent-spawn/register-factories"; import type { McpConfig, SuperintendentDoc } from "../document/parse.js"; +import { + runAutonomousAgent, + type AutonomousOutput, + type McpSpawnConfig +} from "./agent-runner.js"; import { resolveRoleCwd } from "./resolve-cwd.js"; import { buildOwnerSystemPrompt, prependSystemPrompt } from "./system-prompt.js"; import { resolveTemplate, type TemplateContext } from "./templates.js"; @@ -19,15 +24,6 @@ export type OwnerResult = { log_path?: string; }; -type AutonomousInput = { - agent: string; - mode?: string; - prompt: string; - cwd?: string; - mcpServers?: McpSpawnConfig; - logPath?: string; -}; - type ToolCallLike = { name?: unknown; tool?: unknown; @@ -38,22 +34,6 @@ type ToolCallLike = { input?: unknown; }; -type AutonomousOutput = - | string - | { - toolCalls?: unknown; - sessionResult?: unknown; - stdout?: unknown; - logFile?: unknown; - }; - -type SpawnWithAutonomous = typeof spawn & { - autonomous?: ( - agent: string, - options: Omit - ) => Promise; -}; - const WORKFLOW_SERVER_NAME = "owner-workflow"; const WORKFLOW_SERVER_COMMAND = "poe-superintendent-mcp"; const WORKFLOW_SERVER_SUBCOMMAND = "workflow-transition"; @@ -74,7 +54,7 @@ export async function runOwnerReview( buildTemplateContext(doc, context) ); const prompt = prependSystemPrompt(buildOwnerSystemPrompt(), userPrompt); - const result = await runAutonomous({ + const result = await runAutonomousAgent({ agent: doc.frontmatter.owner.agent, mode: doc.frontmatter.owner.mode, prompt, @@ -132,33 +112,6 @@ function toSpawnMcpServer(config: McpConfig): McpSpawnConfig[string] { }; } -async function runAutonomous(input: AutonomousInput): Promise { - const spawnApi = spawn as SpawnWithAutonomous; - - if (typeof spawnApi.autonomous === "function") { - return spawnApi.autonomous(input.agent, { - cwd: input.cwd, - prompt: input.prompt, - mode: input.mode, - ...(input.mcpServers ? { mcpServers: input.mcpServers } : {}), - ...(input.logPath ? { logPath: input.logPath } : {}) - }); - } - - const result = await spawn(input.agent, { - cwd: input.cwd, - prompt: input.prompt, - mode: input.mode as SpawnMode | undefined, - ...(input.mcpServers ? { mcpServers: input.mcpServers } : {}), - ...(input.logPath ? { logPath: input.logPath } : {}) - }); - - return { - stdout: result.stdout, - ...(result.logFile ? { logFile: result.logFile } : {}) - }; -} - function extractLogPath(result: AutonomousOutput): string | undefined { if (typeof result === "string") return undefined; return typeof result.logFile === "string" ? result.logFile : undefined; diff --git a/packages/superintendent/src/runtime/run-superintendent.test.ts b/packages/superintendent/src/runtime/run-superintendent.test.ts index 04eb2c860f..543b68c8cc 100644 --- a/packages/superintendent/src/runtime/run-superintendent.test.ts +++ b/packages/superintendent/src/runtime/run-superintendent.test.ts @@ -16,10 +16,22 @@ const { autonomousMock } = vi.hoisted(() => ({ >() })); -vi.mock("@poe-code/agent-spawn", () => ({ - spawn: Object.assign(vi.fn(), { - autonomous: autonomousMock - }) +vi.mock("./agent-runner.js", () => ({ + runAutonomousAgent: (input: { + agent: string; + mode?: string; + prompt: string; + cwd?: string; + mcpServers?: unknown; + logPath?: string; + }) => + autonomousMock(input.agent, { + cwd: input.cwd, + prompt: input.prompt, + mode: input.mode, + ...(input.mcpServers ? { mcpServers: input.mcpServers } : {}), + ...(input.logPath ? { logPath: input.logPath } : {}) + }) })); const document: SuperintendentDoc = { diff --git a/packages/superintendent/src/runtime/run-superintendent.ts b/packages/superintendent/src/runtime/run-superintendent.ts index 82963d4892..ce6a70f1ff 100644 --- a/packages/superintendent/src/runtime/run-superintendent.ts +++ b/packages/superintendent/src/runtime/run-superintendent.ts @@ -1,5 +1,10 @@ -import { spawn, type McpSpawnConfig, type SpawnMode } from "@poe-code/agent-spawn"; +import "@poe-code/agent-spawn/register-factories"; import type { McpConfig, SuperintendentDoc } from "../document/parse.js"; +import { + runAutonomousAgent, + type AutonomousOutput, + type McpSpawnConfig +} from "./agent-runner.js"; import { resolveRoleCwd } from "./resolve-cwd.js"; import { buildSuperintendentSystemPrompt, @@ -14,15 +19,6 @@ export type SuperintendentResult = { log_path?: string; }; -type AutonomousInput = { - agent: string; - mode?: string; - prompt: string; - cwd?: string; - mcpServers?: McpSpawnConfig; - logPath?: string; -}; - type ToolCallLike = { name?: unknown; tool?: unknown; @@ -33,25 +29,6 @@ type ToolCallLike = { input?: unknown; }; -type AutonomousOutput = - | string - | { - summary?: unknown; - output?: unknown; - stdout?: unknown; - text?: unknown; - toolCalls?: unknown; - sessionResult?: unknown; - logFile?: unknown; - }; - -type SpawnWithAutonomous = typeof spawn & { - autonomous?: ( - agent: string, - options: Omit - ) => Promise; -}; - const SUPERINTENDENT_TOOLS_SERVER_NAME = "superintendent-tools"; const SUPERINTENDENT_TOOLS_SERVER_COMMAND = "poe-superintendent-mcp"; const SUPERINTENDENT_TOOLS_SERVER_SUBCOMMAND = "superintendent-tools"; @@ -76,7 +53,7 @@ export async function runSuperintendent( inspectorNames: Object.keys(doc.frontmatter.inspectors ?? {}) }); const prompt = prependSystemPrompt(systemPrompt, userPrompt); - const result = await runAutonomous({ + const result = await runAutonomousAgent({ agent: doc.frontmatter.superintendent.agent, mode: doc.frontmatter.superintendent.mode, prompt, @@ -146,33 +123,6 @@ function toSpawnMcpServer(config: McpConfig): McpSpawnConfig[string] { }; } -async function runAutonomous(input: AutonomousInput): Promise { - const spawnApi = spawn as SpawnWithAutonomous; - - if (typeof spawnApi.autonomous === "function") { - return spawnApi.autonomous(input.agent, { - cwd: input.cwd, - prompt: input.prompt, - mode: input.mode, - ...(input.mcpServers ? { mcpServers: input.mcpServers } : {}), - ...(input.logPath ? { logPath: input.logPath } : {}) - }); - } - - const result = await spawn(input.agent, { - cwd: input.cwd, - prompt: input.prompt, - mode: input.mode as SpawnMode | undefined, - ...(input.mcpServers ? { mcpServers: input.mcpServers } : {}), - ...(input.logPath ? { logPath: input.logPath } : {}) - }); - - return { - stdout: result.stdout, - ...(result.logFile ? { logFile: result.logFile } : {}) - }; -} - function extractLogPath(result: AutonomousOutput): string | undefined { if (typeof result === "string") return undefined; return typeof result.logFile === "string" ? result.logFile : undefined; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index faa42c554c..714c3a8d52 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -388,6 +388,9 @@ importers: '@poe-code/agent-harness-tools': specifier: '*' version: link:../agent-harness-tools + '@poe-code/agent-spawn': + specifier: '*' + version: link:../agent-spawn '@poe-code/config-extends': specifier: '*' version: link:../config-extends From daff0d02a0a19674c4834161efa79e8086f50950 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 18:55:20 -0500 Subject: [PATCH 015/111] feat: add runtime overrides for agent runs --- docs/plans/agent-harness.md | 1187 +++++++++++------ docs/plans/e2b-integration.md | 6 +- docs/plans/e2b-integration.md.lock | 2 +- packages/agent-harness-tools/src/index.ts | 6 +- .../src/poe-command-execution.test.ts | 50 + .../src/poe-command-execution.ts | 49 +- packages/agent-script/README.md | 365 +++-- packages/agent-spawn/src/acp/acp.test.ts | 113 +- packages/agent-spawn/src/acp/spawn-acp.ts | 5 + packages/agent-spawn/src/acp/spawn.ts | 204 +-- packages/agent-spawn/src/spawn-interactive.ts | 7 + packages/agent-spawn/src/spawn.ts | 7 + packages/agent-spawn/src/types.ts | 11 + packages/experiment-loop/src/run/loop.ts | 5 + packages/experiment-loop/src/types.ts | 10 + packages/ralph/src/run/ralph.ts | 5 + packages/ralph/src/types.ts | 10 + .../superintendent/src/commands/run.test.ts | 54 + packages/superintendent/src/commands/run.ts | 59 +- .../src/runtime/agent-runner.ts | 20 +- packages/superintendent/src/runtime/loop.ts | 5 + .../__snapshots__/runtime-help.test.ts.snap | 111 ++ src/cli/commands/experiment-ralph.test.ts | 76 ++ src/cli/commands/experiment.ts | 20 +- src/cli/commands/ralph.ts | 22 +- src/cli/commands/runtime-help.test.ts | 83 ++ src/cli/commands/runtime-options.ts | 35 + src/cli/commands/spawn-command.test.ts | 40 + src/cli/commands/spawn.ts | 15 +- src/providers/spawn-options.ts | 6 + src/sdk/experiment.ts | 5 + src/sdk/ralph.test.ts | 10 +- src/sdk/ralph.ts | 5 + src/sdk/sdk-core.test.ts | 8 +- src/sdk/spawn.test.ts | 55 + src/sdk/spawn.ts | 24 +- src/sdk/types.ts | 11 + 37 files changed, 1973 insertions(+), 733 deletions(-) create mode 100644 packages/agent-harness-tools/src/poe-command-execution.test.ts create mode 100644 src/cli/commands/__snapshots__/runtime-help.test.ts.snap create mode 100644 src/cli/commands/runtime-help.test.ts create mode 100644 src/cli/commands/runtime-options.ts diff --git a/docs/plans/agent-harness.md b/docs/plans/agent-harness.md index 0fd40f37db..ca9be6e89d 100644 --- a/docs/plans/agent-harness.md +++ b/docs/plans/agent-harness.md @@ -1,45 +1,710 @@ --- -$schema: https://poe-platform.github.io/poe-code/schemas/plans/plan.schema.json -kind: plan +$schema: https://poe-platform.github.io/poe-code/schemas/plans/pipeline.schema.json +kind: pipeline version: 1 ---- - -# agent-harness - -A generic runner for agent-script-based harnesses, paired with co-located markdown documents that supply prompts and config. - -## 1. What we're building - -A new package, `@poe-code/agent-harness`, that runs a **harness pair**: - -- `.ajs` — orchestration script (agent-script source, the program the runtime executes) -- `.md` — complementary markdown document with YAML frontmatter (prompts, agent config, status, research brief) - -The `.ajs` is the orchestrator; the `.md` is data the orchestrator reads. The runtime pairs them by filename, lints + executes the `.ajs`, and exposes the markdown's validated frontmatter as the entry function's argument plus the body via `import.meta`. - -This is **experimental**. It runs alongside the existing `experiment-loop` / `ralph` / `pipeline` / `superintendent` packages without touching them. The shipped templates are demonstrations of how each shape could be expressed as a harness pair; reaching parity with the existing runners is a future goal, not part of this work. -Non-goals: - -- Not a new language. Reuses `agent-script` parser/linter/runtime as-is. -- Not a replacement for `agent-harness-tools` runtime helpers (lock, hooks, run-logs, select-agent). Those keep their place; agent-harness uses them for cross-cutting concerns. -- **Not changing anything about `experiment run` / `ralph run` / `pipeline run` / `superintendent run`.** Those runners, their CLI surfaces, frontmatter, schemas, and packages stay untouched. Parity with them is a future goal, explicitly out of scope. -- Not replacing `scripts/generate-plan-schemas.ts` or any existing `docs/schemas/plans/*.schema.json`. Harness schemas emit to a new path that does not collide. -- No regex-based markdown parsing or templating system invented here — uses the existing `agent-script` loader. - -## 2. User-facing shape +tasks: + - id: toolcraft-schema-validate + title: Add runtime validate() to @poe-code/toolcraft-schema + prompt: | + In packages/toolcraft-schema, add a runtime `validate()` that walks + a SchemaDescriptor and returns either `{ ok: true, value }` (with + defaults applied for missing optionals) or `{ ok: false, issues }`. + + Files to create: + - packages/toolcraft-schema/src/validate.ts + - packages/toolcraft-schema/src/validate.test.ts + + Files to change: + - packages/toolcraft-schema/src/index.ts — re-export + `validate`, `ValidationIssue`, `ValidationResult`. + + Signatures: + type ValidationIssue = { path: readonly string[]; expected: string; + received: string; message: string }; + type ValidationResult = + | { ok: true; value: T } + | { ok: false; issues: readonly ValidationIssue[] }; + function validate( + schema: S, value: unknown + ): ValidationResult>; + + Behavior: + - Walk schema mirror of toJsonSchema. Zero-dep, no ajv. + - S.Optional + missing value: emit `default` if set; otherwise omit. + - S.Object: reject unknown properties (matches the + `additionalProperties: false` toJsonSchema emits). + - S.Enum: reject values not in the const tuple. + - S.Number minimum / S.String minLength / S.Array minItems all + enforced; emit issue with `path` (dotted segments) and `received`. + - On any issue, return ok:false with all collected issues; do not + throw. + + Tests must run in-memory only (no fs). Cover every builder, defaults + application, additionalProperties rejection, nested object paths, + and the multi-issue accumulation behavior. + status: + implement: open + test: open + commit: open + + - id: agent-script-export-parser + title: Parse `export const X = expr` and `export default expr` in agent-script + prompt: | + Extend agent-script's parser to accept two new top-level forms: + - `export const NAME = ;` — single declarator only. + - `export default ;` — initializer must be an + ArrowFunctionExpression (sync or async). + + Both are top-level only. Reject `export function`, `export class`, + `export *`, `export { ... }`, multiple `export default`, and any + non-arrow default initializer at parse time (DisallowedSyntaxError). + + Files to create: + - packages/agent-script/src/parse/parse-export.ts + + Files to change: + - packages/agent-script/src/parse/parser.ts — add AST types + `ExportNamedDeclaration` { type, declaration: VariableDeclaration } + and `ExportDefaultDeclaration` + { type, declaration: ArrowFunctionExpression } to the Statement + union; wire token-level entrypoints from the top-level + statement parser. Disallow these forms when the top-level is an + expression rather than a module. + + Tests in packages/agent-script/src/parse/parse.test.ts (or a new + parse-export.test.ts): + - accept: `export const x = 1`, `export const schema = S.Object({})`, + `export default async () => 1`, `export default () => {}`. + - reject: function decl, class decl, `export *`, `export {x}`, + `export default function`, two `export default` in one module, + `export const a = 1, b = 2` (single declarator only), + export inside a block. + + Do not change runtime semantics yet; just parsing + AST. + status: + implement: open + test: open + commit: open + + - id: agent-script-import-meta-parser + title: Parse `import.meta` as a MetaProperty expression in agent-script + prompt: | + Extend agent-script's parser to accept `import.meta` as an + expression. Member access (`import.meta.body`), destructuring + (`const { body } = import.meta`), and aliasing + (`const m = import.meta`) all work via standard expression rules. + Direct assignment to `import.meta` or any of its properties is a + DisallowedSyntaxError at parse time. + + Files to create: + - packages/agent-script/src/parse/parse-import-meta.ts + + Files to change: + - packages/agent-script/src/parse/parser.ts — add AST type + `MetaProperty` { type, meta: Identifier("import"), + property: Identifier("meta") } to the Expression union; + recognize the token sequence `import` `.` `meta` in expression + position. + + Tests: + - accept: `import.meta`, `import.meta.body`, + `const { body } = import.meta`, `const m = import.meta; + m.body`. + - reject: `import.meta = x`, `import.meta.x = 1`, + `[import.meta] = [...]`, `import.meta()` may parse as a call + (allowed) but assignment-to is rejected. + + Do not wire runtime resolution yet — that's a later task. + status: + implement: open + test: open + commit: open + + - id: agent-script-export-lint + title: Lint rules for export forms and import.meta in agent-script + prompt: | + Add lint codes for the new export and import.meta syntax. The + linter takes a new option `allowedExportNames?: readonly string[]` + defaulting to no allowed names; unknown names emit + `AS-EXPORT-UNKNOWN`. + + Files to change: + - packages/agent-script/src/lint.ts — add codes: + - `AS-EXPORT-UNKNOWN` (named export of a name not in + allowedExportNames). + - `AS-EXPORT-DEFAULT-MULTIPLE` (more than one export default + in the module). + - `AS-EXPORT-DEFAULT-NOT-ARROW` (default initializer is not an + arrow expression). + - `AS-RETURN-AT-TOP` (warning, top-level `return` statement + present alongside an `export default`). + - `AS-IMPORT-META-ASSIGN` (assignment target involves + `import.meta`). + Add `allowedExportNames` to `LintOptions`. + + Files to change in tests (or create new): + - packages/agent-script/src/lint.test.ts — cover each new code + for accept and reject cases. Use `allowedExportNames: ["schema"]` + to test that path; default empty to test the rejection path. + + Do not introduce a runtime requirement that there must be an + `export default`. That decision belongs to the agent-harness + loader, not the linter. + status: + implement: open + test: open + commit: open + + - id: agent-script-runtime-entry + title: Wire importMeta and entryPointArgs into agent-script run() + prompt: | + Extend the agent-script runtime so a host can inject a value for + `import.meta` and supply arguments to be passed into the resolved + `export default` function. + + Files to change: + - packages/agent-script/src/run.ts — add to RunOptions: + importMeta?: Record; + entryPointArgs?: readonly unknown[]; + When `entryPointArgs` is set: after evaluating the module + top-level, look up the default export binding (must be a + callable). Call it with `entryPointArgs`; the awaited result + becomes `returnValue`. If the default export is missing, throw + a runtime error that names the script filename. + - packages/agent-script/src/interp/scope.ts (or the import + binding equivalent) — resolve `MetaProperty` to a deeply-copied + sandbox value of `options.importMeta ?? {}`. + - packages/agent-script/src/interp/cancel.ts — confirm the + existing cancellation wrapping still applies inside the entry + call. The script never sees `signal`; cancellation throws + `SandboxError("aborted")` at the next host call as today. + + Tests in packages/agent-script/src/run.test.ts: + - import.meta resolves to the injected object; properties are + deep-copied (mutating the host object after run starts does + not affect script-side reads). + - entryPointArgs: arrow default export receives the args, its + return becomes returnValue. + - missing default export with entryPointArgs set: runtime error + with filename. + - default export throws: error propagates with sandbox-correct + formatting. + - cancellation between two host calls inside the entry function + still aborts; snapshot captured before the abort allows + restore() to resume from the next tick (use the existing + snapshot test patterns). + + No regex use, no string-level surgery. Use the parser + interpreter + end-to-end. + status: + implement: open + test: open + commit: open + + - id: agent-script-find-exported + title: Add findExportedConstInitializer to agent-script + prompt: | + Add a helper that, given a parsed Module AST, returns the + initializer Expression of `export const = ;` at the + top level, or undefined. + + Files to create: + - packages/agent-script/src/loader/find-exported.ts + - packages/agent-script/src/loader/find-exported.test.ts + + Files to change: + - packages/agent-script/src/index.ts — export + `findExportedConstInitializer` and the `ExportNamedDeclaration`, + `ExportDefaultDeclaration`, `MetaProperty` AST types added in + earlier tasks. + + Signature: + function findExportedConstInitializer( + module: Module, + name: string + ): Expression | undefined; + + Behavior: + - Walk only top-level Statements (no recursion into blocks). + - Match `ExportNamedDeclaration` whose declaration is a + `VariableDeclaration` with `kind: "const"` and a single + declarator whose id is an Identifier with the given name. + - Return the declarator's `init` expression. Return undefined if + no match. + + Tests with parsed fixtures: present, absent, wrong name, nested + block (should be ignored), `let`/`var` (should be ignored). + status: + implement: open + test: open + commit: open + + - id: agent-harness-skeleton + title: Create @poe-code/agent-harness package skeleton + prompt: | + Create the new package at packages/agent-harness/ with the standard + poe-code package layout. Per CLAUDE.md the package must have its + own README listing env variables and config options (this package + reads neither, so document that explicitly). + + Files to create: + - packages/agent-harness/package.json — name + `@poe-code/agent-harness`, depends on `@poe-code/agent-script`, + `@poe-code/agent-harness-tools`, `@poe-code/toolcraft-schema`. + Match the script set used by other monorepo packages + (build/test). No publish-time CLI. + - packages/agent-harness/tsconfig.json — extend the repo's + shared package tsconfig. + - packages/agent-harness/README.md — short overview, env vars + (none), config options (none). + - packages/agent-harness/src/index.ts — empty re-export hub for + types added in later tasks. + + Files to change: + - root tsconfig.json / turbo.json / package.json workspaces if + required so the package is recognized by the build. + + Do not implement loader, modules, templates, codegen, or CLI here — + those land in subsequent tasks. The package must build green + (`npm run build` succeeds) at the end of this task. + status: + implement: open + commit: open + + - id: agent-harness-schema-module + title: Implement schema host module exposing toolcraft-schema S + prompt: | + Add a host module for agent-script that exposes the toolcraft-schema + builders under the module name `schema`. The builders are pure + data constructors so no host bridging logic is needed. + + Files to create: + - packages/agent-harness/src/modules/schema.ts + - packages/agent-harness/src/modules/schema.test.ts + + Files to change: + - packages/agent-harness/src/index.ts — re-export + `makeSchemaModule`. + + Signature: + import { S } from "@poe-code/toolcraft-schema"; + export function makeSchemaModule(): { S: typeof S }; + + Tests: + - Round-trip through agent-script's `run()`: a script that does + `import { S } from "schema"; return S.Object({ x: S.Number() });` + returns the same descriptor toolcraft-schema would build + directly. + - Lint round-trip: passing the module's exports list to + `lint({ modules })` accepts `import { S } from "schema"`. + - All filesystem state through memfs (none expected here). + status: + implement: open + test: open + commit: open + + - id: agent-harness-pair-resolver + title: Resolve .md ↔ .ajs in the same directory + prompt: | + Add a pair resolver. Given the path to an .md, find its sibling + .ajs with the same basename in the same directory; given a .ajs, + find its sibling .md. Either input form must work. + + Files to create: + - packages/agent-harness/src/loader/pair.ts + - packages/agent-harness/src/loader/pair.test.ts + + Files to change: + - packages/agent-harness/src/index.ts — re-export + `resolvePair`, `HarnessPair`, `HarnessFs`. + + Signatures: + type HarnessPair = { ajsPath: string; mdPath: string; + basename: string }; + type HarnessFs = { + stat(path: string): Promise<{ isFile(): boolean }>; + }; + function resolvePair( + inputPath: string, + fs?: HarnessFs + ): Promise; + + Behavior: + - Accept either `.md` or `.ajs` input; compute the sibling. + - Both files must exist and be regular files. Otherwise throw a + `MissingPairError` naming which side is missing. + - Reject inputs whose extension is neither `.md` nor `.ajs` + with a typed error. + - `basename` is the shared stem. + + Tests use memfs per CLAUDE.md. Cover: pair with both, missing + .ajs, missing .md, wrong extension input, directory passed + instead of file. + status: + implement: open + test: open + commit: open + + - id: agent-harness-discovery + title: Discover harness pairs in .poe-code/harnesses/ + prompt: | + Walk a root directory and return all valid harness pairs found in + first-level subdirectories. Project-level results take precedence + over user-level when paths conflict. + + Files to create: + - packages/agent-harness/src/discovery/discover.ts + - packages/agent-harness/src/discovery/discover.test.ts + + Files to change: + - packages/agent-harness/src/index.ts — re-export + `discoverHarnesses`. + + Signature: + function discoverHarnesses( + rootDir: string, + fs?: HarnessFs + ): Promise; + + Behavior: + - For each immediate subdirectory of rootDir, look for a + `/.md` + `/.ajs` pair using the resolver + from the previous task. Skip subdirectories without both. + - Return results sorted alphabetically by basename. + - Do not recurse beyond one level — harnesses live in their own + named directory. + - Missing rootDir resolves to `[]` (not an error). + + Tests with memfs: empty root, one valid pair, multiple pairs, + half-valid subdir (just .md), unrelated files mixed in, missing + root. + status: + implement: open + test: open + commit: open + + - id: agent-harness-extract-schema + title: Extract `export const schema` initializer from .ajs + prompt: | + Extract the schema descriptor declared in a .ajs file's + `export const schema = ...` initializer. Use a sandboxed evaluation + with only the `schema` host module bound and a tight budget. + + Files to create: + - packages/agent-harness/src/loader/extract-schema.ts + - packages/agent-harness/src/loader/extract-schema.test.ts + + Files to change: + - packages/agent-harness/src/index.ts — re-export + `extractSchema`. + + Signature: + function extractSchema( + ajsSource: string, + ajsPath: string + ): Promise; + + Behavior: + - Parse the .ajs into a Module AST (use agent-script's parse). + - Use `findExportedConstInitializer(module, "schema")`. If + undefined, return undefined. + - Synthesize a minimal source string of the form + `import { S } from "schema"; return ;` using the + original initializer's source span. Run it through + agent-script's `run()` with only `makeSchemaModule()` bound + and a small budget. + - On runtime error, throw with a message that points at + ajsPath and explains the schema initializer must be pure + (only `schema` module imports allowed). + - Return the awaited descriptor. + + Tests: + - Returns undefined when the script has no export const schema. + - Returns the correct descriptor for a simple S.Object schema. + - Returns the correct descriptor for a nested schema using + S.Optional, S.Enum, S.Array. + - Throws with a clear message when the initializer references + an identifier other than `S` or attempts an `import { ... } + from "agent"`. + - Tight budget rejects non-terminating initializers. + status: + implement: open + test: open + commit: open + + - id: agent-harness-validate-frontmatter + title: Validate .md frontmatter against a SchemaDescriptor + prompt: | + Wrap toolcraft-schema's `validate()` with friendlier error + formatting suited to surfacing validation issues in CLI output. + + Files to create: + - packages/agent-harness/src/loader/validate.ts + - packages/agent-harness/src/loader/validate.test.ts + + Files to change: + - packages/agent-harness/src/index.ts — re-export + `validateFrontmatter`, `FrontmatterValidationError`. + + Signature: + function validateFrontmatter( + schema: SchemaDescriptor, + frontmatter: Record, + mdPath: string + ): Record; // typed to Static + // when the caller has the type + + Behavior: + - Call toolcraft-schema's `validate(schema, frontmatter)`. + - On ok:true return `value` (with defaults applied). + - On ok:false throw a `FrontmatterValidationError` whose message + lists each issue as `: : ` on + its own line. Include the original issues array as an + `issues` property on the error. + + Tests cover ok path with defaults, single-issue rejection, + multi-issue rejection, empty frontmatter against a schema with + required fields. memfs only if you read the .md; this function + itself takes a parsed object, no fs needed. + status: + implement: open + test: open + commit: open + + - id: agent-harness-run + title: Implement runHarnessPair end-to-end + prompt: | + Public entry point that runs a harness pair: lock, read both + files, split frontmatter, extract schema, validate frontmatter, + execute the .ajs with import.meta + entryPointArgs wired. + + Files to create: + - packages/agent-harness/src/loader/run.ts + - packages/agent-harness/src/loader/run.test.ts + + Files to change: + - packages/agent-harness/src/index.ts — re-export + `runHarnessPair`, `RunHarnessPairOptions`, + `HarnessImportMeta`. + + Signatures: + type HarnessImportMeta = { + kind: string | undefined; + version: number | undefined; + filename: string; + dirname: string; + body: string; + }; + type RunHarnessPairOptions = { + modulesFor: ( + frontmatter: Record, + meta: HarnessImportMeta + ) => ModuleRegistry; + signal?: AbortSignal; + snapshotPath?: string; + }; + function runHarnessPair( + mdPath: string, + options: RunHarnessPairOptions + ): Promise; + + Wiring: + - Resolve pair via resolvePair. + - Acquire the workflow lock via @poe-code/agent-harness-tools' + `lockWorkflow(mdPath)`. Release on completion or error. + - Read .ajs and .md sources. + - Split .md frontmatter + body using agent-script's + `splitFrontmatter`. + - Lint the .ajs with `allowedExportNames: ["schema"]`. Throw + on errors. + - Extract schema. If present, validateFrontmatter; otherwise + pass raw frontmatter through. + - Build `meta: HarnessImportMeta = { kind: validated.kind, + version: validated.version, filename: mdPath, + dirname: dirname(mdPath), body }`. + - Build modules via `options.modulesFor(validated, meta)`, + plus `schema: makeSchemaModule()` (in case the entry needs + it — keep it available). + - Call agent-script's `run(ajsSource, { modules, importMeta: + meta, entryPointArgs: [validated], signal: options.signal, + snapshotPath: options.snapshotPath })`. + - Default snapshotPath when not provided: under the runner's + run-log dir from `resolveRunLogDir({ planPath: mdPath, + runner: "harness", homeDir: os.homedir() })`. + + Tests with memfs: + - happy path: validates frontmatter, invokes default export + with the validated value, returns its result. + - missing schema: passes raw frontmatter through. + - failing validation: throws with mdPath + field path; lock + released; snapshot file not touched. + - missing default export: lint error from the inner lint pass. + - top-level `return` in .ajs: lint warning only, run still + succeeds. + - resume: with a snapshotPath pointing to a snapshot from a + previous aborted run, the entry resumes from the next host + call. Build this by aborting via signal mid-run, then + re-invoking with the same path. + - concurrent run: second invocation against same .md while the + first holds the lock errors with EEXIST. + status: + implement: open + test: open + commit: open + + - id: agent-harness-templates + title: Ship four demo template pairs + prompt: | + Ship four demo harness pairs as built-in templates. Each pair is + one `.ajs` orchestrator + one `.md` plan with default frontmatter. + Names use `*-demo` suffix to keep `kind` values and `$schema` + URLs distinct from the existing experiment / ralph / pipeline / + superintendent runners (which are not touched by this work). + + Files to create: + - packages/agent-harness/src/templates/ralph-demo/ralph-demo.ajs + - packages/agent-harness/src/templates/ralph-demo/ralph-demo.md + - packages/agent-harness/src/templates/experiment-demo/experiment-demo.ajs + - packages/agent-harness/src/templates/experiment-demo/experiment-demo.md + - packages/agent-harness/src/templates/pipeline-demo/pipeline-demo.ajs + - packages/agent-harness/src/templates/pipeline-demo/pipeline-demo.md + - packages/agent-harness/src/templates/superintendent-demo/superintendent-demo.ajs + - packages/agent-harness/src/templates/superintendent-demo/superintendent-demo.md + - packages/agent-harness/src/templates/index.ts — exports + `listBuiltinTemplates()` returning the four pairs with + kind + paths. + - packages/agent-harness/src/templates/index.test.ts — fixture + tests that for each template: lints clean with + allowedExportNames: ["schema"]; the schema initializer + extracts; the default `.md` frontmatter validates against + the extracted schema; running with a stub `agent` module + completes and returns a non-error result. + + Each `.ajs` uses: + import { S } from "schema"; + import { spawn } from "agent"; + // optional: import { event } from "log"; + export const schema = S.Object({ ... }); + export default async (frontmatter) => { ... }; + + No top-level `return`. No manual signal / abort handling. Use + `import.meta` for `kind`, `filename`, `dirname`, `body`. Inside + each entry, drive the loop using the existing + packages/agent-script/examples/{experiment,pipeline,superintendent}.md + bodies as design references for what each demo should *do*, not + as imports. + + Files to change: + - packages/agent-harness/src/index.ts — re-export + `listBuiltinTemplates`. + status: + implement: open + test: open + commit: open + + - id: agent-harness-codegen + title: Codegen *.schema.json from agent-harness templates + prompt: | + Walk the built-in template directory, statically extract each + template's `export const schema`, run it through + `toolcraft-schema`'s `toJsonSchema`, and emit + `docs/schemas/harnesses/.schema.json`. Wire the script + into `npm run build` *alongside* the existing + `codegen:plan-schemas` — do not modify, replace, or remove + `codegen:plan-schemas` or any file under `docs/schemas/plans/`. + + Files to create: + - packages/agent-harness/src/codegen/emit-schemas.ts + - packages/agent-harness/src/codegen/emit-schemas.test.ts + - scripts/generate-harness-schemas.ts — one-line wrapper that + calls the package entry. + - docs/schemas/harnesses/.gitkeep — placeholder so the empty + directory is tracked. + + Files to change: + - package.json — add `"codegen:harness-schemas": + "tsx scripts/generate-harness-schemas.ts"` to scripts; append + it to the `build` chain right after `codegen:plan-schemas`. + Use deep-merge / parse — do not regex over package.json (per + CLAUDE.md). + - packages/agent-harness/src/index.ts — re-export + `runHarnessCodegen` (the package-level entrypoint). + + Signature of the package entry: + function runHarnessCodegen(options?: { + fs?: { mkdir; writeFile }; + repoRoot?: string; + }): Promise; + + Output format mirrors scripts/generate-plan-schemas.ts: sorted + JSON keys, $id pointing at the public docs URL + `https://poe-platform.github.io/poe-code/schemas/harnesses/.schema.json`, + $schema set to draft 2020-12. + + Tests use memfs to assert the four expected files are written + with the expected $id and a stable key order. Do not write to + the real filesystem. + status: + implement: open + test: open + commit: open + + - id: agent-harness-cli + title: Add `poe-code harness {run,new,list}` CLI command + prompt: | + Register a new top-level command `harness` exposing three + subcommands: `run`, `new`, `list`. Implement using the project's + design-system primitives — do not import @clack/prompts or chalk + directly (CLAUDE.md). Per CLAUDE.md, every CLI option must also + be accepted as an arg so the command is usable in CI; defaults + are accepted only with `--yes`. + + Files to create: + - src/cli/commands/harness.ts + - src/cli/commands/harness-command.test.ts + + Files to change: + - src/cli/index.ts (or wherever commands register) — register + the new `harness` command. Do not edit registrations for + `experiment`, `ralph`, `pipeline`, or `superintendent`. + + Subcommand behavior: + - `poe-code harness run [] [--yes]`: if md-path given, + run that pair via runHarnessPair. If omitted, discover + harnesses from `.poe-code/harnesses/` (project) then + `~/.poe-code/harnesses/` (user); 0 → error, 1 → run it, + >1 → interactive select (or fail with "ambiguous, pass a + path" under --yes). + - `poe-code harness new [--dir ] + [--yes]`: scaffold a new pair from a built-in template under + `--dir` (defaults to `.poe-code/harnesses//`). + Refuse to overwrite existing files. + - `poe-code harness list`: print discovered pairs as a table + (basename, dir, .md mtime). + + Tests: + - Unit tests via the existing CLI test harness (mock fs, mock + spawn). Cover: run with explicit path, run with discovery, + new with missing template, new refusing to overwrite, list + empty / list multiple. + - After implementation, run a screenshot validation per + CLAUDE.md: `npm run screenshot-poe-code -- harness --help` + and one of `harness list` against a fixture directory, to + verify the visual surface is consistent with other commands. + Do not commit screenshot tests; screenshots are for ad-hoc + validation only. + status: + implement: open + test: open + commit: open +--- -A harness is a pair of files with the same basename, in the same directory: +# Context -```text -.poe-code/harnesses/ralph/ - ralph.ajs # orchestrator - ralph.md # plan / prompt / frontmatter (the document being run) -``` +`@poe-code/agent-harness` is a new experimental package that runs **harness pairs**: a `.ajs` orchestrator paired with a sibling `.md` plan. The orchestrator is agent-script source; the markdown carries YAML frontmatter (validated against a schema declared inside the `.ajs`) and a body the orchestrator can use as a prompt. This is a parallel track — the existing `experiment-loop` / `ralph` / `pipeline` / `superintendent` packages and their CLI commands are **not** modified, replaced, or migrated. Parity is a future plan. -### The `.ajs` orchestrator - -ESM-shaped. One required default export (the entry), one optional named export (the frontmatter schema). No top-level `return`. No manual cancellation handling — the interpreter aborts between host calls, the snapshot scheduler persists progress, `restore()` resumes. +## Canonical .ajs shape ```js import { S } from "schema"; @@ -49,201 +714,72 @@ import { event } from "log"; export const schema = S.Object({ iterations: S.Optional(S.Number({ minimum: 1, default: 3 })), agent: S.Optional(S.String({ default: "claude-code" })), - status: S.Object({ - state: S.Enum(["open", "in_progress", "completed", "failed"] as const), - iteration: S.Number({ minimum: 0 }), - }), }); export default async (frontmatter) => { const { kind, filename, body } = import.meta; - - for (let i = frontmatter.status.iteration; i < frontmatter.iterations; i++) { + for (let i = 0; i < frontmatter.iterations; i++) { const r = await spawn({ agent: frontmatter.agent, prompt: body }); event("iteration.completed", { kind, file: filename, i, summary: r.summary }); } }; ``` -Contract: - -- `export default` — required, must be an async arrow. Receives the validated frontmatter as its single argument. Its return value is the harness result. -- `export const schema` — optional. If present, the loader evaluates it against `toolcraft-schema` builders and validates the `.md` frontmatter before invoking the entry. If absent, the entry receives the raw frontmatter map. -- `import.meta` — exposes `{ kind, version, filename, dirname, body }` of the **paired `.md`**, matching Node's ESM `import.meta` extensions. `body` is the markdown content below the YAML header. - -### The `.md` plan - -Plain markdown with YAML frontmatter. The frontmatter conforms to whatever `export const schema` declares; the body is free-form prose the orchestrator can use as the prompt. - -```markdown ---- -$schema: https://poe-platform.github.io/poe-code/schemas/harnesses/ralph.schema.json -kind: ralph -version: 1 -agent: claude-code -iterations: 3 -status: - state: open - iteration: 0 ---- -# Refactor the auth module - -Split the monolithic auth.ts into separate files for session management, -token validation, and middleware. Keep all existing tests passing. -``` - -### CLI - -```bash -# run a harness pair -poe-code harness run .poe-code/harnesses/ralph/ralph.md - -# discover-and-run from .poe-code/harnesses/ -poe-code harness run - -# scaffold a new harness pair -poe-code harness new my-loop - -# list installed harnesses -poe-code harness list -``` +Rules: -The runner pairs `.md` ↔ `.ajs` by basename in the same directory, lints the `.ajs`, validates the `.md` frontmatter against the extracted schema, then executes the entry. +- **`export default`** — required. Async arrow only. Receives the validated frontmatter as its single argument. Its return value is the harness result. +- **`export const schema`** — optional. If present, the loader evaluates it in a sandboxed pre-pass with only the `schema` host module bound, then validates the `.md` frontmatter against it. +- **`import.meta`** — exposes `{ kind, version, filename, dirname, body }` of the **paired `.md`** (mirroring Node's ESM extensions; `body` is harness-specific). +- **No top-level `return`** in the new shape. **No manual signal / abort handling** — the agent-script interpreter aborts between host calls automatically; the snapshot scheduler persists progress; `restore()` resumes. -### Built-in templates +## Subset extensions to agent-script -`@poe-code/agent-harness` ships templates that `harness new ` scaffolds. They are demonstrations of the pair model on familiar shapes — they are **not** wired to or invoked from the existing `experiment run` / `ralph run` / `pipeline run` / `superintendent run` commands. The existing runners stay exactly as they are; parity with them is a future goal, out of scope for this work. +Three additions, top-level only: -- `ralph-demo` — iterative single-agent loop -- `experiment-demo` — measure, mutate, keep-or-revert via git -- `pipeline-demo` — sequenced tasks with builder/reviewer roles -- `superintendent-demo` — builder + parallel inspectors + judge + owner +- `ExportNamedDeclaration` — `export const NAME = expr;` (single declarator, allowlist-controlled name). +- `ExportDefaultDeclaration` — `export default expr;` (must be an arrow expression, exactly one per file). +- `MetaProperty` for `import.meta` — sandbox value injected via a new `RunOptions.importMeta`. Cannot be assigned to. -Each is one `.ajs` + one `.md`. Demo names are intentionally distinct from the existing `kind` values to avoid `$schema` URL collisions and to make the experimental status legible. +`run()` gains `entryPointArgs?: readonly unknown[]` — when set, the runtime invokes the resolved default export with these args after evaluating the module top-level, and that result becomes `returnValue`. -## 3. Implementation details and technical decisions - -### Package layout - -New package `@poe-code/agent-harness` at `packages/agent-harness/`. Owns the loader, the discovery / pairing logic, the per-harness templates, and the codegen entry point. Depends on `@poe-code/agent-script`, `@poe-code/agent-harness-tools`, `@poe-code/toolcraft-schema`. - -```text -packages/agent-harness/ - src/ - loader/ # paired-file loader: discover, pair, validate, run - pair.ts # resolve .ajs ↔ .md - extract-schema.ts # AST-level pull of `export const schema` initializer - validate.ts # toolcraft-schema validator over frontmatter - run.ts # public runHarnessPair() - modules/ - schema.ts # makeSchemaModule(): exposes toolcraft-schema `S` to .ajs - codegen/ - emit-schemas.ts # walks installed templates, emits docs/schemas/harnesses/*.json - templates/ - ralph/{ralph.ajs,ralph.md} - experiment/{experiment.ajs,experiment.md} - pipeline/{pipeline.ajs,pipeline.md} - superintendent/{superintendent.ajs,superintendent.md} - cli/ # `poe-code harness {run,new,list}` command bodies - index.ts -``` - -### Subset extensions to agent-script - -Three additions, all gated to top-level use only. - -1. **`ExportNamedDeclaration`** — `export const NAME = expr;`. Limited to a single declarator. Allowlist of names is configured per-host: agent-harness allows `schema`. Anything else is `AS-EXPORT-UNKNOWN`. Keeps the surface narrow; nothing else can be exported. -2. **`ExportDefaultDeclaration`** — `export default expr;`. Initializer must be an arrow function expression (sync or async). Exactly one per file. Lint code `AS-EXPORT-DEFAULT-MISSING` / `AS-EXPORT-DEFAULT-MULTIPLE` / `AS-EXPORT-DEFAULT-NOT-ARROW`. -3. **`MetaProperty` for `import.meta`** — recognized as an expression. Resolves at runtime to a host-injected sandbox object. Cannot be assigned to (`import.meta.x = ...` is a lint error). - -Top-level `return` becomes a lint warning in `.ajs` files paired with markdown (`AS-RETURN-AT-TOP`); the new shape uses the default export's return value. - -Existing single-file harness markdowns (`packages/agent-script/examples/*.md`) keep working — the legacy top-level-return path stays. The new package only consumes the new shape. - -### `schema` host module - -```ts -// packages/agent-harness/src/modules/schema.ts -import { S } from "@poe-code/toolcraft-schema"; - -export function makeSchemaModule(): { S: typeof S } { - return { S }; -} -``` - -Registered as `schema` for both lint and execution. The builders are pure — no IO, no host bridge needed. This lets the loader run the schema initializer in the standard interpreter without special-casing pure evaluation. - -### Two-pass loader +## Two-pass loader ```ts -async function runHarnessPair(mdPath: string, options: RunHarnessPairOptions): Promise { - const ajsPath = await resolvePair(mdPath); // .md ↔ .ajs - const ajsSource = await readFile(ajsPath, "utf8"); - const { frontmatter, body } = splitFrontmatter(await readFile(mdPath, "utf8")); - - // Pass 1: lint, then evaluate just `export const schema` if present - const ast = parse(ajsSource, ajsPath); - lint(ajsSource, { filename: ajsPath, modules: lintModulesFor(options) }); - const schemaInit = findExportedConstInitializer(ast, "schema"); - const schema = schemaInit - ? await evaluateSchemaInitializer(schemaInit, { schemaModule: makeSchemaModule() }) - : undefined; - - // Validate frontmatter (no-op if no schema) - const validated = schema ? validate(schema, frontmatter) : frontmatter; - - // Pass 2: full execution; default export receives validated frontmatter - return run(ajsSource, { - modules: options.modulesFor(validated, { kind: validated.kind, version: validated.version, filepath: mdPath, body }), - importMeta: { kind: validated.kind, version: validated.version, filename: mdPath, dirname: path.dirname(mdPath), body }, - entryPointArgs: [validated], - signal: options.signal, - snapshotPath: options.snapshotPath, - }); +async function runHarnessPair(mdPath, options) { + // pair, lock, read both files + // pass 1: lint + extract `export const schema` initializer + sandboxed eval + // validate .md frontmatter against the schema (pass-through if absent) + // pass 2: agent-script run() with importMeta + entryPointArgs } ``` -`run()` gets two new options — `importMeta` (object injected as `import.meta`) and `entryPointArgs` (forwarded to the resolved default export). When `entryPointArgs` is set, the runtime treats the resolved default export as the entry instead of expecting a top-level returned value. - -`evaluateSchemaInitializer` reuses the existing interpreter with a stripped-down module registry (only `schema`) and a tight budget. Initializer that calls anything not exported by `schema` is a lint error before this step. - -### Runtime validator on toolcraft-schema - -`@poe-code/toolcraft-schema` gains `validate(schema, value)` returning `{ ok: true, value } | { ok: false, errors: ValidationError[] }`. Walks the descriptor mirror of `toJsonSchema`. Zero-dep, no ajv. Errors carry `path` (dotted), `expected`, `received`. Validation failure surfaces to the user with the `.md` filepath and the offending field path. - -### Codegen +The schema is extracted with `findExportedConstInitializer` and evaluated through agent-script's `run()` with only `makeSchemaModule()` bound and a tight budget. The schema initializer that imports anything other than `schema` is rejected at lint time. -A new script walks `packages/agent-harness/src/templates/*/`, statically loads each `.ajs`'s `export const schema`, and emits `docs/schemas/harnesses/.schema.json` via `toJsonSchema(schema)`. Wired in as `npm run codegen:harness-schemas` and added to `npm run build` **alongside** the existing `codegen:plan-schemas` — neither replaces the other. Output path `docs/schemas/harnesses/` is new, so there's no overlap with `docs/schemas/plans/*.schema.json`. +## Cross-cutting concerns reuse `@poe-code/agent-harness-tools` -### Locks, run logs, snapshots +- **Lock**: `lockWorkflow(mdPath)` before pass 1; release on completion or error. +- **Run logs**: `resolveRunLogDir({ planPath: mdPath, runner: "harness", homeDir })` for log directory. +- **Snapshot**: written under the run-log dir; agent-script's existing `restore()` validates source-hash match before resuming. -All cross-cutting concerns reuse `@poe-code/agent-harness-tools`: +## Codegen -- **Lock**: `lockWorkflow(mdPath)` before pass 1; release on completion or error. Existing `.lock` file convention. -- **Run logs**: `resolveRunLogDir({ planPath: mdPath, runner: "harness", homeDir })`. Each `event(...)` call from the orchestrator is appended as JSONL. -- **Snapshot**: `snapshotPath = resolveRunLogDir(...) + "/snapshot.json"`. Passed straight to `agent-script`'s `run({ snapshotPath, snapshotIntervalMs })`. On rerun, the loader reads it and passes it to `run({ snapshot })` — agent-script's existing `restore()` validates source-hash match before resuming. +`codegen:harness-schemas` walks `packages/agent-harness/src/templates/*/`, statically loads each `.ajs`'s `export const schema`, and emits `docs/schemas/harnesses/.schema.json` via `toJsonSchema(schema)`. Added to the `build` chain **alongside** the existing `codegen:plan-schemas`. Output path is new — there is no overlap with `docs/schemas/plans/*.schema.json`. -### Relationship to existing packages +## Edge cases -Out of scope. `experiment-loop`, `ralph`, `pipeline`, `superintendent` are not touched. Their bespoke runtimes, frontmatter parsers, JsonSchema literals, CLI commands, dashboards, and emitted `docs/schemas/plans/*.schema.json` files remain exactly as they are. `agent-harness` is a parallel experimental track. If/when parity is reached and we decide to converge, that's a separate plan. +- No `export const schema` → frontmatter passes through raw to the entry. Allowed. +- Missing pair (.md without .ajs or vice versa) → hard error. +- Schema initializer references non-`schema` module → lint error before evaluation. +- Default export not an arrow → lint error. +- Frontmatter fails validation → runner exits non-zero with mdPath + dotted field path; snapshot untouched. +- Source hash drift on resume → existing `restore()` rejects the snapshot, run starts fresh. +- Concurrent runs against same `.md` → second errors with `EEXIST`. +- `import.meta` aliasing (`const m = import.meta`) → supported; member access works because MetaProperty resolves to a sandbox object. -### Edge cases - -- **No `export const schema`** — frontmatter passes through to the entry as the raw parsed YAML (untyped). Allowed; useful for trivial harnesses. -- **No `.md` paired** — hard error. Every `.ajs` requires a `.md`. -- **No `.ajs` paired** — hard error. Every `.md` discovered as a harness target requires a sibling `.ajs`. -- **Schema initializer references a non-pure value** — caught by lint. `schema` module is the only allowed import inside the initializer. -- **Default export is not an arrow** — lint error. Arrow + async arrow only. -- **Frontmatter fails validation** — runner exits non-zero with a message naming the `.md` path and the failing field. Snapshot is not touched. -- **Source hash drift on resume** — existing `restore()` behavior: the snapshot is rejected, the run starts fresh. -- **Concurrent runs against the same `.md`** — `lockWorkflow` rejects the second one with `EEXIST`. -- **Top-level `import.meta` aliasing (`const m = import.meta`)** — supported. Subsequent `m.body` works because `MetaProperty` resolves to a sandbox object with normal property access. - -## 4. Interfaces and test plan - -### Public API of `@poe-code/agent-harness` +## Public API surface ```ts +// @poe-code/agent-harness export type HarnessImportMeta = { kind: string | undefined; version: number | undefined; @@ -251,240 +787,35 @@ export type HarnessImportMeta = { dirname: string; body: string; }; - -export type HarnessPair = { - ajsPath: string; - mdPath: string; - basename: string; -}; - +export type HarnessPair = { ajsPath: string; mdPath: string; basename: string }; export type RunHarnessPairOptions = { - modulesFor: ( - frontmatter: Record, - meta: HarnessImportMeta - ) => ModuleRegistry; + modulesFor: (frontmatter: Record, meta: HarnessImportMeta) => ModuleRegistry; signal?: AbortSignal; snapshotPath?: string; }; - -export function resolvePair(mdPath: string): Promise; -export function discoverHarnesses(rootDir: string): Promise; -export function runHarnessPair( - mdPath: string, - options: RunHarnessPairOptions -): Promise; - +export function resolvePair(inputPath: string, fs?: HarnessFs): Promise; +export function discoverHarnesses(rootDir: string, fs?: HarnessFs): Promise; +export function extractSchema(ajsSource: string, ajsPath: string): Promise; +export function validateFrontmatter(schema: SchemaDescriptor, frontmatter: Record, mdPath: string): Record; +export function runHarnessPair(mdPath: string, options: RunHarnessPairOptions): Promise; +export function makeSchemaModule(): { S: typeof S }; export function listBuiltinTemplates(): readonly { kind: string; ajsPath: string; mdPath: string }[]; -export function scaffoldFromTemplate( - kind: string, - destination: { dir: string; basename: string } -): Promise; -``` +export function runHarnessCodegen(options?: { fs?: { mkdir; writeFile }; repoRoot?: string }): Promise; -### New surface on `@poe-code/agent-script` - -```ts -// run.ts — additions to RunOptions -export type RunOptions = { - // ...existing fields - importMeta?: Record; - entryPointArgs?: readonly unknown[]; -}; +// @poe-code/agent-script — additions +export type RunOptions = { /* existing */ importMeta?: Record; entryPointArgs?: readonly unknown[] }; +export type ExportNamedDeclaration; ExportDefaultDeclaration; MetaProperty; +export function findExportedConstInitializer(module: Module, name: string): Expression | undefined; -// parser AST additions -export type ExportNamedDeclaration = BaseNode & { - type: "ExportNamedDeclaration"; - declaration: VariableDeclaration; // const only, single declarator -}; -export type ExportDefaultDeclaration = BaseNode & { - type: "ExportDefaultDeclaration"; - declaration: ArrowFunctionExpression; -}; -export type MetaProperty = BaseNode & { - type: "MetaProperty"; - meta: Identifier; // "import" - property: Identifier; // "meta" -}; - -// new public helper -export function findExportedConstInitializer( - module: Module, - name: string -): Expression | undefined; +// @poe-code/toolcraft-schema — additions +export type ValidationIssue = { path: readonly string[]; expected: string; received: string; message: string }; +export type ValidationResult = { ok: true; value: T } | { ok: false; issues: readonly ValidationIssue[] }; +export function validate(schema: S, value: unknown): ValidationResult>; ``` -### New surface on `@poe-code/toolcraft-schema` - -```ts -export type ValidationIssue = { - path: readonly string[]; - expected: string; - received: string; - message: string; -}; -export type ValidationResult = - | { ok: true; value: T } - | { ok: false; issues: readonly ValidationIssue[] }; - -export function validate( - schema: S, - value: unknown -): ValidationResult>; -``` - -### Test plan - -#### `@poe-code/toolcraft-schema` - -- Unit: `validate()` accepts every `S.*` builder, surfaces typed issues, applies `default` for missing optionals, rejects unknown properties on `S.Object` (matching emitted `additionalProperties: false`). -- Snapshot: `toJsonSchema(schema)` output for each builder remains stable. - -#### `@poe-code/agent-script` - -- Parser: `export const x = …`, `export default async () => {}`, `import.meta`, `import.meta.X`. Reject `export function`, `export class`, `export *`, multiple `export default`, top-level `import.meta = …`. -- Linter: only `schema` is allowlisted as a named export (configurable per registry via lint options); unknown export names emit `AS-EXPORT-UNKNOWN`. `AS-RETURN-AT-TOP` warns when `.ajs` has both top-level `return` and `export default`. -- Runtime: `run({ importMeta, entryPointArgs })` resolves the default export and invokes it with `entryPointArgs`. Cancellation between host calls inside the entry still throws `SandboxError("aborted")`. Snapshot/restore round-trip works across an aborted entry call. - -#### `@poe-code/agent-harness` - -- `resolvePair`: pairs by basename in same dir, surfaces `MissingPair` errors, ignores non-`.md`/`.ajs` siblings. -- `discoverHarnesses`: walks `.poe-code/harnesses/` and `/.poe-code/harnesses/`, returns deduped list (project beats user). -- `extractSchema`: returns `undefined` when absent, returns evaluated descriptor when present, errors when initializer references non-`schema` modules. -- `runHarnessPair`: - - happy path: validates frontmatter, invokes default export, returns its result. - - missing schema: passes raw frontmatter through. - - failing validation: rejects with named field path, leaves snapshot untouched, releases lock. - - missing default export: lint error before run. - - top-level `return` in `.ajs`: lint warning, run still proceeds. - - resume: on a second invocation with a snapshot, the entry resumes from the next host call. -- Lock: second concurrent run against same `.md` errors with `EEXIST`. -- All filesystem state through `memfs` per CLAUDE.md. - -#### Integration - -- Run each shipped demo template end-to-end with a stub `agent` module. Assert: result, journal entries, snapshot file exists and parses. -- CLI: `poe-code harness run ` happy path, `harness new `, `harness list`. Use `npm run dev -- harness ...` for spot tests; rely on screenshot tests for visual UI surfaces. -- Confirm the existing `experiment run` / `ralph run` / `pipeline run` / `superintendent run` test suites still pass unchanged — proving the new package doesn't touch them. - -### Autonomy checklist - -What an agent needs to build the package end-to-end without coming back: - -- This document for level 1–5 context. -- Existing `agent-script` parser/lint/run code as the reference for adding `Export*` and `MetaProperty` AST nodes. -- Existing `toolcraft-schema` builders and `toJsonSchema` as the reference for `validate`. -- Existing `agent-harness-tools` (lock, run-logs, paths) — used as-is. -- Existing per-package frontmatter files as **inspiration only** for what a demo template might cover. The agent-harness package does not import from, modify, or replace those packages. -- `scripts/generate-plan-schemas.ts` as a structural reference for the new `scripts/generate-harness-schemas.ts`. The original is left untouched. - -### Rollout - -1. Land subset extensions (`Export*`, `MetaProperty`) + `toolcraft-schema` validator. No consumers yet, green build. -2. Land `agent-harness` package with templates, codegen, and the `harness` command marked experimental. The four existing runners keep working unchanged. -3. Stop here. Parity with the existing runners is a separate, future plan. - -## 5. Code plan - -Build order keeps the branch green at every step. Each step is one PR. - -### Step 1 — `toolcraft-schema` validator - -Files to create: - -- `packages/toolcraft-schema/src/validate.ts` -- `packages/toolcraft-schema/src/validate.test.ts` - -Files to change: - -- `packages/toolcraft-schema/src/index.ts` — re-export `validate`, `ValidationIssue`, `ValidationResult`. - -Signatures: - -- `function validate(schema: S, value: unknown): ValidationResult>` -- internal: `function walk(schema: SchemaDescriptor, value: unknown, path: readonly string[], issues: ValidationIssue[]): unknown` - -### Step 2 — agent-script subset extensions - -Files to create: - -- `packages/agent-script/src/parse/parse-export.ts` -- `packages/agent-script/src/parse/parse-import-meta.ts` -- `packages/agent-script/src/loader/find-exported.ts` -- `packages/agent-script/src/loader/find-exported.test.ts` - -Files to change: - -- `packages/agent-script/src/parse/parser.ts` — add `ExportNamedDeclaration`, `ExportDefaultDeclaration`, `MetaProperty` to `Statement`/`Expression` unions; wire token-level entrypoints. -- `packages/agent-script/src/lint.ts` — add `AS-EXPORT-UNKNOWN`, `AS-EXPORT-DEFAULT-MISSING`, `AS-EXPORT-DEFAULT-MULTIPLE`, `AS-EXPORT-DEFAULT-NOT-ARROW`, `AS-RETURN-AT-TOP`, `AS-IMPORT-META-ASSIGN`. Accept `allowedExportNames` in `LintOptions`. -- `packages/agent-script/src/run.ts` — add `importMeta?` and `entryPointArgs?` to `RunOptions`. When `entryPointArgs` is set, after evaluating the module, look up the default export binding and call it with the args; the result becomes `returnValue`. -- `packages/agent-script/src/interp/scope.ts` — bind `import.meta` resolution to the runtime-injected value. -- `packages/agent-script/src/index.ts` — export `findExportedConstInitializer`, the new AST types. - -Signatures: - -- `function findExportedConstInitializer(module: Module, name: string): Expression | undefined` - -### Step 3 — `agent-harness` package skeleton - -Files to create: - -- `packages/agent-harness/package.json` -- `packages/agent-harness/README.md` -- `packages/agent-harness/tsconfig.json` -- `packages/agent-harness/src/index.ts` -- `packages/agent-harness/src/loader/pair.ts` -- `packages/agent-harness/src/loader/pair.test.ts` -- `packages/agent-harness/src/loader/extract-schema.ts` -- `packages/agent-harness/src/loader/extract-schema.test.ts` -- `packages/agent-harness/src/loader/validate.ts` -- `packages/agent-harness/src/loader/validate.test.ts` -- `packages/agent-harness/src/loader/run.ts` -- `packages/agent-harness/src/loader/run.test.ts` -- `packages/agent-harness/src/modules/schema.ts` -- `packages/agent-harness/src/modules/schema.test.ts` -- `packages/agent-harness/src/discovery/discover.ts` -- `packages/agent-harness/src/discovery/discover.test.ts` -- `packages/agent-harness/src/templates/index.ts` - -Signatures: - -- `function resolvePair(mdPath: string, fs?: HarnessFs): Promise` -- `function discoverHarnesses(rootDir: string, fs?: HarnessFs): Promise` -- `function extractSchema(ajsSource: string, ajsPath: string): Promise` -- `function validateFrontmatter(schema: SchemaDescriptor, frontmatter: Record): Record` (throws with named field path on failure) -- `function runHarnessPair(mdPath: string, options: RunHarnessPairOptions): Promise` -- `function makeSchemaModule(): { S: typeof S }` - -### Step 4 — built-in demo templates - -Files to create: - -- `packages/agent-harness/src/templates/ralph-demo/ralph-demo.ajs` -- `packages/agent-harness/src/templates/ralph-demo/ralph-demo.md` -- `packages/agent-harness/src/templates/experiment-demo/experiment-demo.ajs` -- `packages/agent-harness/src/templates/experiment-demo/experiment-demo.md` -- `packages/agent-harness/src/templates/pipeline-demo/pipeline-demo.ajs` -- `packages/agent-harness/src/templates/pipeline-demo/pipeline-demo.md` -- `packages/agent-harness/src/templates/superintendent-demo/superintendent-demo.ajs` -- `packages/agent-harness/src/templates/superintendent-demo/superintendent-demo.md` -- `packages/agent-harness/src/templates/index.test.ts` — fixture tests that each template lints, frontmatter validates, runs against stub modules. - -Each `.ajs` declares `export const schema = S.Object({...})` and `export default async (frontmatter) => {...}`. Names are `*-demo` to make experimental status legible and to keep `$schema` URLs separate from the existing runners' schemas. - -### Step 5 — codegen + CLI - -Files to create: - -- `packages/agent-harness/src/codegen/emit-schemas.ts` -- `packages/agent-harness/src/codegen/emit-schemas.test.ts` -- `scripts/generate-harness-schemas.ts` — one-line wrapper over the codegen entry. -- `src/cli/commands/harness.ts` -- `src/cli/commands/harness-command.test.ts` -- `docs/schemas/harnesses/.gitkeep` — emitted output lives here. - -Files to change: - -- `package.json` — add `codegen:harness-schemas` script; add it to the `build` chain alongside the existing `codegen:plan-schemas` (do not remove or modify `codegen:plan-schemas`). -- `src/cli/index.ts` (or wherever commands register) — register the new `harness` command. No edits to existing `experiment` / `ralph` / `pipeline` / `superintendent` command registrations. +## Out of scope -That's the full scope of this plan. `experiment-loop`, `ralph`, `pipeline`, `superintendent`, `scripts/generate-plan-schemas.ts`, and `docs/schemas/plans/*.schema.json` are not touched. +- No changes to `experiment-loop`, `ralph`, `pipeline`, `superintendent` packages. +- No changes to their CLI commands or dashboards. +- No changes to `scripts/generate-plan-schemas.ts` or any file under `docs/schemas/plans/`. +- No deletion of `packages/agent-script/examples/*.md` legacy single-file harnesses. diff --git a/docs/plans/e2b-integration.md b/docs/plans/e2b-integration.md index 52e75cbe08..ab47b33e02 100644 --- a/docs/plans/e2b-integration.md +++ b/docs/plans/e2b-integration.md @@ -316,7 +316,7 @@ tasks: status: implement: done test: done - commit: open + commit: done - id: cli-universal-flags title: Add universal --runtime/--detach/--mount-poe-code flags to all four task @@ -343,8 +343,8 @@ tasks: docs/SNAPSHOT_TESTING.md). Take a screenshot of `poe-code spawn --help` via `npm run screenshot-poe-code -- spawn --help` to verify visually. status: - implement: open - test: open + implement: done + test: done commit: open - id: docker-factory-and-build diff --git a/docs/plans/e2b-integration.md.lock b/docs/plans/e2b-integration.md.lock index 6121abbbe5..bea39f3571 100644 --- a/docs/plans/e2b-integration.md.lock +++ b/docs/plans/e2b-integration.md.lock @@ -1 +1 @@ -{"pid":82216,"host":"m5mb-kjopek","acquiredAt":"2026-05-03T23:37:05.950Z"} \ No newline at end of file +{"pid":82216,"host":"m5mb-kjopek","acquiredAt":"2026-05-03T23:54:21.246Z"} \ No newline at end of file diff --git a/packages/agent-harness-tools/src/index.ts b/packages/agent-harness-tools/src/index.ts index c17d786eac..9510f3cc3e 100644 --- a/packages/agent-harness-tools/src/index.ts +++ b/packages/agent-harness-tools/src/index.ts @@ -48,7 +48,11 @@ export { type LogStreamFs } from "./log-stream.js"; export { runPoeCommand } from "./run-poe-command.js"; -export { resolvePoeCommandExecution } from "./poe-command-execution.js"; +export { + applyRuntimeOverrides, + resolvePoeCommandExecution, + type RuntimeOverrideOptions +} from "./poe-command-execution.js"; export { skillPlanConfigSection } from "./skill-config.js"; export * from "./execution-env.js"; export * from "./workspace-transfer.js"; diff --git a/packages/agent-harness-tools/src/poe-command-execution.test.ts b/packages/agent-harness-tools/src/poe-command-execution.test.ts new file mode 100644 index 0000000000..626095056d --- /dev/null +++ b/packages/agent-harness-tools/src/poe-command-execution.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, it } from "vitest"; +import { applyRuntimeOverrides } from "./poe-command-execution.js"; + +describe("runtime command execution overrides", () => { + it("applies CLI/SDK runtime overrides after config resolution", () => { + const resolved = applyRuntimeOverrides( + { + runtime: { + type: "host", + build_args: {}, + mounts: [] + }, + runner: { + detach: false, + upload_max_file_mb: 100, + download_conflict: "refuse", + workspace: { exclude: [".git"] } + } + }, + { + runtime: "docker", + runtimeImage: "poe-code:test", + detach: true, + mountPoeCode: true + }, + "/repo" + ); + + expect(resolved).toEqual({ + runtime: { + type: "docker", + build_args: {}, + mounts: [ + { + source: "/repo", + target: "/usr/local/lib/poe-code", + readonly: true + } + ], + image: "poe-code:test" + }, + runner: { + detach: true, + upload_max_file_mb: 100, + download_conflict: "refuse", + workspace: { exclude: [".git"] } + } + }); + }); +}); diff --git a/packages/agent-harness-tools/src/poe-command-execution.ts b/packages/agent-harness-tools/src/poe-command-execution.ts index 09adf7eaff..57911eb009 100644 --- a/packages/agent-harness-tools/src/poe-command-execution.ts +++ b/packages/agent-harness-tools/src/poe-command-execution.ts @@ -17,11 +17,20 @@ import { } from "@poe-code/poe-code-config"; import { selectExecutionEnv, type OpenSpec } from "./execution-env.js"; +export type RuntimeOverrideOptions = { + runtime?: "host" | "docker" | "e2b"; + runtimeImage?: string; + runtimeTemplate?: string; + detach?: boolean; + mountPoeCode?: boolean; +}; + export function resolvePoeCommandExecution(input: { cwd: string; env: Record; argv: string[]; tool: string; + runtime?: RuntimeOverrideOptions; context?: { homeDir?: string; state?: StateManager; @@ -34,7 +43,7 @@ export function resolvePoeCommandExecution(input: { state: StateManager; } { const homeDir = input.context?.homeDir ?? os.homedir(); - const config = loadRuntimeConfig(input.cwd, homeDir); + const config = applyRuntimeOverrides(loadRuntimeConfig(input.cwd, homeDir), input.runtime, input.cwd); const resolved = resolveRuntime({ cwd: input.cwd, config }); const factory = selectExecutionEnv(resolved.runtime); @@ -57,6 +66,44 @@ export function resolvePoeCommandExecution(input: { }; } +export function applyRuntimeOverrides( + config: ResolvedConfig, + overrides: RuntimeOverrideOptions | undefined, + cwd = process.cwd() +): ResolvedConfig { + if (!overrides) { + return config; + } + + const runtime = parseRuntime({ + ...config.runtime, + ...(overrides.runtime !== undefined ? { type: overrides.runtime } : {}), + ...(overrides.runtimeImage !== undefined ? { image: overrides.runtimeImage } : {}), + ...(overrides.runtimeTemplate !== undefined + ? { template_id: overrides.runtimeTemplate } + : {}), + ...(overrides.mountPoeCode === true + ? { mounts: [...config.runtime.mounts, createPoeCodeMount(cwd)] } + : {}) + }); + + return { + runtime, + runner: { + ...config.runner, + ...(overrides.detach === true ? { detach: true } : {}) + } + }; +} + +function createPoeCodeMount(cwd: string): { source: string; target: string; readonly: boolean } { + return { + source: cwd, + target: "/usr/local/lib/poe-code", + readonly: true + }; +} + function loadRuntimeConfig(cwd: string, homeDir: string): ResolvedConfig { const document = deepMergeDocuments( readConfigDocument(resolveConfigPath(homeDir)), diff --git a/packages/agent-script/README.md b/packages/agent-script/README.md index df925cc29b..084338baee 100644 --- a/packages/agent-script/README.md +++ b/packages/agent-script/README.md @@ -1,278 +1,243 @@ # @poe-code/agent-script -Parse, lint, execute, and checkpoint agent-script programs. +**Run agent orchestration as code, not as a state machine.** -`@poe-code/agent-script` is the small runtime used for harness-style scripts in Poe Code. It gives you: +Agent-script is a tiny, deterministic JavaScript-subset interpreter. You write the orchestration as a regular `async/await` script; the runtime sandboxes it, snapshots it on every yield, and only lets it touch the host through modules you register. -- a parser for the agent-script language subset -- a linter for syntax, module, and safety rules -- a runtime for executing scripts against registered host modules -- snapshot helpers for dump/restore flows -- a file-based harness runner for `.ajs` files and markdown plans +It is the engine behind Poe Code's pipelines, experiment loops, and superintendent runs. -## Overview +## Why use it -Agent-script is a constrained JavaScript-like language designed for deterministic, host-mediated automation. Scripts import named modules that you register from the host, then run inside the subset interpreter. +- **Orchestration as code.** Multi-agent shapes — pipeline, experiment, superintendent, custom — are just JS. No DSL, no JSON state machine, no per-step LLM round trip. +- **Deterministic & sandboxed.** No `eval`, no `new`, no `class`, no `this`, no regex literals, no `function` keyword. Imports are limited to modules you register. Budgets cap steps, depth, deadlines, string and array sizes. +- **Crash-safe long runs.** Every `await` yields a snapshot. The scheduler writes them atomically to disk on an interval. A run can be resumed against the original source — the source hash is verified before restore. +- **File-based plans.** A `.ajs` file or a markdown file with YAML frontmatter and a `js` fenced block is the unit of work. Frontmatter holds the plan; the script walks it. +- **MCP code mode.** Connect to an MCP server once, then call tools imperatively from the script — no LLM in the loop for the orchestration layer. -`runHarness()` is the usual entrypoint for plan-style documents: +## At a glance -- `.ajs` files are treated as raw scripts -- markdown files load YAML frontmatter, then execute the first `js` fenced block -- if a markdown file has no fenced `js` block, the markdown body is treated as the script source +```js +import { spawn } from "agent"; +import { agents, tasks } from "harness"; +import { event } from "log"; -## API - -### `parse(source, filename?)` - -Parses a single top-level expression or statement and returns an AST with source spans. - -- Use this for tooling, syntax inspection, or tests. -- Throws on parse errors or disallowed syntax. +for (const task of tasks) { + event("task.started", { id: task.id }); + const build = await spawn(agents.builder, { prompt: task.prompt }); + const review = await spawn(agents.reviewer, { prompt: build.summary }); + event("task.completed", { id: task.id, review: review.summary }); +} +``` -### `lint(source, options?)` +That snippet runs inside the sandbox. `agent`, `harness`, and `log` are host modules registered by the caller; everything else is plain JavaScript. -Returns diagnostics for the agent-script subset and registered modules. +## Use cases -Options: +### 1. Multi-agent orchestrator -- `filename?`: filename used in diagnostics. Defaults to ``. -- `modules?`: registered module metadata used to validate `import` statements. +You have several agent personas (builder, reviewer, judge, owner, …) and want to run them in a specific shape. Write the shape as a script. -Diagnostics include: +See: -- parse/disallowed syntax errors -- unknown modules and unknown exports -- unknown identifiers -- closure and async-safety checks -- subset-specific method restrictions -- a small set of warnings for unused bindings and unnecessary patterns +- `examples/pipeline.md` — sequential builder → reviewer over a list of tasks +- `examples/superintendent.md` — builder + parallel inspectors + judge + owner, with rounds +- `examples/experiment.md` — checkpoint → attempt → measure → keep-or-revert loop -### `run(source, options?)` +Run any of them with the bundled CLI: -Executes a script module and returns: +```bash +npx poe-agent-script examples/pipeline.md +``` -- `{ ok: true, returnValue?, snapshot, stats }` on success -- `{ ok: false, error, snapshot, stats }` on interpreter errors +### 2. MCP code mode -Options: +Letting an LLM call MCP tools turn-by-turn is expensive, slow, and non-deterministic. With agent-script, the LLM produces (or you author) a script that calls MCP tools directly: -- `bindings?`: extra top-level host bindings -- `budget?`: interpreter budget instance -- `modules?`: runtime module registry -- `randomSeed?`: deterministic seed for `Math.random()` -- `signal?`: abort signal for cancellation -- `snapshot?`: prior snapshot validated through `restore()` -- `snapshotIntervalMs?`: periodic snapshot write interval -- `snapshotPath?`: file path written by the snapshot scheduler -- `sink?`: console sink used by the subset `console` globals +```js +import { client, server } from "mcp"; -### `dump(resultOrPromise)` +const fs = await client(server({ command: "mcp-fs", args: ["--root", "/tmp/work"] })); +const tools = await fs.tools(); +const result = await fs.tool("read_file", { path: "/tmp/work/notes.md" }); +``` -Serializes a run snapshot to formatted JSON. +The host wires up the actual transport via a `connectMcp` callback (see [`src/modules/mcp.ts`](src/modules/mcp.ts)). The script just composes calls. -- Accepts a completed `RunResult` -- Accepts the pending promise returned by `run()` -- When used with an in-flight `run()` promise, resolves to the latest yielded snapshot +### 3. Sandboxed user scripting -### `restore(snapshot, { source })` +Embed agent-script in your own product when you want to let users (or models) write small programs against a fixed set of capabilities you control. The sandbox guarantees they cannot reach outside the modules you registered, can't allocate unbounded memory, and can't run forever. -Validates that a stored snapshot still matches the current source by comparing `sourceHash`. +## Spec — index card -- Returns the snapshot unchanged when the hash matches -- Throws when the source changed since the snapshot was taken +| Aspect | Detail | +| --- | --- | +| **Source unit** | one module body; `import` from registered modules only | +| **Allowed** | `const`, `let`, arrays, objects, destructuring, rest, spread, arrow funcs (incl. `async`), top-level `await`, `if`, `for`, `for...of`, `while`, `break`, `continue`, `try`/`catch`/`finally`, `throw`, `return`, template literals, optional chaining | +| **Disallowed** | `function`, `class`, `new`, `this`, `var`, `do…while`, `switch`, labels, regex literals, generators, `eval`, `Function` | +| **Lint extras** | `await` only at top level or inside `async` arrows; lambdas can't close over outer `let`; no `__proto__` / `prototype` / `constructor`; no regex args to `String#split` / `replace` / `replaceAll`; `Array#sort` only takes an arrow returning a number | +| **Built-in globals** | `console`, `Error` and friends, `Math`, `Object`, `Array`, `Promise.all` / `race` / `allSettled` / `any` | +| **Determinism** | `Math.random()` requires `randomSeed`; otherwise unbound. Snapshots include the RNG state. | +| **Snapshots** | written at most every `snapshotIntervalMs` (default 30 s) to `snapshotPath`; resumed via `restore()` if `sourceHash` matches | +| **Budgets** | `maxSteps`, `deadline`, `maxCallDepth`, `stringLength`, `arrayLength` | +| **Cancellation** | `AbortSignal`, observed at every host call and yield point | -### `runHarness(filepath, options)` +## Built-in host modules -Loads a harness document from disk, lints it, and executes it. +Registered by the caller via the factory functions exported from the package. None of them are auto-installed — you choose which to wire up per run. -Options: +| Import | Factory | What it gives the script | +|---|---|---| +| `agent` | `makeAgentModule(spawnAgent)` | `spawn(definition, { prompt, mode, model, mcp, cwd, timeoutMs })` | +| `git` | `makeGitModule(cwd)` | `head`, `checkpoint`, `commit`, `revert`, `diff` | +| `harness` | `makeHarnessModule(frontmatter, meta)` | `tasks`, `agents`, `meta` (kind, version, filepath, frontmatter) | +| `log` | `makeLogModule(sink?)` | `info`, `error`, `event` (JSONL by default) | +| `metric` | `makeMetricModule(npmRunner)` | `run(name)` — runs an npm script and parses its last numeric line | +| `mcp` | `makeMcpModule(connectMcp)` | `server(handle)`, `client(handle)` → `{ tools(), tool(name, args) }` | +| `env` | `makeEnvModule(allowList)` | `get(name)` — only for names in the allowlist | +| `time` | `makeTimeModule({ now?, random? })` | `now`, `uuid` | +| `fail` | `makeFailModule()` | `default(message)` — throws `HarnessFailure` | -- `modulesFor(frontmatter, meta)`: returns the runtime module registry for that file -- `signal?`: abort signal for cancellation -- `snapshotPath?`: file path written by the snapshot scheduler +## Quick start -Behavior: +```ts +import { lint, run } from "@poe-code/agent-script"; -- For markdown files, `frontmatter` is the parsed YAML mapping and `meta` includes `filepath`, `kind`, and `version` -- For `.ajs` files, `frontmatter` is `{}` and `kind` / `version` are `undefined` -- Lint errors throw `LintError` before execution -- The `harness` module is automatically excluded for raw `.ajs` scripts +const source = ` + import { greet } from "custom"; + return await greet("Ada"); +`; -## Language Subset +const modules = { + custom: { greet: async (name) => `hello ${name}` } +}; -### In +const errors = lint(source, { modules: { custom: ["greet"] } }) + .filter((d) => d.severity === "error"); +if (errors.length > 0) throw new Error(errors.map((d) => d.message).join("\n")); -- `import` declarations from registered host modules -- `const` and `let` -- arrays, objects, destructuring, rest, and spread -- arrow functions, including `async` arrows -- `await` at top level and inside `async` arrows -- `if`, `for`, `for...of`, `while`, `break`, and `continue` -- `try` / `catch` / `finally`, `throw`, and `return` -- template literals -- property access, optional chaining, and function calls -- primitive values plus plain array/object data +const result = await run(source, { modules }); +if (!result.ok) throw result.error; +console.log(result.returnValue); // "hello Ada" +``` -### Out +## Harness files -- `function` declarations and expressions -- generators -- `class` -- `new` -- `this` -- `var` -- `do...while` -- `switch` -- `with` -- labels -- regex literals -- `eval` and `Function` +`runHarness(filepath, options)` loads a script from disk, lints it, then runs it. -### Runtime and lint restrictions +- `.ajs` files: the entire file is the script. Frontmatter is `{}`. The `harness` module is auto-excluded since there's nothing for it to surface. +- `.md` files: YAML frontmatter is parsed; the **first** `js` fenced block is the script. If there is no fenced block, the entire markdown body is treated as script source. -- `await` is only valid at script top level or inside `async` arrows -- lambdas cannot close over outer `let` bindings -- `__proto__`, `prototype`, and `constructor` property access is rejected -- `String#split()` does not accept regex separators -- `String#replace()` and `String#replaceAll()` do not accept regex search values or function replacers -- `Array#sort()` only accepts comparators that are arrows returning a number +```ts +import { makeHarnessModule, runHarness } from "@poe-code/agent-script"; -## Registered Modules +const result = await runHarness("docs/plans/example.md", { + modulesFor: (frontmatter, meta) => ({ + harness: makeHarnessModule(frontmatter, meta), + custom: { greet: (name) => `hello ${name}` } + }), + snapshotPath: ".cache/example.snapshot.json" +}); +``` -### Runtime shape +## API -`run()` expects a module registry shaped like this: +### `parse(source, filename?)` -```ts -const modules = { - moduleName: { - exportedName: valueOrFunction - } -}; -``` +Parses a single top-level expression or statement and returns an AST with source spans. Throws on parse errors or disallowed syntax. -You can use either plain objects or `Map`s at both levels: +### `lint(source, options?)` -```ts -const modules = new Map([ - [ - "custom", - new Map([ - ["hello", (name: string) => `hello ${name}`] - ]) - ] -]); -``` +Returns diagnostics for the agent-script subset and registered modules. -Each export can be: +- `filename?` — used in diagnostics, defaults to `` +- `modules?` — registered module metadata used to validate `import` statements -- a sandbox-copyable value: `string`, `number`, `boolean`, `null`, `undefined`, plain arrays, plain objects -- a host function -- an async host function +Diagnostics cover parse errors, unknown modules and exports, unknown identifiers, closure and async-safety violations, subset-specific method restrictions, and warnings for unused bindings. -Host functions are wrapped automatically so subset code can call them safely. +### `run(source, options?)` -### Lint shape +Executes a script module. Resolves to: -`lint()` only needs module metadata, not live functions. The simplest shape is an export list: +- `{ ok: true, returnValue?, snapshot, stats }` on success +- `{ ok: false, error, snapshot, stats }` on interpreter errors -```ts -const lintModules = { - custom: ["hello"] -}; -``` +Options: `bindings`, `budget`, `modules`, `randomSeed`, `signal`, `snapshot` (prior snapshot), `snapshotIntervalMs`, `snapshotPath`, `sink`. -For source-backed modules, you can also register: +### `dump(resultOrPromise)` -```ts -const lintModules = { - custom: { - exports: ["hello"], - filename: "/repo/custom.ajs", - source: 'exported source used for dependency checks' - } -}; -``` +Serializes a snapshot to formatted JSON. Accepts either a completed `RunResult` or the in-flight promise from `run()` (in which case it resolves to the latest yielded snapshot). -That richer shape lets the linter detect source-module cycles. +### `restore(snapshot, { source })` -## Adding A Custom Module +Validates a stored snapshot against the current source via `sourceHash`. Returns it unchanged on match, throws on mismatch. -1. Create a host object that exposes the functions or values you want the script to import. -2. Register it under a module name in `run({ modules })`. -3. If you lint separately, register the same module name and exported names in `lint({ modules })`. -4. If you need explicit host/sandbox copying, use `deepCopyToSandbox()` and `deepCopyFromSandbox()`. +### `runHarness(filepath, options)` -Minimal custom module: +Loads, lints, and runs a harness file. -```ts -import { lint, run } from "@poe-code/agent-script"; +- `modulesFor(frontmatter, meta)` — returns the module registry for that file +- `signal?`, `snapshotPath?` -const source = [ - 'import { greet } from "custom";', - 'return await greet("Ada");' -].join("\n"); +`LintError` is thrown before execution if lint reports errors. -const runtimeModules = { - custom: { - greet: async (name: string) => `hello ${name}` - } -}; +## Adding a custom module -const diagnostics = lint(source, { - filename: "example.ajs", - modules: { - custom: ["greet"] - } -}); +1. Build a host object exposing the values or async functions the script should see. +2. Register it under a name in `run({ modules })`. +3. Mirror the same name and exported names in `lint({ modules })` if you lint separately. +4. For explicit boundary copying, use `deepCopyToSandbox` / `deepCopyFromSandbox`. -if (diagnostics.some((diagnostic) => diagnostic.severity === "error")) { - throw new Error("Script did not lint cleanly."); -} +The runtime accepts plain objects or `Map`s at both levels: -const result = await run(source, { - modules: runtimeModules -}); +```ts +const modules = new Map([ + ["custom", new Map([["hello", (name: string) => `hello ${name}`]])] +]); +``` -if (!result.ok) { - throw new Error(result.error.message); -} +For lint, the simplest shape is just an export list: -console.log(result.returnValue); +```ts +const lintModules = { custom: ["hello"] }; ``` -## Harness Example +Source-backed modules (used to detect cross-module cycles) take a richer shape: ```ts -import { makeHarnessModule, runHarness } from "@poe-code/agent-script"; - -const result = await runHarness("/repo/docs/plans/example.md", { - modulesFor(frontmatter, meta) { - return { - harness: makeHarnessModule(frontmatter, meta), - custom: { - greet: (name: string) => `hello ${name}` - } - }; - } -}); +const lintModules = { + custom: { exports: ["hello"], filename: "/repo/custom.ajs", source: "…" } +}; ``` -## Environment variables +## Gotchas -This package does not read package-level environment variables. +- **No mutable closures.** Lambdas cannot capture an outer `let`. The idiomatic loop is recursion (see `examples/experiment.md`) or `for…of` whose body does not return a closure that reads the loop variable. +- **No `function` at all.** Use arrow functions everywhere. The lint error is explicit but easy to hit when porting existing JS. +- **Markdown parsing is greedy and quiet.** Only the first `js` fenced block runs. If there is no fenced block, the *entire* markdown body becomes the script source — which often fails to parse but the failure mode surprises people. +- **Snapshots are source-pinned.** Editing the script invalidates every prior snapshot for it. There is no migration path; bump or fork the file if you need to keep an old run resumable. +- **`Math.random()` is unbound by default.** Pass `randomSeed` to enable it. Snapshots persist the RNG state so resumes stay deterministic. +- **`Promise.all` is fine; user-defined concurrency primitives are not.** `Promise` is exposed only for `all` / `race` / `allSettled` / `any`. There is no `new Promise(...)`. +- **Agent failures throw.** `agent.spawn` rejects when the child agent's `exitCode !== 0`. Catch it if your shape needs to recover. +- **MCP module is BYO transport.** `makeMcpModule` requires a `connectMcp` callback that returns a working `listTools` / `callTool` connection. The package does not bundle a transport. +- **`env` module is allowlisted.** `makeEnvModule(["FOO"])` will only return `FOO`. Anything else returns `undefined` even if it's set in `process.env`. +- **Budgets are hard limits, not soft warnings.** Hitting `maxSteps` or `deadline` throws `SandboxError` with `code: "budgetExceeded"`. There is no graceful degradation; size budgets generously for your workload or wrap the run in your own retry policy. -Notes: +## What's not here yet -- `run()`, `lint()`, `parse()`, `dump()`, `restore()`, and `runHarness()` do not read environment variables on their own -- `makeEnvModule(allowList)` reads from the current process environment, but only for names you explicitly allow +- No regex support of any kind (literals, `RegExp`, regex args to string methods). +- No user-defined classes or prototype chains. +- No streaming/iterator protocol — `for…of` works on arrays, not generators. +- No filesystem, network, or process modules in the box. Build them as host modules with the surface you actually want to expose. +- No multi-file imports — a script is a single module body. Compose by registering more modules. -## Configuration +## Environment variables -This package does not read package-level config files. +This package does not read package-level environment variables. `makeEnvModule(allowList)` reads from `process.env`, but only for names in `allowList`. `parse`, `lint`, `run`, `dump`, `restore`, and `runHarness` do not read environment variables on their own. + +## Configuration -Runner options: +This package does not read package-level config files. Runner options come through the call sites: -- `lint()` reads `filename` and `modules` -- `run()` reads `bindings`, `budget`, `modules`, `randomSeed`, `signal`, `snapshot`, `snapshotIntervalMs`, `snapshotPath`, and `sink` -- `runHarness()` reads `modulesFor`, `signal`, and `snapshotPath` +- `lint({ filename, modules })` +- `run({ bindings, budget, modules, randomSeed, signal, snapshot, snapshotIntervalMs, snapshotPath, sink })` +- `runHarness({ modulesFor, signal, snapshotPath })` diff --git a/packages/agent-spawn/src/acp/acp.test.ts b/packages/agent-spawn/src/acp/acp.test.ts index b1b30a6b71..e49c4d4a16 100644 --- a/packages/agent-spawn/src/acp/acp.test.ts +++ b/packages/agent-spawn/src/acp/acp.test.ts @@ -2,6 +2,12 @@ import { describe, it, expect, vi, beforeEach } from "vitest"; import { PassThrough, Readable } from "node:stream"; import { EventEmitter } from "node:events"; import { spawn as spawnChildProcess, type ChildProcessWithoutNullStreams } from "node:child_process"; +import { + registerExecutionEnvFactory, + type ExecutionEnvFactory, + type OpenSpec, + type RunSpec +} from "@poe-code/agent-harness-tools"; import { readLines } from "./line-reader.js"; import { applyMiddlewares, type AcpMiddleware, type SpawnContext } from "./middleware.js"; @@ -787,6 +793,104 @@ describe("acp/spawnStreaming", () => { expect(spawnOptions).toMatchObject({ cwd: "/tmp", stdio: ["pipe", "pipe", "pipe"] }); }); + it("routes streaming spawns through the requested runtime backend", async () => { + let capturedOpenSpec: OpenSpec | undefined; + let capturedRunSpec: RunSpec | undefined; + const stdout = new PassThrough(); + const stderr = new PassThrough(); + const stdin = new PassThrough(); + const kill = vi.fn(); + + const dockerFactory: ExecutionEnvFactory = { + type: "docker", + supportsDetach: true, + async open(openSpec) { + capturedOpenSpec = openSpec; + return { + id: "docker-test", + job: null, + async uploadWorkspace() { + return { files: 0, bytes: 0, skipped: [] }; + }, + async downloadWorkspace() { + return { files: 0, bytes: 0, conflicts: [] }; + }, + exec(spec) { + capturedRunSpec = spec; + queueMicrotask(() => { + stdout.write( + `${JSON.stringify({ + type: "text", + sessionID: "ses_docker", + part: { type: "text", messageID: "msg_1", text: "from docker" } + })}\n` + ); + stdout.end(); + stderr.write("warn\n"); + stderr.end(); + }); + return { + pid: 123, + stdin, + stdout, + stderr, + result: Promise.resolve({ exitCode: 0 }), + kill + }; + }, + async detach() { + throw new Error("unused"); + }, + shell() { + throw new Error("unused"); + }, + async close() {} + }; + }, + async attach() { + throw new Error("unused"); + } + }; + registerExecutionEnvFactory(dockerFactory); + + const { events, done } = spawnStreaming({ + agentId: "opencode", + prompt: "hello", + cwd: "/tmp", + runtime: "docker", + runtimeImage: "poe-code:test", + mountPoeCode: true + }); + + await expect(collect(events)).resolves.toEqual([ + { event: "session_start", threadId: "ses_docker" }, + { event: "agent_message", text: "from docker" } + ]); + await expect(done).resolves.toEqual({ + stdout: "", + stderr: "warn\n", + exitCode: 0 + }); + + expect(spawnChildProcess).not.toHaveBeenCalled(); + expect(capturedOpenSpec?.runtime).toMatchObject({ + type: "docker", + image: "poe-code:test" + }); + expect(capturedOpenSpec?.runtime.mounts).toContainEqual({ + source: "/tmp", + target: "/usr/local/lib/poe-code", + readonly: true + }); + expect(capturedRunSpec).toMatchObject({ + command: "opencode", + cwd: "/tmp", + stdin: "pipe", + stdout: "pipe", + stderr: "pipe" + }); + }); + it("passes through multiple usage events without accumulating into done", async () => { const mock = createMockChildProcess({ stdoutLines: [ @@ -862,7 +966,7 @@ describe("acp/spawnStreaming", () => { } }); - it("rejects done when child process emits error", async () => { + it("returns exit code 1 when the runtime reports a process launch error", async () => { const mock = createMockChildProcess({ error: new Error("spawn failed") }); vi.mocked(spawnChildProcess).mockReturnValue(mock.child); @@ -871,9 +975,12 @@ describe("acp/spawnStreaming", () => { prompt: "hello" }); - const doneRejection = expect(done).rejects.toThrow("spawn failed"); await expect(collect(events)).resolves.toEqual([]); - await doneRejection; + await expect(done).resolves.toEqual({ + stdout: "", + stderr: "", + exitCode: 1 + }); }); it("writes prompt to stdin when useStdin is true and stdinMode is available", async () => { diff --git a/packages/agent-spawn/src/acp/spawn-acp.ts b/packages/agent-spawn/src/acp/spawn-acp.ts index b8d6f9f3cb..6d8017c070 100644 --- a/packages/agent-spawn/src/acp/spawn-acp.ts +++ b/packages/agent-spawn/src/acp/spawn-acp.ts @@ -12,6 +12,11 @@ export interface SpawnAcpOptions { model?: string; mode?: SpawnMode; mcpServers?: McpSpawnConfig; + runtime?: "host" | "docker" | "e2b"; + runtimeImage?: string; + runtimeTemplate?: string; + detach?: boolean; + mountPoeCode?: boolean; signal?: AbortSignal; } diff --git a/packages/agent-spawn/src/acp/spawn.ts b/packages/agent-spawn/src/acp/spawn.ts index 8b76f85d57..6c55ece997 100644 --- a/packages/agent-spawn/src/acp/spawn.ts +++ b/packages/agent-spawn/src/acp/spawn.ts @@ -1,10 +1,11 @@ -import { spawn as spawnChildProcess } from "node:child_process"; +import "../register-factories.js"; +import { runPoeCommand } from "@poe-code/agent-harness-tools"; import { getAdapter } from "../adapters/index.js"; import type { AcpEvent } from "./types.js"; -import { readLines } from "./line-reader.js"; import { resolveConfig } from "../configs/resolve-config.js"; import { getMcpArgs, getMcpEnv } from "../mcp-args.js"; import { stripModelNamespace } from "../model-utils.js"; +import { resolveSpawnExecution } from "../runtime.js"; import { resolveModeConfig, type CliSpawnConfig, type SpawnOptions, type SpawnResult } from "../types.js"; function createAbortError(): Error { @@ -13,14 +14,6 @@ function createAbortError(): Error { return error; } -function createActivityTimeoutError(timeoutMs: number): Error { - const error = new Error( - `Agent spawn timed out after ${timeoutMs / 1000}s of inactivity` - ); - error.name = "ActivityTimeoutError"; - return error; -} - export interface SpawnStreamingOptions extends SpawnOptions { agentId: string; } @@ -34,6 +27,77 @@ function isAcpEvent(value: unknown): value is AcpEvent { return !!value && typeof value === "object" && "event" in value; } +function createLineQueue(): { + push(chunk: string): void; + close(): void; + lines(): AsyncIterable; +} { + const lines: string[] = []; + const waiters: Array<{ + resolve(value: IteratorResult): void; + }> = []; + let pending = ""; + let closed = false; + + const emit = (line: string): void => { + const waiter = waiters.shift(); + if (waiter) { + waiter.resolve({ done: false, value: line }); + return; + } + lines.push(line); + }; + + const finishWaiters = (): void => { + while (waiters.length > 0) { + const waiter = waiters.shift()!; + waiter.resolve({ done: true, value: undefined }); + } + }; + + return { + push(chunk: string): void { + if (closed) return; + pending += chunk; + let newlineIndex = pending.indexOf("\n"); + while (newlineIndex !== -1) { + const raw = pending.slice(0, newlineIndex); + emit(raw.endsWith("\r") ? raw.slice(0, -1) : raw); + pending = pending.slice(newlineIndex + 1); + newlineIndex = pending.indexOf("\n"); + } + }, + close(): void { + if (closed) return; + if (pending.length > 0) { + emit(pending.endsWith("\r") ? pending.slice(0, -1) : pending); + pending = ""; + } + closed = true; + finishWaiters(); + }, + lines(): AsyncIterable { + return { + [Symbol.asyncIterator](): AsyncIterator { + return { + next(): Promise> { + if (lines.length > 0) { + return Promise.resolve({ done: false, value: lines.shift()! }); + } + if (closed) { + return Promise.resolve({ done: true, value: undefined }); + } + return new Promise((resolve) => { + waiters.push({ resolve }); + }); + } + }; + } + }; + } + }; +} + function getDefaultArgsPosition(config: CliSpawnConfig): "beforePrompt" | "afterPrompt" { return config.defaultArgsPosition ?? "afterPrompt"; } @@ -119,83 +183,73 @@ export function spawnStreaming(options: SpawnStreamingOptions): SpawnStreamingRe } const envOverrides = { ...mcpEnvVars, ...modeResolved.env }; - const child = spawnChildProcess(binaryName, args, { - cwd: options.cwd, - stdio: ["pipe", "pipe", "pipe"], - env: Object.keys(envOverrides).length > 0 - ? { ...process.env, ...envOverrides } - : undefined - }); - let aborted = false; - let timedOut = false; - const onAbort = () => { - aborted = true; - child.kill("SIGTERM"); - }; - options.signal?.addEventListener("abort", onAbort, { once: true }); - - let activityTimer: ReturnType | undefined; - const resetActivityTimer = options.activityTimeoutMs - ? () => { - if (activityTimer) clearTimeout(activityTimer); - activityTimer = setTimeout(() => { - timedOut = true; - child.kill("SIGTERM"); - }, options.activityTimeoutMs); + const processEnv = + Object.keys(envOverrides).length > 0 ? { ...process.env, ...envOverrides } : undefined; + const queue = createLineQueue(); + const argv = [binaryName, ...args]; + const execution = resolveSpawnExecution({ + cwd: options.cwd ?? process.cwd(), + env: (processEnv ?? process.env) as Record, + argv, + tool: agentId, + runtime: { + runtime: options.runtime, + runtimeImage: options.runtimeImage, + runtimeTemplate: options.runtimeTemplate, + detach: options.detach, + mountPoeCode: options.mountPoeCode + }, + openSpec: { + execution: { + wrapForLogTee: false, + stdin: "pipe", + stdout: "pipe", + stderr: "pipe", + env: processEnv as Record | undefined, + input: useStdin ? options.prompt : "", + captureOutput: true, + activityTimeoutMs: options.activityTimeoutMs, + onStdout(chunk: string) { + queue.push(chunk); + }, + onStderr(chunk: string) { + if (options.tee?.stderr) options.tee.stderr.write(chunk); + } } - : undefined; - - resetActivityTimer?.(); - - const result: SpawnResult = { stdout: "", stderr: "", exitCode: 1 }; - child.stderr.setEncoding("utf8"); - child.stderr.on("data", (chunk) => { - result.stderr += chunk; - resetActivityTimer?.(); - if (options.tee?.stderr) options.tee.stderr.write(chunk); + } }); - if (useStdin) { - child.stdin.write(options.prompt); - } - child.stdin.end(); - + const result: SpawnResult = { stdout: "", stderr: "", exitCode: 1 }; const adapter = getAdapter(spawnConfig.adapter); const events: AsyncIterable = (async function* () { - for await (const output of adapter(readLines(child.stdout))) { + for await (const output of adapter(queue.lines())) { if (!isAcpEvent(output)) continue; - resetActivityTimer?.(); yield output; } })(); - const done = new Promise((resolve, reject) => { - child.on("error", (error) => { - options.signal?.removeEventListener("abort", onAbort); - if (activityTimer) clearTimeout(activityTimer); - if (aborted) { - reject(createAbortError()); - return; - } - reject(error); - }); - - child.on("close", (code) => { - options.signal?.removeEventListener("abort", onAbort); - if (activityTimer) clearTimeout(activityTimer); - if (aborted) { - reject(createAbortError()); - return; + const done = (async (): Promise => { + try { + const runResult = await runPoeCommand({ + factory: execution.factory, + openSpec: execution.openSpec, + detach: execution.detach, + state: execution.state, + signal: options.signal + }); + + if (runResult.kind === "detached") { + return { stdout: "", stderr: "", exitCode: 0 }; } - if (timedOut) { - reject(createActivityTimeoutError(options.activityTimeoutMs!)); - return; - } - result.exitCode = code ?? 1; - resolve(result); - }); - }); + + result.stderr = runResult.stderr ?? ""; + result.exitCode = runResult.exitCode; + return result; + } finally { + queue.close(); + } + })(); return { events, done }; } diff --git a/packages/agent-spawn/src/spawn-interactive.ts b/packages/agent-spawn/src/spawn-interactive.ts index be01d6f6ab..94e4b6e2cc 100644 --- a/packages/agent-spawn/src/spawn-interactive.ts +++ b/packages/agent-spawn/src/spawn-interactive.ts @@ -73,6 +73,13 @@ export async function spawnInteractive( env: (processEnv ?? process.env) as Record, argv, tool: resolved.agentId, + runtime: { + runtime: options.runtime, + runtimeImage: options.runtimeImage, + runtimeTemplate: options.runtimeTemplate, + detach: options.detach, + mountPoeCode: options.mountPoeCode + }, openSpec: { execution: { wrapForLogTee: false, diff --git a/packages/agent-spawn/src/spawn.ts b/packages/agent-spawn/src/spawn.ts index 182ee4bd6c..34c736fda8 100644 --- a/packages/agent-spawn/src/spawn.ts +++ b/packages/agent-spawn/src/spawn.ts @@ -177,6 +177,13 @@ export async function spawn( env: (processEnv ?? process.env) as Record, argv, tool: resolvedId, + runtime: { + runtime: options.runtime, + runtimeImage: options.runtimeImage, + runtimeTemplate: options.runtimeTemplate, + detach: options.detach, + mountPoeCode: options.mountPoeCode + }, context, openSpec: { execution: { diff --git a/packages/agent-spawn/src/types.ts b/packages/agent-spawn/src/types.ts index f9dae67196..4dd6388450 100644 --- a/packages/agent-spawn/src/types.ts +++ b/packages/agent-spawn/src/types.ts @@ -1,4 +1,5 @@ import type { AdapterType } from "./adapters/index.js"; +import type { RuntimeOverrideOptions } from "@poe-code/agent-harness-tools"; import type { StateManager } from "@poe-code/poe-code-config"; export type SpawnMode = "yolo" | "edit" | "read"; @@ -64,6 +65,16 @@ export interface SpawnOptions { logDir?: string; /** Overrides the auto-generated log filename. Must be used together with `logDir`. */ logFileName?: string; + /** Per-invocation runtime/runner config overrides. */ + runtime?: RuntimeOverrideOptions["runtime"]; + /** Docker image override for docker runtime. */ + runtimeImage?: string; + /** E2B template override for e2b runtime. */ + runtimeTemplate?: string; + /** Run through a detached runtime job when the backend supports it. */ + detach?: boolean; + /** Mount the local poe-code checkout into the runtime for development. */ + mountPoeCode?: boolean; } export interface SpawnUsage { diff --git a/packages/experiment-loop/src/run/loop.ts b/packages/experiment-loop/src/run/loop.ts index b3c3d74563..cbdd01e0f6 100644 --- a/packages/experiment-loop/src/run/loop.ts +++ b/packages/experiment-loop/src/run/loop.ts @@ -440,6 +440,11 @@ export async function runExperimentLoop( logFileName: makeRunLogFileName( `experiment-${experimentIndex}-${currentSpecifier.agent}` ), + ...(options.runtime ? { runtime: options.runtime } : {}), + ...(options.runtimeImage ? { runtimeImage: options.runtimeImage } : {}), + ...(options.runtimeTemplate ? { runtimeTemplate: options.runtimeTemplate } : {}), + ...(options.detach ? { detach: options.detach } : {}), + ...(options.mountPoeCode ? { mountPoeCode: options.mountPoeCode } : {}), ...(model ? { model } : {}), ...(options.signal ? { signal: options.signal } : {}) }); diff --git a/packages/experiment-loop/src/types.ts b/packages/experiment-loop/src/types.ts index 6f1b3c516f..a7b3a732ad 100644 --- a/packages/experiment-loop/src/types.ts +++ b/packages/experiment-loop/src/types.ts @@ -40,6 +40,11 @@ export interface AgentRunInput { prompt: string; cwd: string; model?: string; + runtime?: "host" | "docker" | "e2b"; + runtimeImage?: string; + runtimeTemplate?: string; + detach?: boolean; + mountPoeCode?: boolean; signal?: AbortSignal; logDir?: string; logFileName?: string; @@ -56,6 +61,11 @@ export interface ExperimentRunOptions { homeDir: string; docPath: string; agent?: string | string[]; + runtime?: "host" | "docker" | "e2b"; + runtimeImage?: string; + runtimeTemplate?: string; + detach?: boolean; + mountPoeCode?: boolean; maxExperiments?: number; fs?: ExperimentFileSystem; git?: ExperimentGit; diff --git a/packages/ralph/src/run/ralph.ts b/packages/ralph/src/run/ralph.ts index 8c37ba1a55..ccad131ce5 100644 --- a/packages/ralph/src/run/ralph.ts +++ b/packages/ralph/src/run/ralph.ts @@ -99,6 +99,11 @@ export async function runRalph( cwd: input.cwd, logDir: runLogDir, logFileName: makeRunLogFileName(specifier.agent), + ...(options.runtime ? { runtime: options.runtime } : {}), + ...(options.runtimeImage ? { runtimeImage: options.runtimeImage } : {}), + ...(options.runtimeTemplate ? { runtimeTemplate: options.runtimeTemplate } : {}), + ...(options.detach ? { detach: options.detach } : {}), + ...(options.mountPoeCode ? { mountPoeCode: options.mountPoeCode } : {}), ...(specifier.model ?? input.model ? { model: specifier.model ?? input.model } : {}), diff --git a/packages/ralph/src/types.ts b/packages/ralph/src/types.ts index 1407a3be85..f15cef521a 100644 --- a/packages/ralph/src/types.ts +++ b/packages/ralph/src/types.ts @@ -19,6 +19,11 @@ export interface AgentRunInput { prompt: string; cwd: string; model?: string; + runtime?: "host" | "docker" | "e2b"; + runtimeImage?: string; + runtimeTemplate?: string; + detach?: boolean; + mountPoeCode?: boolean; signal?: AbortSignal; logDir?: string; logFileName?: string; @@ -45,6 +50,11 @@ export interface RalphRunOptions { homeDir: string; docPath: string; maxIterations?: number; + runtime?: "host" | "docker" | "e2b"; + runtimeImage?: string; + runtimeTemplate?: string; + detach?: boolean; + mountPoeCode?: boolean; fs?: RalphFileSystem; runAgent?: (input: AgentRunInput) => Promise; onIterationStart?: ( diff --git a/packages/superintendent/src/commands/run.test.ts b/packages/superintendent/src/commands/run.test.ts index f6d6023618..5c3fbef1cf 100644 --- a/packages/superintendent/src/commands/run.test.ts +++ b/packages/superintendent/src/commands/run.test.ts @@ -261,6 +261,60 @@ describe("superintendent run command", () => { expect(result.builderAgent).toBe("codex"); }); + it("passes runtime overrides from command options into agent runs", async () => { + const fs = createFs({ + "/repo/docs/plans/plan.md": createDoc("codex") + }); + const executeAgent = vi.fn(async () => ({ + stdout: "", + stderr: "", + exitCode: 0 + })); + const runLoopMock = vi.fn(async (options: RunLoopOptions) => { + await options.runAgent?.({ + agent: "claude-code", + prompt: "Build", + cwd: "/repo" + }); + return { + state: "completed" as const, + round: 1, + reviewTurn: 0, + maxRounds: 100, + maxReviewTurns: 5, + stopReason: "completed" as const + }; + }); + + const { runSuperintendentCommand } = await import("./run.js"); + await runSuperintendentCommand({ + cwd: "/repo", + homeDir: "/home/test", + docPath: "/repo/docs/plans/plan.md", + assumeYes: true, + interactive: false, + useDashboard: false, + fs, + runLoop: runLoopMock, + executeAgent, + runtime: "e2b", + runtimeTemplate: "tpl_123", + detach: true, + mountPoeCode: true, + env: {} + }); + + expect(executeAgent).toHaveBeenCalledWith( + "claude-code", + expect.objectContaining({ + runtime: "e2b", + runtimeTemplate: "tpl_123", + detach: true, + mountPoeCode: true + }) + ); + }); + it("prompts for a builder agent when frontmatter omits builder.agent", async () => { const fs = createFs({ "/repo/docs/plans/plan.md": createDocWithBuilderSection([ diff --git a/packages/superintendent/src/commands/run.ts b/packages/superintendent/src/commands/run.ts index 70153c83fe..e0afd30db5 100644 --- a/packages/superintendent/src/commands/run.ts +++ b/packages/superintendent/src/commands/run.ts @@ -61,6 +61,11 @@ export type RunCommandOptions = { homeDir: string; docPath?: string; builderAgent?: string; + runtime?: "host" | "docker" | "e2b"; + runtimeImage?: string; + runtimeTemplate?: string; + detach?: boolean; + mountPoeCode?: boolean; configuredDefaultAgent?: string | null; planDirectory?: string; assumeYes?: boolean; @@ -124,6 +129,15 @@ const runParams = S.Object({ description: "Override the builder agent for this run. Precedence: --agent > plan frontmatter builder.agent." })), + runtime: S.Optional(S.Enum(["host", "docker", "e2b"] as const, { + description: "Override runtime backend: host, docker, or e2b" + })), + runtimeImage: S.Optional(S.String({ description: "Override Docker runtime image" })), + runtimeTemplate: S.Optional(S.String({ description: "Override E2B runtime template id" })), + detach: S.Optional(S.Boolean({ description: "Run as a detached runtime job" })), + mountPoeCode: S.Optional(S.Boolean({ + description: "Mount the local poe-code checkout into the runtime" + })), tui: S.Optional(S.Boolean({ description: "Show a live dashboard while Superintendent is running" })) }); @@ -144,6 +158,11 @@ export const runCommand = defineCommand({ homeDir, docPath: params.doc, ...(params.agent ? { builderAgent: params.agent } : {}), + ...(params.runtime ? { runtime: params.runtime } : {}), + ...(params.runtimeImage ? { runtimeImage: params.runtimeImage } : {}), + ...(params.runtimeTemplate ? { runtimeTemplate: params.runtimeTemplate } : {}), + ...(params.detach ? { detach: params.detach } : {}), + ...(params.mountPoeCode ? { mountPoeCode: params.mountPoeCode } : {}), configuredDefaultAgent: commandConfig.configuredDefaultAgent, assumeYes: process.argv.includes("--yes"), interactive: Boolean(process.stdin.isTTY), @@ -203,6 +222,11 @@ export function createRunMcpCommand(runners?: RunMcpCommandRunners) { homeDir, docPath: params.doc, ...(params.agent ? { builderAgent: params.agent } : {}), + ...(params.runtime ? { runtime: params.runtime } : {}), + ...(params.runtimeImage ? { runtimeImage: params.runtimeImage } : {}), + ...(params.runtimeTemplate ? { runtimeTemplate: params.runtimeTemplate } : {}), + ...(params.detach ? { detach: params.detach } : {}), + ...(params.mountPoeCode ? { mountPoeCode: params.mountPoeCode } : {}), configuredDefaultAgent: commandConfig.configuredDefaultAgent, assumeYes: true, interactive: false, @@ -413,6 +437,13 @@ export async function runSuperintendentCommand( session: undefined, executeAgent: options.executeAgent, selectedBuilderAgent, + runtime: { + runtime: options.runtime, + runtimeImage: options.runtimeImage, + runtimeTemplate: options.runtimeTemplate, + detach: options.detach, + mountPoeCode: options.mountPoeCode + }, activeStage: () => activeStage, now, stderr @@ -675,6 +706,13 @@ export async function runSuperintendentCommand( session, executeAgent: options.executeAgent, selectedBuilderAgent, + runtime: { + runtime: options.runtime, + runtimeImage: options.runtimeImage, + runtimeTemplate: options.runtimeTemplate, + detach: options.detach, + mountPoeCode: options.mountPoeCode + }, activeStage: () => session.activeStage, now, stderr @@ -870,6 +908,10 @@ function createAgentRunner(options: { session: RunSession | undefined; executeAgent: RunCommandOptions["executeAgent"]; selectedBuilderAgent: string; + runtime: Pick< + RunCommandOptions, + "runtime" | "runtimeImage" | "runtimeTemplate" | "detach" | "mountPoeCode" + >; activeStage: () => RunSession["activeStage"]; now: () => number; stderr: NodeJS.WritableStream; @@ -902,7 +944,12 @@ function createAgentRunner(options: { const onStderr = (chunk: string) => stderrBuffer.push(chunk); try { - const result = await executeAgent(agent, { ...input, onStdout, onStderr }); + const result = await executeAgent(agent, { + ...input, + ...options.runtime, + onStdout, + onStderr + }); if (options.session && result.usage) { options.session.tokensIn += result.usage.inputTokens; @@ -986,6 +1033,11 @@ async function executeSpawnAgent( ...(input.mcpServers ? { mcpServers: input.mcpServers } : {}), ...(input.signal ? { signal: input.signal } : {}), ...(input.logPath ? { logPath: input.logPath } : {}), + ...(input.runtime ? { runtime: input.runtime } : {}), + ...(input.runtimeImage ? { runtimeImage: input.runtimeImage } : {}), + ...(input.runtimeTemplate ? { runtimeTemplate: input.runtimeTemplate } : {}), + ...(input.detach ? { detach: input.detach } : {}), + ...(input.mountPoeCode ? { mountPoeCode: input.mountPoeCode } : {}), ...(tee ? { tee } : {}) }); @@ -1023,6 +1075,11 @@ async function executeSpawnAgentStreaming( ...(input.mode ? { mode: input.mode as "read" | "edit" | "yolo" } : {}), ...(input.mcpServers ? { mcpServers: input.mcpServers } : {}), ...(input.signal ? { signal: input.signal } : {}), + ...(input.runtime ? { runtime: input.runtime } : {}), + ...(input.runtimeImage ? { runtimeImage: input.runtimeImage } : {}), + ...(input.runtimeTemplate ? { runtimeTemplate: input.runtimeTemplate } : {}), + ...(input.detach ? { detach: input.detach } : {}), + ...(input.mountPoeCode ? { mountPoeCode: input.mountPoeCode } : {}), ...(input.onStderr ? { tee: { stderr: { write: input.onStderr } } } : {}) }); diff --git a/packages/superintendent/src/runtime/agent-runner.ts b/packages/superintendent/src/runtime/agent-runner.ts index f20f1359c9..5d73436adc 100644 --- a/packages/superintendent/src/runtime/agent-runner.ts +++ b/packages/superintendent/src/runtime/agent-runner.ts @@ -2,6 +2,7 @@ import "@poe-code/agent-spawn/register-factories"; import { mkdirSync, openSync, writeSync, closeSync } from "node:fs"; import path from "node:path"; import { + type RuntimeOverrideOptions, resolvePoeCommandExecution, runPoeCommand } from "@poe-code/agent-harness-tools"; @@ -20,6 +21,11 @@ export type AutonomousInput = { cwd?: string; mcpServers?: McpSpawnConfig; logPath?: string; + runtime?: RuntimeOverrideOptions["runtime"]; + runtimeImage?: string; + runtimeTemplate?: string; + detach?: boolean; + mountPoeCode?: boolean; }; export type AutonomousOutput = @@ -62,7 +68,12 @@ export async function runAutonomousAgent(input: AutonomousInput): Promise, argv, tool: input.agent, + runtime: { + runtime: input.runtime, + runtimeImage: input.runtimeImage, + runtimeTemplate: input.runtimeTemplate, + detach: input.detach, + mountPoeCode: input.mountPoeCode + }, openSpec: { execution: { wrapForLogTee: false, diff --git a/packages/superintendent/src/runtime/loop.ts b/packages/superintendent/src/runtime/loop.ts index 1048a687f8..afc7ce311b 100644 --- a/packages/superintendent/src/runtime/loop.ts +++ b/packages/superintendent/src/runtime/loop.ts @@ -49,6 +49,11 @@ export interface AgentRunInput { cwd: string; mode?: string; mcpServers?: McpSpawnConfig; + runtime?: "host" | "docker" | "e2b"; + runtimeImage?: string; + runtimeTemplate?: string; + detach?: boolean; + mountPoeCode?: boolean; signal?: AbortSignal; logPath?: string; onStdout?: (chunk: string) => void; diff --git a/src/cli/commands/__snapshots__/runtime-help.test.ts.snap b/src/cli/commands/__snapshots__/runtime-help.test.ts.snap new file mode 100644 index 0000000000..c5c6450e3e --- /dev/null +++ b/src/cli/commands/__snapshots__/runtime-help.test.ts.snap @@ -0,0 +1,111 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`runtime option help > snapshots experiment help 1`] = ` +"Poe - experiment run + +Usage: poe-code experiment run [options] [doc] + +Run an experiment doc through the autonomous experiment loop. + +Arguments: + doc Experiment doc path + +Options: + --agent Override the agent from frontmatter + --max-experiments Limit the number of experiments to run + --tui Show a live dashboard while the experiment is running + --no-tui Disable the live dashboard for this experiment run + --runtime Override runtime backend: host | docker | e2b + (choices: "host", "docker", "e2b") + --runtime-image Override Docker runtime image + --runtime-template Override E2B runtime template id + --detach Run as a detached runtime job + --mount-poe-code Mount the local poe-code checkout into the runtime + -h, --help Display help for command +" +`; + +exports[`runtime option help > snapshots ralph help 1`] = ` +"Poe - ralph run + +Usage: poe-code ralph run [options] [doc] + +Run the selected markdown doc through repeated agent iterations. + +Arguments: + doc Markdown doc path + +Options: + --agent Override the agent from frontmatter + --iterations Override iterations from frontmatter + --tui Show a live dashboard while Ralph is running + --no-tui Disable the live dashboard for this Ralph run + --runtime Override runtime backend: host | docker | e2b + (choices: "host", "docker", "e2b") + --runtime-image Override Docker runtime image + --runtime-template Override E2B runtime template id + --detach Run as a detached runtime job + --mount-poe-code Mount the local poe-code checkout into the runtime + -h, --help Display help for command +" +`; + +exports[`runtime option help > snapshots spawn help 1`] = ` +"Poe - spawn + +Usage: poe-code spawn [options] [prompt] [agentArgs...] + +Run a single prompt through a configured agent CLI. + +Arguments: + agent Agent to spawn (claude-code | claude | codex | + goose | kimi | kimi-cli | opencode | poe-agent) + prompt Prompt text to send, '@path/to/file' to load from + a file, or '-' / stdin + agentArgs Additional arguments forwarded to the agent CLI + +Options: + --model Model identifier override passed to the agent CLI + -C, --cwd Working directory or workspace locator for the + agent CLI + --stdin Read the prompt from stdin + -i, --interactive Launch the agent in interactive TUI mode + --mode Permission mode: yolo | edit | read (default: + yolo) + --mcp-servers MCP server config JSON (or @path/to/file.json): + {name: {command, args?, env?}} + --log-dir Directory override for ACP JSONL spawn logs + --activity-timeout-ms Kill the agent after N ms of inactivity + --runtime Override runtime backend: host | docker | e2b + (choices: "host", "docker", "e2b") + --runtime-image Override Docker runtime image + --runtime-template Override E2B runtime template id + --detach Run as a detached runtime job + --mount-poe-code Mount the local poe-code checkout into the runtime + -h, --help Display help for command +" +`; + +exports[`runtime option help > snapshots superintendent help 1`] = ` +"Poe - poe-code superintendent run + +Usage: poe-code superintendent run [options] [doc] + +Run the full superintendent loop. + +Options: + [doc] Path to the superintendent markdown document + --agent Override the builder agent for this run. Precedence: --agent > plan frontmatter builder.agent. + --runtime Override runtime backend: host, docker, or e2b + --runtime-image Override Docker runtime image + --runtime-template Override E2B runtime template id + --detach [value] Run as a detached runtime job + --mount-poe-code [value] Mount the local poe-code checkout into the runtime + --tui [value] Show a live dashboard while Superintendent is running + +Global options: + --yes Accept defaults, skip prompts + --output Output format (rich, md, json) + -h, --help Show help +" +`; diff --git a/src/cli/commands/experiment-ralph.test.ts b/src/cli/commands/experiment-ralph.test.ts index 5524dea822..784f1fe77b 100644 --- a/src/cli/commands/experiment-ralph.test.ts +++ b/src/cli/commands/experiment-ralph.test.ts @@ -237,6 +237,44 @@ describe("experiment run command", () => { expect(loggerOutput).toContain("Kept: 1"); }); + it("passes runtime flags to the experiment SDK", async () => { + const container = createCliContainer({ + fs: createMemFs({ + "/repo/docs/loop.md": "# Loop" + }), + prompts: vi.fn().mockResolvedValue({}), + env: { cwd, homeDir }, + logger: () => {} + }); + const program = createBaseProgram(); + registerExperimentCommand(program, container); + + await program.parseAsync([ + "node", + "cli", + "experiment", + "run", + "docs/loop.md", + "--agent", + "claude", + "--runtime", + "e2b", + "--runtime-template", + "tpl_123", + "--detach", + "--mount-poe-code" + ]); + + expect(vi.mocked(sdkRunExperiment)).toHaveBeenCalledWith( + expect.objectContaining({ + runtime: "e2b", + runtimeTemplate: "tpl_123", + detach: true, + mountPoeCode: true + }) + ); + }); + it("rejects malformed max-experiments values before starting the loop", async () => { const container = createCliContainer({ fs: createMemFs({ @@ -1631,6 +1669,44 @@ describe("ralph run command", () => { ); }); + it("passes runtime flags to the Ralph SDK", async () => { + const container = createCliContainer({ + fs: createMemFs({ + "/repo/docs/loop.md": "# Loop" + }), + prompts: vi.fn().mockResolvedValue({}), + env: { cwd, homeDir }, + logger: () => {} + }); + const program = createBaseProgram(); + registerRalphCommand(program, container); + + await program.parseAsync([ + "node", + "cli", + "ralph", + "run", + "docs/loop.md", + "--agent", + "claude", + "--iterations", + "5", + "--runtime", + "docker", + "--runtime-image", + "poe-code:test", + "--detach" + ]); + + expect(vi.mocked(sdkRunRalph)).toHaveBeenCalledWith( + expect.objectContaining({ + runtime: "docker", + runtimeImage: "poe-code:test", + detach: true + }) + ); + }); + it("reads agent and iterations from frontmatter and skips prompts", async () => { const container = createCliContainer({ fs: createMemFs({ diff --git a/src/cli/commands/experiment.ts b/src/cli/commands/experiment.ts index 731e2bd203..fb1aa39bde 100644 --- a/src/cli/commands/experiment.ts +++ b/src/cli/commands/experiment.ts @@ -50,6 +50,7 @@ import { registerDashboardQuitCommands, shouldUseInteractiveDashboard } from "./dashboard-loop-shared.js"; +import { addRuntimeOptions, pickRuntimeOptions, type RuntimeCliOptions } from "./runtime-options.js"; const DEFAULT_EXPERIMENT_AGENT = "claude-code"; const DEFAULT_EXPERIMENT_SCOPE: SkillScope = "local"; @@ -67,6 +68,7 @@ type ExperimentDashboardRunOptions = { docPath: string; maxExperiments?: number; runOptions: Parameters[0]; + runtimeOptions: RuntimeCliOptions; }; function resolveExperimentPaths( @@ -238,6 +240,7 @@ function formatExperimentStageLabel(index: number): string { function createExperimentDashboardRunAgent(options: { appendOutput: (kind: "tool" | "error", message: string) => void; activeStage: () => string; + runtimeOptions: RuntimeCliOptions; }): NonNullable { return async (input) => { const errorBuffer = createDashboardLineBuffer((line) => { @@ -255,6 +258,7 @@ function createExperimentDashboardRunAgent(options: { cwd: input.cwd, model: input.model, mode: "yolo", + ...options.runtimeOptions, ...(input.signal ? { signal: input.signal } : {}), useStdin: true, tee: { @@ -348,7 +352,8 @@ async function runExperimentWithDashboard( const runAgent = createExperimentDashboardRunAgent({ appendOutput, - activeStage: () => formatExperimentStageLabel(currentExperimentIndex) + activeStage: () => formatExperimentStageLabel(currentExperimentIndex), + runtimeOptions: options.runtimeOptions }); try { @@ -609,14 +614,16 @@ export function registerExperimentCommand(program: Command, container: CliContai .description("Run autonomous experiment loop workflows.") .addHelpCommand(false); - experiment + const run = experiment .command("run") .description("Run an experiment doc through the autonomous experiment loop.") .argument("[doc]", "Experiment doc path") .option("--agent ", "Override the agent from frontmatter") .option("--max-experiments ", "Limit the number of experiments to run") .option("--tui", "Show a live dashboard while the experiment is running") - .option("--no-tui", "Disable the live dashboard for this experiment run") + .option("--no-tui", "Disable the live dashboard for this experiment run"); + + addRuntimeOptions(run) .action(async function (this: Command, docArg?: string) { const flags = resolveCommandFlags(program); const resources = createExecutionResources(container, flags, "experiment:run"); @@ -624,7 +631,8 @@ export function registerExperimentCommand(program: Command, container: CliContai agent?: string; maxExperiments?: string; tui?: boolean; - }>(); + } & RuntimeCliOptions>(); + const runtimeOptions = pickRuntimeOptions(options); resources.logger.intro("experiment run"); @@ -659,6 +667,7 @@ export function registerExperimentCommand(program: Command, container: CliContai cwd: container.env.cwd, homeDir: container.env.homeDir, docPath, + ...runtimeOptions, ...(maxExperiments !== undefined ? { maxExperiments } : {}), onExperimentStart(index, currentAgent) { resources.logger.info(`Experiment ${index} (${currentAgent})`); @@ -697,7 +706,8 @@ export function registerExperimentCommand(program: Command, container: CliContai agent, docPath, maxExperiments, - runOptions + runOptions, + runtimeOptions }) : await sdkRunExperiment(runOptions); diff --git a/src/cli/commands/ralph.ts b/src/cli/commands/ralph.ts index b31647eb3a..f4c8262458 100644 --- a/src/cli/commands/ralph.ts +++ b/src/cli/commands/ralph.ts @@ -40,6 +40,7 @@ import { registerDashboardQuitCommands, shouldUseInteractiveDashboard } from "./dashboard-loop-shared.js"; +import { addRuntimeOptions, pickRuntimeOptions, type RuntimeCliOptions } from "./runtime-options.js"; const DEFAULT_RALPH_AGENT = "claude-code"; const DEFAULT_RALPH_ITERATIONS = 3; @@ -49,6 +50,7 @@ type RalphDashboardRunOptions = { docPath: string; maxIterations: number; runOptions: RalphRunOptions; + runtimeOptions: RuntimeCliOptions; }; function formatRalphAgentSummary(agent: string | string[]): string { @@ -82,6 +84,7 @@ function formatRalphStageLabel(iteration: number): string { function createRalphDashboardRunAgent(options: { appendOutput: (kind: "tool" | "error", message: string) => void; activeStage: () => string; + runtimeOptions: RuntimeCliOptions; }): NonNullable { return async (input) => { const errorBuffer = createDashboardLineBuffer((line) => { @@ -99,6 +102,7 @@ function createRalphDashboardRunAgent(options: { cwd: input.cwd, model: input.model, mode: "yolo", + ...options.runtimeOptions, ...(input.signal ? { signal: input.signal } : {}), useStdin: true, tee: { @@ -197,7 +201,8 @@ async function runRalphWithDashboard(options: RalphDashboardRunOptions): Promise ...options.runOptions, runAgent: createRalphDashboardRunAgent({ appendOutput, - activeStage: () => currentStage + activeStage: () => currentStage, + runtimeOptions: options.runtimeOptions }), signal: abortController.signal, onIterationStart(iteration, totalIterations, currentAgent) { @@ -667,14 +672,16 @@ export function registerRalphCommand(program: Command, container: CliContainer): } }); - ralph + const run = ralph .command("run") .description("Run the selected markdown doc through repeated agent iterations.") .argument("[doc]", "Markdown doc path") .option("--agent ", "Override the agent from frontmatter") .option("--iterations ", "Override iterations from frontmatter") .option("--tui", "Show a live dashboard while Ralph is running") - .option("--no-tui", "Disable the live dashboard for this Ralph run") + .option("--no-tui", "Disable the live dashboard for this Ralph run"); + + addRuntimeOptions(run) .action(async function (this: Command, docArg?: string) { const flags = resolveCommandFlags(program); const resources = createExecutionResources(container, flags, "ralph:run"); @@ -682,7 +689,8 @@ export function registerRalphCommand(program: Command, container: CliContainer): agent?: string; iterations?: string; tui?: boolean; - }>(); + } & RuntimeCliOptions>(); + const runtimeOptions = pickRuntimeOptions(options); resources.logger.intro("ralph run"); @@ -723,7 +731,8 @@ export function registerRalphCommand(program: Command, container: CliContainer): cwd: container.env.cwd, homeDir: container.env.homeDir, docPath, - maxIterations + maxIterations, + ...runtimeOptions }; const useDashboard = shouldUseInteractiveDashboard(options.tui ?? commandConfig.tui); const result = useDashboard @@ -731,7 +740,8 @@ export function registerRalphCommand(program: Command, container: CliContainer): agent, docPath, maxIterations, - runOptions + runOptions, + runtimeOptions }) : await sdkRunRalph({ ...runOptions, diff --git a/src/cli/commands/runtime-help.test.ts b/src/cli/commands/runtime-help.test.ts new file mode 100644 index 0000000000..3af33aa363 --- /dev/null +++ b/src/cli/commands/runtime-help.test.ts @@ -0,0 +1,83 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { CommanderError } from "commander"; +import { Volume, createFsFromVolume } from "memfs"; +import { createProgram } from "../program.js"; +import type { FileSystem } from "../utils/file-system.js"; + +function createMemFs(): FileSystem { + const volume = new Volume(); + volume.mkdirSync("/home/test", { recursive: true }); + return createFsFromVolume(volume).promises as unknown as FileSystem; +} + +function stripAnsi(input: string): string { + let result = ""; + let index = 0; + + while (index < input.length) { + const char = input[index]; + if (char === "\u001b" && input[index + 1] === "[") { + index += 2; + while (index < input.length && input[index] !== "m") { + index += 1; + } + index += 1; + continue; + } + result += char; + index += 1; + } + + return result; +} + +async function renderHelp(argv: string[]): Promise { + process.argv = ["node", "/usr/local/bin/poe-code", ...argv]; + const program = createProgram({ + fs: createMemFs(), + prompts: vi.fn().mockResolvedValue({}), + env: { + cwd: "/repo", + homeDir: "/home/test", + variables: {} + }, + logger: () => {} + }); + const chunks: string[] = []; + const stdoutWrite = vi + .spyOn(process.stdout, "write") + .mockImplementation(((chunk: unknown) => { + chunks.push(String(chunk)); + return true; + }) as unknown as typeof process.stdout.write); + + try { + await program.parseAsync(["node", "cli", ...argv]); + } catch (error) { + if (!(error instanceof CommanderError) || error.code !== "commander.helpDisplayed") { + throw error; + } + } finally { + stdoutWrite.mockRestore(); + } + + return stripAnsi(chunks.join("")); +} + +describe("runtime option help", () => { + const originalArgv = [...process.argv]; + + afterEach(() => { + vi.restoreAllMocks(); + process.argv = [...originalArgv]; + }); + + it.each([ + ["spawn", ["spawn", "--help"]], + ["experiment", ["experiment", "run", "--help"]], + ["ralph", ["ralph", "run", "--help"]], + ["superintendent", ["superintendent", "run", "--help"]] + ])("snapshots %s help", async (_name, argv) => { + await expect(renderHelp(argv)).resolves.toMatchSnapshot(); + }); +}); diff --git a/src/cli/commands/runtime-options.ts b/src/cli/commands/runtime-options.ts new file mode 100644 index 0000000000..9ce256a368 --- /dev/null +++ b/src/cli/commands/runtime-options.ts @@ -0,0 +1,35 @@ +import type { Command } from "commander"; +import { Option } from "commander"; + +export type RuntimeCliOptions = { + runtime?: "host" | "docker" | "e2b"; + runtimeImage?: string; + runtimeTemplate?: string; + detach?: boolean; + mountPoeCode?: boolean; +}; + +export function addRuntimeOptions(command: TCommand): TCommand { + return command + .addOption( + new Option("--runtime ", "Override runtime backend: host | docker | e2b").choices([ + "host", + "docker", + "e2b" + ]) + ) + .option("--runtime-image ", "Override Docker runtime image") + .option("--runtime-template ", "Override E2B runtime template id") + .option("--detach", "Run as a detached runtime job") + .option("--mount-poe-code", "Mount the local poe-code checkout into the runtime"); +} + +export function pickRuntimeOptions(options: RuntimeCliOptions): RuntimeCliOptions { + return { + ...(options.runtime ? { runtime: options.runtime } : {}), + ...(options.runtimeImage ? { runtimeImage: options.runtimeImage } : {}), + ...(options.runtimeTemplate ? { runtimeTemplate: options.runtimeTemplate } : {}), + ...(options.detach ? { detach: true } : {}), + ...(options.mountPoeCode ? { mountPoeCode: true } : {}) + }; +} diff --git a/src/cli/commands/spawn-command.test.ts b/src/cli/commands/spawn-command.test.ts index d3878e4faf..8e3ba4141a 100644 --- a/src/cli/commands/spawn-command.test.ts +++ b/src/cli/commands/spawn-command.test.ts @@ -274,6 +274,46 @@ describe("spawn command", () => { expect(logs.some((line) => line.includes("Final output"))).toBe(true); }); + it("passes runtime flags to the spawn SDK", async () => { + vi.mocked(sdkSpawn).mockImplementation(() => ({ + events: emptyAsyncIterable(), + result: Promise.resolve({ stdout: "", stderr: "", exitCode: 0 }) + })); + + const { runner } = createCommandRunnerStub(); + const program = createProgram({ + fs, + prompts: vi.fn().mockResolvedValue({}), + env: { cwd, homeDir }, + commandRunner: runner, + logger: () => {} + }); + + await program.parseAsync([ + "node", + "cli", + "spawn", + "claude", + "--runtime", + "docker", + "--runtime-image", + "poe-code:test", + "--detach", + "--mount-poe-code", + "hello" + ]); + + expect(sdkSpawn).toHaveBeenCalledWith( + "claude-code", + expect.objectContaining({ + runtime: "docker", + runtimeImage: "poe-code:test", + detach: true, + mountPoeCode: true + }) + ); + }); + it("emits ACP NDJSON plus a final spawn_result event in json mode", async () => { process.env.OUTPUT_FORMAT = "json"; resetOutputFormatCache(); diff --git a/src/cli/commands/spawn.ts b/src/cli/commands/spawn.ts index bc9024dc08..db59247d6f 100644 --- a/src/cli/commands/spawn.ts +++ b/src/cli/commands/spawn.ts @@ -36,6 +36,7 @@ import { spawnAutonomous } from "../../sdk/autonomous.js"; import type { FileSystem } from "../../utils/file-system.js"; import { OperationCancelledError, ValidationError } from "../errors.js"; import { resolveSpawnWorkspace } from "../../workspace/resolve-spawn-workspace.js"; +import { addRuntimeOptions, pickRuntimeOptions, type RuntimeCliOptions } from "./runtime-options.js"; export interface CustomSpawnHandlerContext { container: CliContainer; @@ -64,7 +65,7 @@ export function registerSpawnCommand( const serviceList = listSpawnServiceNames(spawnServices, extraServices); const serviceDescription = `Agent to spawn${formatServiceList(serviceList)}`; - program + const spawnCommand = program .command("spawn") .alias("s") .description("Run a single prompt through a configured agent CLI.") @@ -85,7 +86,9 @@ export function registerSpawnCommand( "--activity-timeout-ms ", "Kill the agent after N ms of inactivity", (value: string) => parsePositiveInt(value, "--activity-timeout-ms") - ) + ); + + addRuntimeOptions(spawnCommand) .argument("", serviceDescription) .argument("[prompt]", "Prompt text to send, '@path/to/file' to load from a file, or '-' / stdin") .argument("[agentArgs...]", "Additional arguments forwarded to the agent CLI") @@ -106,7 +109,8 @@ export function registerSpawnCommand( mcpConfig?: string; logDir?: string; activityTimeoutMs?: number; - }>(); + } & RuntimeCliOptions>(); + const runtimeOptions = pickRuntimeOptions(commandOptions); const shouldEmitUiOutput = resolveOutputFormat() !== "json"; const rawMcpInput = commandOptions.mcpServers ?? commandOptions.mcpConfig; const mcpInput = await resolveMcpSpawnInput(rawMcpInput, container.fs, container.env.cwd); @@ -179,6 +183,7 @@ export function registerSpawnCommand( args: forwardedArgs, model, mode: commandOptions.mode as SpawnMode | undefined, + ...runtimeOptions, ...(mcpServers ? { mcpServers } : {}), cwd: cwdOverride }); @@ -195,6 +200,7 @@ export function registerSpawnCommand( cwd: cwdOverride, logDir: commandOptions.logDir, activityTimeoutMs: commandOptions.activityTimeoutMs, + ...runtimeOptions, useStdin: shouldReadFromStdin }; @@ -289,7 +295,8 @@ export function registerSpawnCommand( ...(spawnOptions.logDir !== undefined ? { logDir: spawnOptions.logDir } : {}), ...(spawnOptions.activityTimeoutMs !== undefined ? { activityTimeoutMs: spawnOptions.activityTimeoutMs } - : {}) + : {}), + ...runtimeOptions }); process.exitCode = final.exitCode; diff --git a/src/providers/spawn-options.ts b/src/providers/spawn-options.ts index 8d337d0330..a7053e1209 100644 --- a/src/providers/spawn-options.ts +++ b/src/providers/spawn-options.ts @@ -1,4 +1,5 @@ import type { McpSpawnConfig, SpawnMode } from "@poe-code/agent-spawn"; +import type { RuntimeOverrideOptions } from "@poe-code/agent-harness-tools"; export interface SpawnCommandOptions { prompt: string; @@ -11,6 +12,11 @@ export interface SpawnCommandOptions { cwd?: string; useStdin?: boolean; interactive?: boolean; + runtime?: RuntimeOverrideOptions["runtime"]; + runtimeImage?: string; + runtimeTemplate?: string; + detach?: boolean; + mountPoeCode?: boolean; } export type ProviderSpawnOptions< diff --git a/src/sdk/experiment.ts b/src/sdk/experiment.ts index d94eeaa0d2..1d991a14e1 100644 --- a/src/sdk/experiment.ts +++ b/src/sdk/experiment.ts @@ -75,6 +75,11 @@ export async function runExperiment(options: ExperimentRunOptions): Promise { const result = await runRalph({ cwd: "/repo", homeDir: "/home/test", - docPath: "docs/loop.md" + docPath: "docs/loop.md", + runtime: "docker", + runtimeImage: "poe-code:test", + detach: true }); expect(result).toEqual(expectedResult); @@ -102,7 +105,10 @@ describe("SDK ralph", () => { prompt: "Improve the doc", cwd: "/repo", model: "gpt-5.2", - mode: "yolo" + mode: "yolo", + runtime: "docker", + runtimeImage: "poe-code:test", + detach: true }); expect(agentResult).toEqual({ stdout: "done", diff --git a/src/sdk/ralph.ts b/src/sdk/ralph.ts index fea511ac74..1721bc05f0 100644 --- a/src/sdk/ralph.ts +++ b/src/sdk/ralph.ts @@ -24,6 +24,11 @@ export async function runRalph( cwd: input.cwd, model: input.model, mode: "yolo", + ...(options.runtime ? { runtime: options.runtime } : {}), + ...(options.runtimeImage ? { runtimeImage: options.runtimeImage } : {}), + ...(options.runtimeTemplate ? { runtimeTemplate: options.runtimeTemplate } : {}), + ...(options.detach ? { detach: options.detach } : {}), + ...(options.mountPoeCode ? { mountPoeCode: options.mountPoeCode } : {}), ...(input.signal ? { signal: input.signal } : {}) }); }); diff --git a/src/sdk/sdk-core.test.ts b/src/sdk/sdk-core.test.ts index 1d530be0d2..3188e52ef6 100644 --- a/src/sdk/sdk-core.test.ts +++ b/src/sdk/sdk-core.test.ts @@ -689,6 +689,9 @@ describe("SDK experiment", () => { docPath: "docs/loop.md", agent: "codex", model: "gpt-5.2", + runtime: "e2b", + runtimeTemplate: "tpl_123", + mountPoeCode: true, maxExperiments: 3, onExperimentStart, onExperimentComplete @@ -720,7 +723,10 @@ describe("SDK experiment", () => { prompt: "Improve the metric", cwd: "/repo", model: "gpt-5.2", - mode: "yolo" + mode: "yolo", + runtime: "e2b", + runtimeTemplate: "tpl_123", + mountPoeCode: true }); expect(agentResult).toEqual({ stdout: "done", diff --git a/src/sdk/spawn.test.ts b/src/sdk/spawn.test.ts index 985e4ba34f..43c684b473 100644 --- a/src/sdk/spawn.test.ts +++ b/src/sdk/spawn.test.ts @@ -812,6 +812,61 @@ describe("SDK spawn()", () => { expect(spawnCore).not.toHaveBeenCalled(); }); + it("uses runtime-aware streaming flow when ACP agents receive runtime overrides", async () => { + vi.mocked(getAcpSpawnConfig).mockReturnValue({ + kind: "acp", + agentId: "opencode", + acpArgs: ["acp"], + skipAuth: true + } as any); + vi.mocked(getSpawnConfig).mockReturnValue({ + kind: "cli", + agentId: "opencode", + adapter: "opencode" + } as any); + vi.mocked(spawnStreaming).mockImplementation(() => ({ + events: (async function* () { + yield { event: "agent_message", text: "streamed" }; + })(), + done: Promise.resolve({ + stdout: "", + stderr: "", + exitCode: 0 + }) + })); + + const { events, result } = spawn("opencode", "test prompt", { + runtime: "docker", + runtimeImage: "poe-code:test", + detach: true, + mountPoeCode: true + }); + + const received: unknown[] = []; + for await (const event of events) { + received.push(event); + } + + expect(received).toEqual([{ event: "agent_message", text: "streamed" }]); + await expect(result).resolves.toEqual({ + stdout: "", + stderr: "", + exitCode: 0 + }); + + expect(spawnAcp).not.toHaveBeenCalled(); + expect(spawnStreaming).toHaveBeenCalledWith( + expect.objectContaining({ + agentId: "opencode", + prompt: "test prompt", + runtime: "docker", + runtimeImage: "poe-code:test", + detach: true, + mountPoeCode: true + }) + ); + }); + it("composes ACP middlewares in SDK streaming path", async () => { vi.mocked(getSpawnConfig).mockReturnValue({ kind: "cli", diff --git a/src/sdk/spawn.ts b/src/sdk/spawn.ts index 709a94e509..4ef7f6d034 100644 --- a/src/sdk/spawn.ts +++ b/src/sdk/spawn.ts @@ -128,6 +128,8 @@ export function spawn( }; const resolveModel = async () => options.model ?? await resolveConfiguredModel(getContainer(), service); + const runtimeOverrides = pickRuntimeOverrides(options); + const hasRuntimeOverrides = Object.keys(runtimeOverrides).length > 0; if (options.interactive) { resolveEventsOnce(emptyEvents); @@ -139,6 +141,7 @@ export function spawn( mode: options.mode, signal: options.signal, args: options.args, + ...runtimeOverrides, ...(resolvedMcpServers ? { mcpServers: resolvedMcpServers } : {}) }); return { @@ -150,7 +153,7 @@ export function spawn( } const acpSpawnConfig = getAcpSpawnConfig(service); - if (acpSpawnConfig) { + if (acpSpawnConfig && !hasRuntimeOverrides) { const model = await resolveModel(); const { events: rawEvents, done } = spawnAcp({ agentId: service, @@ -160,6 +163,7 @@ export function spawn( mode: options.mode, mcpServers: options.mcpServers, signal: options.signal, + ...runtimeOverrides }); const middlewareContext: AcpSpawnContext = { @@ -213,6 +217,7 @@ export function spawn( mode: options.mode, args: options.args, signal: options.signal, + ...runtimeOverrides, ...(resolvedMcpServers ? { mcpServers: resolvedMcpServers } : {}), ...(options.tee ? { tee: options.tee } : {}), ...(options.activityTimeoutMs !== undefined @@ -267,6 +272,7 @@ export function spawn( mode: options.mode, args: options.args, signal: options.signal, + ...runtimeOverrides, ...(resolvedMcpServers ? { mcpServers: resolvedMcpServers } : {}), ...(options.tee ? { tee: options.tee } : {}), ...(options.activityTimeoutMs !== undefined @@ -287,6 +293,7 @@ export function spawn( model, mode: options.mode, args: options.args, + ...runtimeOverrides, ...(resolvedMcpServers ? { mcpServers: resolvedMcpServers } : {}), useStdin: options.useStdin ?? false }); @@ -317,6 +324,21 @@ function getCapturedUsage(usage: SpawnUsage | undefined): SpawnUsage | undefined return undefined; } +function pickRuntimeOverrides( + options: Pick< + SpawnOptions, + "runtime" | "runtimeImage" | "runtimeTemplate" | "detach" | "mountPoeCode" + > +): Pick { + return { + ...(options.runtime ? { runtime: options.runtime } : {}), + ...(options.runtimeImage ? { runtimeImage: options.runtimeImage } : {}), + ...(options.runtimeTemplate ? { runtimeTemplate: options.runtimeTemplate } : {}), + ...(options.detach ? { detach: options.detach } : {}), + ...(options.mountPoeCode ? { mountPoeCode: options.mountPoeCode } : {}) + }; +} + /** * Spawns an agent and renders ACP events to stdout with pretty formatting. * diff --git a/src/sdk/types.ts b/src/sdk/types.ts index 0197296a81..7ce7de5714 100644 --- a/src/sdk/types.ts +++ b/src/sdk/types.ts @@ -1,3 +1,4 @@ +import type { RuntimeOverrideOptions } from "@poe-code/agent-harness-tools"; import type { McpSpawnConfig, SessionResult, SpawnMode } from "@poe-code/agent-spawn"; /** @@ -38,6 +39,16 @@ export interface SpawnOptions { * Disabled when undefined. */ activityTimeoutMs?: number; + /** Runtime backend override: host, docker, or e2b */ + runtime?: RuntimeOverrideOptions["runtime"]; + /** Docker image override for docker runtime */ + runtimeImage?: string; + /** E2B template id override for e2b runtime */ + runtimeTemplate?: string; + /** Run as a detached runtime job when supported */ + detach?: boolean; + /** Mount the local poe-code checkout into the runtime for development */ + mountPoeCode?: boolean; } /** From c7a86b33941ad4c223b95a3867b0978e735dce5b Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 19:03:53 -0500 Subject: [PATCH 016/111] feat: add docker execution env --- docs/plans/e2b-integration.md | 6 +- docs/plans/e2b-integration.md.lock | 2 +- .../src/execution-env.test.ts | 4 +- .../agent-harness-tools/src/execution-env.ts | 5 +- .../src/poe-command-execution.ts | 4 +- .../agent-spawn/src/register-factories.ts | 3 +- .../docker-execution-env.integration.test.ts | 74 +++ .../src/docker/docker-execution-env.test.ts | 446 +++++++++++++++++ .../src/docker/docker-execution-env.ts | 460 ++++++++++++++++++ packages/process-runner/src/index.test.ts | 22 + packages/process-runner/src/index.ts | 3 + packages/process-runner/src/types.ts | 18 + 12 files changed, 1038 insertions(+), 9 deletions(-) create mode 100644 packages/process-runner/src/docker/docker-execution-env.integration.test.ts create mode 100644 packages/process-runner/src/docker/docker-execution-env.test.ts create mode 100644 packages/process-runner/src/docker/docker-execution-env.ts diff --git a/docs/plans/e2b-integration.md b/docs/plans/e2b-integration.md index ab47b33e02..5206c42299 100644 --- a/docs/plans/e2b-integration.md +++ b/docs/plans/e2b-integration.md @@ -345,7 +345,7 @@ tasks: status: implement: done test: done - commit: open + commit: done - id: docker-factory-and-build title: Add dockerExecutionEnvFactory with content-addressed image build @@ -372,8 +372,8 @@ tasks: For the dockerfile build path, the build is done by spawning the docker CLI through the host runner — no docker SDK dep. status: - implement: open - test: open + implement: done + test: done commit: open - id: cli-runtime-init-build-templates diff --git a/docs/plans/e2b-integration.md.lock b/docs/plans/e2b-integration.md.lock index bea39f3571..6432db5305 100644 --- a/docs/plans/e2b-integration.md.lock +++ b/docs/plans/e2b-integration.md.lock @@ -1 +1 @@ -{"pid":82216,"host":"m5mb-kjopek","acquiredAt":"2026-05-03T23:54:21.246Z"} \ No newline at end of file +{"pid":82216,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T00:02:46.660Z"} \ No newline at end of file diff --git a/packages/agent-harness-tools/src/execution-env.test.ts b/packages/agent-harness-tools/src/execution-env.test.ts index 779a9767c5..0e7cd3a604 100644 --- a/packages/agent-harness-tools/src/execution-env.test.ts +++ b/packages/agent-harness-tools/src/execution-env.test.ts @@ -78,8 +78,8 @@ describe("execution env registry", () => { expect(branchSites).toMatchInlineSnapshot(` [ - "execution-env.ts:86:const factory = executionEnvFactories.get(runtime.type);", - "execution-env.ts:89:\`No execution environment factory registered for runtime type "\${runtime.type}".\`", + "execution-env.ts:89:const factory = executionEnvFactories.get(runtime.type);", + "execution-env.ts:92:\`No execution environment factory registered for runtime type "\${runtime.type}".\`", ] `); }); diff --git a/packages/agent-harness-tools/src/execution-env.ts b/packages/agent-harness-tools/src/execution-env.ts index 19c5419137..f166412492 100644 --- a/packages/agent-harness-tools/src/execution-env.ts +++ b/packages/agent-harness-tools/src/execution-env.ts @@ -1,5 +1,6 @@ import type { RunnerScope, RuntimeConfig } from "@poe-code/poe-code-config"; -import type { RunHandle, RunSpec } from "@poe-code/process-runner"; +import type { RunHandle, Runner, RunSpec } from "@poe-code/process-runner"; +import type { StateManager } from "@poe-code/poe-code-config"; export type { RuntimeConfig } from "@poe-code/poe-code-config"; export type { RunHandle, RunSpec } from "@poe-code/process-runner"; @@ -18,6 +19,8 @@ export interface OpenSpec { cwd: string; runtime: RuntimeConfig; runner?: RunnerScope; + state?: StateManager; + hostRunner?: Runner; env: Record; uploadIgnoreFiles: string[]; jobLabel: { tool: string; argv: string[] }; diff --git a/packages/agent-harness-tools/src/poe-command-execution.ts b/packages/agent-harness-tools/src/poe-command-execution.ts index 57911eb009..e457c20059 100644 --- a/packages/agent-harness-tools/src/poe-command-execution.ts +++ b/packages/agent-harness-tools/src/poe-command-execution.ts @@ -46,15 +46,17 @@ export function resolvePoeCommandExecution(input: { const config = applyRuntimeOverrides(loadRuntimeConfig(input.cwd, homeDir), input.runtime, input.cwd); const resolved = resolveRuntime({ cwd: input.cwd, config }); const factory = selectExecutionEnv(resolved.runtime); + const state = input.context?.state ?? loadState(homeDir); return { factory, detach: factory.supportsDetach === true && config.runner.detach, - state: input.context?.state ?? loadState(homeDir), + state, openSpec: { cwd: input.cwd, runtime: resolved.runtime, runner: config.runner, + state, env: input.env, uploadIgnoreFiles: config.runner.workspace?.exclude ?? [], jobLabel: { diff --git a/packages/agent-spawn/src/register-factories.ts b/packages/agent-spawn/src/register-factories.ts index 6230a97c52..13939d3d3b 100644 --- a/packages/agent-spawn/src/register-factories.ts +++ b/packages/agent-spawn/src/register-factories.ts @@ -1,9 +1,10 @@ import { spawn as spawnChildProcess } from "node:child_process"; import { registerExecutionEnvFactory } from "@poe-code/agent-harness-tools"; import type { ExecutionEnvFactory, OpenedEnv, RunSpec } from "@poe-code/agent-harness-tools"; -import { hostExecutionEnvFactory } from "@poe-code/process-runner"; +import { dockerExecutionEnvFactory, hostExecutionEnvFactory } from "@poe-code/process-runner"; registerExecutionEnvFactory(hostExecutionEnvFactory); +registerExecutionEnvFactory(dockerExecutionEnvFactory); if (process.env.VITEST === "true") { registerExecutionEnvFactory(createTestHostExecutionEnvFactory()); diff --git a/packages/process-runner/src/docker/docker-execution-env.integration.test.ts b/packages/process-runner/src/docker/docker-execution-env.integration.test.ts new file mode 100644 index 0000000000..d6959e5de4 --- /dev/null +++ b/packages/process-runner/src/docker/docker-execution-env.integration.test.ts @@ -0,0 +1,74 @@ +import { spawnSync } from "node:child_process"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { describe, expect, it } from "vitest"; +import { dockerExecutionEnvFactory } from "./docker-execution-env.js"; +import type { OpenSpec } from "../types.js"; + +const dockerAvailable = spawnSync("docker", ["info"], { + stdio: "ignore", + timeout: 3000 +}).status === 0; + +describe.skipIf(!dockerAvailable)("dockerExecutionEnvFactory integration", () => { + it("builds a local Dockerfile image and copies workspace changes back", async () => { + const cwd = mkdtempSync(path.join(tmpdir(), "poe-docker-env-")); + const dockerfilePath = path.join(cwd, "Dockerfile"); + writeFileSync(dockerfilePath, "FROM alpine:latest\nWORKDIR /workspace\n", "utf8"); + writeFileSync(path.join(cwd, "input.txt"), "from-host", "utf8"); + + const state = createMemoryState(); + const env = await dockerExecutionEnvFactory.open({ + cwd, + runtime: { + type: "docker", + dockerfile: "Dockerfile", + build_context: ".", + build_args: {}, + mounts: [] + }, + state, + env: {}, + uploadIgnoreFiles: [], + jobLabel: { + tool: "sh", + argv: ["sh", "-c", "cat input.txt > output.txt"] + } + } satisfies OpenSpec); + + try { + await env.uploadWorkspace(); + const handle = env.exec({ + command: "sh", + args: ["-c", "cat input.txt > output.txt"], + cwd, + stdout: "pipe", + stderr: "pipe" + }); + + await expect(handle.result).resolves.toEqual({ exitCode: 0 }); + await env.downloadWorkspace({ conflictPolicy: "overwrite" }); + expect(readFileSync(path.join(cwd, "output.txt"), "utf8")).toBe("from-host"); + expect(state.entries).toHaveLength(1); + } finally { + await env.close(); + rmSync(cwd, { recursive: true, force: true }); + } + }, 120_000); +}); + +function createMemoryState() { + const entries: unknown[] = []; + return { + entries, + templates: { + async get() { + return null; + }, + async put(_backend: string, entry: unknown) { + entries.push(entry); + } + } + }; +} diff --git a/packages/process-runner/src/docker/docker-execution-env.test.ts b/packages/process-runner/src/docker/docker-execution-env.test.ts new file mode 100644 index 0000000000..90e06e8dde --- /dev/null +++ b/packages/process-runner/src/docker/docker-execution-env.test.ts @@ -0,0 +1,446 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { readFile } from "node:fs/promises"; +import { Readable } from "node:stream"; +import { detectEngine } from "./engine.js"; +import { createHostRunner } from "../host/host-runner.js"; +import type { OpenSpec, RunHandle, RunSpec, Runner } from "../types.js"; + +vi.mock("node:fs/promises", () => ({ + readFile: vi.fn() +})); + +vi.mock("./engine.js", () => ({ + detectEngine: vi.fn(() => "docker") +})); + +vi.mock("./context.js", async () => { + const actual = await vi.importActual("./context.js"); + + return { + ...actual, + detectContext: vi.fn(() => null) + }; +}); + +vi.mock("../host/host-runner.js", () => ({ + createHostRunner: vi.fn() +})); + +describe("dockerExecutionEnvFactory", () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(detectEngine).mockReturnValue("docker"); + }); + + it("opens a persistent container from a configured image with runtime mounts", async () => { + const runner = createCapturingRunner([ + { exitCode: 0, stdout: ["container-from-image\n"] } + ]); + const state = createState(null); + const { dockerExecutionEnvFactory } = await import("./docker-execution-env.js"); + + const env = await dockerExecutionEnvFactory.open( + createOpenSpec({ + runtime: { + type: "docker", + image: "node:22", + build_args: {}, + mounts: [{ source: "/repo", target: "/workspace", readonly: true }] + }, + state, + hostRunner: runner + }) + ); + + expect(env.id).toBe("container-from-image"); + expect(readFile).not.toHaveBeenCalled(); + expect(state.getCalls).toEqual([]); + expect(state.putCalls).toEqual([]); + expect(runner.specs[0]).toMatchObject({ + command: "docker", + args: [ + "run", + "-d", + "-i", + "--name", + expect.stringMatching(/^poe-env-/), + "-v", + "/repo:/workspace:ro", + "node:22", + "sh", + "-c", + "while :; do sleep 3600; done" + ] + }); + }); + + it("uses the configured container engine instead of auto-detecting", async () => { + const runner = createCapturingRunner([ + { exitCode: 0 }, + { exitCode: 0, stdout: ["podman-container\n"] } + ]); + vi.mocked(readFile).mockResolvedValue(Buffer.from("FROM alpine\n")); + const { dockerExecutionEnvFactory } = await import("./docker-execution-env.js"); + + await dockerExecutionEnvFactory.open( + createOpenSpec({ + runtime: { + type: "docker", + dockerfile: "Dockerfile", + build_context: ".", + build_args: {}, + mounts: [], + engine: "podman" + }, + hostRunner: runner + }) + ); + + expect(detectEngine).not.toHaveBeenCalled(); + expect(runner.specs[0]?.command).toBe("podman"); + expect(runner.specs[1]?.command).toBe("podman"); + expect(runner.specs[1]?.args?.[0]).toBe("run"); + }); + + it("uses a cached dockerfile image when the template hash exists", async () => { + const runner = createCapturingRunner([ + { exitCode: 0, stdout: ["cached-container\n"] } + ]); + vi.mocked(readFile).mockResolvedValue(Buffer.from("FROM alpine\n")); + const state = createState({ + image: "poe-code/local:cached", + hash: "unused", + runtime_type: "docker", + dockerfile_path: "/repo/.poe-code/Dockerfile", + built_at: "2026-05-03T00:00:00.000Z" + }); + const { dockerExecutionEnvFactory } = await import("./docker-execution-env.js"); + + const env = await dockerExecutionEnvFactory.open( + createOpenSpec({ + runtime: { + type: "docker", + dockerfile: ".poe-code/Dockerfile", + build_context: ".", + build_args: { B: "2", A: "1" }, + mounts: [] + }, + state, + hostRunner: runner + }) + ); + + expect(env.id).toBe("cached-container"); + expect(state.getCalls).toEqual([{ backend: "docker", hash: expect.any(String) }]); + expect(state.putCalls).toEqual([]); + expect(runner.specs).toHaveLength(1); + expect(runner.specs[0]?.args).toContain("poe-code/local:cached"); + }); + + it("builds and caches a dockerfile image on template cache miss with sorted build args", async () => { + const runner = createCapturingRunner([ + { exitCode: 0 }, + { exitCode: 0, stdout: ["built-container\n"] } + ]); + vi.mocked(readFile).mockResolvedValue(Buffer.from("FROM alpine\nARG ALPHA\nARG ZED\n")); + const state = createState(null); + const { dockerExecutionEnvFactory } = await import("./docker-execution-env.js"); + + const env = await dockerExecutionEnvFactory.open( + createOpenSpec({ + runtime: { + type: "docker", + dockerfile: "Dockerfile", + build_context: "docker", + build_args: { ZED: "last", ALPHA: "first" }, + mounts: [] + }, + state, + hostRunner: runner + }) + ); + + const buildSpec = runner.specs[0]; + const builtImage = state.putCalls[0]?.entry.image; + + expect(env.id).toBe("built-container"); + expect(builtImage).toMatch(/^poe-code\/local:[a-f0-9]{64}$/); + expect(buildSpec).toEqual({ + command: "docker", + args: [ + "build", + "--tag", + builtImage, + "-f", + "/repo/Dockerfile", + "--build-arg", + "ALPHA=first", + "--build-arg", + "ZED=last", + "/repo/docker" + ], + stdout: "pipe", + stderr: "pipe" + }); + expect(state.putCalls[0]?.backend).toBe("docker"); + expect(state.putCalls[0]?.entry).toMatchObject({ + hash: expect.any(String), + image: builtImage, + runtime_type: "docker", + dockerfile_path: "/repo/Dockerfile" + }); + }); + + it("executes commands inside the opened container", async () => { + const runner = createCapturingRunner([ + { exitCode: 0, stdout: ["container-id\n"] }, + { exitCode: 0, stdout: ["ok\n"] } + ]); + const { dockerExecutionEnvFactory } = await import("./docker-execution-env.js"); + const env = await dockerExecutionEnvFactory.open( + createOpenSpec({ + runtime: { + type: "docker", + image: "alpine:latest", + build_args: {}, + mounts: [] + }, + hostRunner: runner + }) + ); + + const handle = env.exec({ + command: "printf", + args: ["ok"], + cwd: "/workspace", + env: { A: "1" }, + stdin: "pipe", + stdout: "pipe", + stderr: "pipe", + tty: true + }); + + expect(runner.specs[1]).toEqual({ + command: "docker", + args: [ + "exec", + "-i", + "-t", + "-w", + "/workspace", + "-e", + "A=1", + "container-id", + "printf", + "ok" + ], + stdin: "pipe", + stdout: "pipe", + stderr: "pipe", + tty: true + }); + await expect(handle.result).resolves.toEqual({ exitCode: 0 }); + }); + + it("uploads and downloads the workspace through docker cp tarballs", async () => { + const runner = createCapturingRunner([ + { exitCode: 0, stdout: ["container-id\n"] }, + { exitCode: 0 }, + { exitCode: 0 }, + { exitCode: 0 }, + { exitCode: 0 }, + { exitCode: 0 }, + { exitCode: 0 } + ]); + const { dockerExecutionEnvFactory } = await import("./docker-execution-env.js"); + const env = await dockerExecutionEnvFactory.open( + createOpenSpec({ + runtime: { + type: "docker", + image: "alpine:latest", + build_args: {}, + mounts: [] + }, + hostRunner: runner + }) + ); + + await env.uploadWorkspace(); + await env.downloadWorkspace({ conflictPolicy: "overwrite" }); + + expect(runner.specs.map((spec) => [spec.command, spec.args?.[0], spec.args?.[1]])).toEqual([ + ["docker", "run", "-d"], + ["tar", "-cf", expect.any(String)], + ["docker", "cp", expect.stringContaining(".tar")], + ["docker", "exec", "container-id"], + ["docker", "exec", "container-id"], + ["docker", "cp", expect.stringContaining("container-id:")], + ["tar", "-xf", expect.any(String)] + ]); + }); + + it("passes upload ignore files to the host tar command in configured order", async () => { + const runner = createCapturingRunner([ + { exitCode: 0, stdout: ["container-id\n"] }, + { exitCode: 0 }, + { exitCode: 0 }, + { exitCode: 0 } + ]); + const { dockerExecutionEnvFactory } = await import("./docker-execution-env.js"); + const env = await dockerExecutionEnvFactory.open( + createOpenSpec({ + runtime: { + type: "docker", + image: "alpine:latest", + build_args: {}, + mounts: [] + }, + uploadIgnoreFiles: ["node_modules", "dist"], + hostRunner: runner + }) + ); + + await env.uploadWorkspace(); + + expect(runner.specs[1]).toMatchObject({ + command: "tar", + args: [ + "--exclude", + "node_modules", + "--exclude", + "dist", + "-cf", + expect.any(String), + "-C", + "/repo", + "." + ] + }); + }); + + it("refuses local overwrites on download when conflict policy is refuse", async () => { + const runner = createCapturingRunner([ + { exitCode: 0, stdout: ["container-id\n"] }, + { exitCode: 0 }, + { exitCode: 0 }, + { exitCode: 0 } + ]); + const { dockerExecutionEnvFactory } = await import("./docker-execution-env.js"); + const env = await dockerExecutionEnvFactory.open( + createOpenSpec({ + runtime: { + type: "docker", + image: "alpine:latest", + build_args: {}, + mounts: [] + }, + hostRunner: runner + }) + ); + + await env.downloadWorkspace({ conflictPolicy: "refuse" }); + + expect(runner.specs[3]).toMatchObject({ + command: "tar", + args: ["-xkf", expect.any(String), "-C", "/repo"] + }); + }); + + it("attaches to an existing container id", async () => { + const runner = createCapturingRunner([{ exitCode: 0, stdout: ["attached\n"] }]); + vi.mocked(createHostRunner).mockReturnValue(runner); + const { dockerExecutionEnvFactory } = await import("./docker-execution-env.js"); + const env = await dockerExecutionEnvFactory.attach("container-id"); + + const handle = env.exec({ + command: "printf", + args: ["attached"], + stdout: "pipe", + stderr: "pipe" + }); + + expect(runner.specs[0]).toEqual({ + command: "docker", + args: ["exec", "container-id", "printf", "attached"], + stdin: undefined, + stdout: "pipe", + stderr: "pipe", + tty: undefined + }); + await expect(handle.result).resolves.toEqual({ exitCode: 0 }); + }); +}); + +function createOpenSpec(overrides: Partial = {}): OpenSpec { + return { + cwd: "/repo", + runtime: { + type: "docker", + image: "alpine:latest", + build_args: {}, + mounts: [] + }, + env: {}, + uploadIgnoreFiles: [], + jobLabel: { + tool: "node", + argv: ["node", "--version"] + }, + ...overrides + }; +} + +function createState(template: unknown) { + const getCalls: Array<{ backend: string; hash: string }> = []; + const putCalls: Array<{ backend: string; entry: Record }> = []; + + return { + getCalls, + putCalls, + templates: { + async get(backend: string, hash: string) { + getCalls.push({ backend, hash }); + return template; + }, + async put(backend: string, entry: Record) { + putCalls.push({ backend, entry }); + } + } + }; +} + +function createCapturingRunner( + results: Array<{ exitCode: number; stdout?: string[]; stderr?: string[] }> +): Runner & { specs: RunSpec[] } { + const specs: RunSpec[] = []; + const runner: Runner & { specs: RunSpec[] } = { + name: "mock", + specs, + exec(spec) { + const result = results.shift(); + if (!result) { + throw new Error(`No mock result for ${spec.command}`); + } + + specs.push(spec); + return createHandle(result); + } + }; + + return runner; +} + +function createHandle(result: { exitCode: number; stdout?: string[]; stderr?: string[] }): RunHandle { + return { + pid: 123, + stdin: null, + stdout: result.stdout ? ReadableStreamFrom(result.stdout) : null, + stderr: result.stderr ? ReadableStreamFrom(result.stderr) : null, + result: Promise.resolve({ exitCode: result.exitCode }), + kill() {} + }; +} + +function ReadableStreamFrom(chunks: string[]): NodeJS.ReadableStream { + return Readable.from(chunks); +} diff --git a/packages/process-runner/src/docker/docker-execution-env.ts b/packages/process-runner/src/docker/docker-execution-env.ts new file mode 100644 index 0000000000..ce8c62d81f --- /dev/null +++ b/packages/process-runner/src/docker/docker-execution-env.ts @@ -0,0 +1,460 @@ +import { createHash, randomBytes } from "node:crypto"; +import { mkdtempSync, rmSync } from "node:fs"; +import { readFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { buildDockerRunArgs } from "./args.js"; +import { buildContextArgs, detectContext } from "./context.js"; +import { detectEngine } from "./engine.js"; +import { createHostRunner } from "../host/host-runner.js"; +import type { + DockerMount, + Engine, + ExecutionEnvFactory, + OpenSpec, + OpenedEnv, + Runner, + RunSpec +} from "../types.js"; + +interface DockerRuntime { + type: "docker"; + image?: string; + dockerfile?: string; + build_context?: string; + build_args?: Record; + mounts?: DockerMount[]; + engine?: Engine; + network?: string; + extra_args?: string[]; +} + +const containerCommand = ["sh", "-c", "while :; do sleep 3600; done"] as const; + +export const dockerExecutionEnvFactory: ExecutionEnvFactory = { + type: "docker", + supportsDetach: true, + async open(spec): Promise { + const runtime = parseDockerRuntime(spec.runtime); + const runner = spec.hostRunner ?? createHostRunner(); + const engine = runtime.engine ?? detectEngine(); + const context = detectContext(); + const image = await resolveImage({ + spec, + runtime, + runner, + engine, + context + }); + const containerName = createContainerName(); + const runArgs = buildDockerRunArgs({ + engine, + context, + image, + command: containerCommand[0], + args: containerCommand.slice(1), + cwd: undefined, + env: undefined, + mounts: runtime.mounts ?? [], + ports: [], + network: runtime.network, + containerName, + detached: true, + interactive: true, + tty: false, + rm: false, + extraArgs: runtime.extra_args ?? [] + }); + const [command, ...args] = runArgs; + const id = (await runAndRead(runner, { command, args, stdout: "pipe", stderr: "pipe" })).trim(); + + return createDockerEnv({ + id, + spec, + runner, + engine, + context + }); + }, + async attach(envId): Promise { + const engine = detectEngine(); + return createDockerEnv({ + id: envId, + spec: createAttachedSpec(), + runner: createHostRunner(), + engine, + context: detectContext() + }); + } +}; + +function createDockerEnv(input: { + id: string; + spec: OpenSpec; + runner: Runner; + engine: Engine; + context: string | null; +}): OpenedEnv { + const containerRef = input.id; + + return { + id: containerRef, + job: null, + async uploadWorkspace() { + const tempDir = mkdtempSync(path.join(tmpdir(), "poe-docker-upload-")); + const archivePath = path.join(tempDir, "workspace.tar"); + try { + const excludeArgs = input.spec.uploadIgnoreFiles.flatMap((ignored) => [ + "--exclude", + ignored + ]); + const tarArgs = [...excludeArgs, "-cf", archivePath, "-C", input.spec.cwd, "."]; + await runOrThrow(input.runner, { + command: "tar", + args: tarArgs, + stdout: "pipe", + stderr: "pipe" + }); + await runOrThrow(input.runner, { + command: input.engine, + args: [ + ...buildContextArgs(input.engine, input.context), + "cp", + archivePath, + `${containerRef}:/tmp/poe-workspace-upload.tar` + ], + stdout: "pipe", + stderr: "pipe" + }); + await runOrThrow(input.runner, { + command: input.engine, + args: [ + ...buildContextArgs(input.engine, input.context), + "exec", + containerRef, + "sh", + "-c", + `mkdir -p ${shellQuote(input.spec.cwd)} && tar -xf /tmp/poe-workspace-upload.tar -C ${shellQuote(input.spec.cwd)}` + ], + stdout: "pipe", + stderr: "pipe" + }); + + return { files: 0, bytes: 0, skipped: [] }; + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } + }, + async downloadWorkspace(opts) { + const tempDir = mkdtempSync(path.join(tmpdir(), "poe-docker-download-")); + const archivePath = path.join(tempDir, "workspace.tar"); + try { + await runOrThrow(input.runner, { + command: input.engine, + args: [ + ...buildContextArgs(input.engine, input.context), + "exec", + containerRef, + "sh", + "-c", + `tar -cf /tmp/poe-workspace-download.tar -C ${shellQuote(input.spec.cwd)} .` + ], + stdout: "pipe", + stderr: "pipe" + }); + await runOrThrow(input.runner, { + command: input.engine, + args: [ + ...buildContextArgs(input.engine, input.context), + "cp", + `${containerRef}:/tmp/poe-workspace-download.tar`, + archivePath + ], + stdout: "pipe", + stderr: "pipe" + }); + const extractMode = opts.conflictPolicy === "refuse" ? "-xkf" : "-xf"; + await runOrThrow(input.runner, { + command: "tar", + args: [extractMode, archivePath, "-C", input.spec.cwd], + stdout: "pipe", + stderr: "pipe" + }); + + return { files: 0, bytes: 0, conflicts: [] }; + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } + }, + exec(spec) { + return input.runner.exec({ + command: input.engine, + args: [ + ...buildContextArgs(input.engine, input.context), + "exec", + ...(spec.stdin === "pipe" || spec.stdin === "inherit" ? ["-i"] : []), + ...(spec.tty === true ? ["-t"] : []), + ...(spec.cwd !== undefined ? ["-w", spec.cwd] : []), + ...buildEnvArgs(spec.env), + containerRef, + spec.command, + ...(spec.args ?? []) + ], + stdin: spec.stdin, + stdout: spec.stdout, + stderr: spec.stderr, + tty: spec.tty + }); + }, + async detach() { + return createContainerJob(containerRef, input.runner, input.engine, input.context); + }, + shell() { + const shellSpec = input.spec.shellSpec; + return this.exec({ + command: shellSpec?.command ?? input.spec.env.SHELL ?? "sh", + ...(shellSpec?.args ? { args: shellSpec.args } : {}), + cwd: input.spec.cwd, + env: shellSpec && "env" in shellSpec ? shellSpec.env : input.spec.env, + stdin: "inherit", + stdout: "inherit", + stderr: "inherit", + tty: true + }); + }, + async close() { + await runOrThrow(input.runner, { + command: input.engine, + args: [...buildContextArgs(input.engine, input.context), "rm", "-f", containerRef], + stdout: "pipe", + stderr: "pipe" + }); + } + }; +} + +async function resolveImage(input: { + spec: OpenSpec; + runtime: DockerRuntime; + runner: Runner; + engine: Engine; + context: string | null; +}): Promise { + if (input.runtime.image !== undefined) { + return input.runtime.image; + } + + const dockerfilePath = path.resolve( + input.spec.cwd, + input.runtime.dockerfile ?? path.join(".poe-code", "Dockerfile") + ); + const buildContext = path.resolve(input.spec.cwd, input.runtime.build_context ?? "."); + const dockerfileBytes = await readFile(dockerfilePath); + const hash = hashDockerTemplate(dockerfileBytes, input.runtime.build_args ?? {}); + const cached = await input.spec.state?.templates.get("docker", hash); + + if (cached?.image !== undefined) { + return cached.image; + } + + const image = `poe-code/local:${hash}`; + await buildImage({ + runner: input.runner, + engine: input.engine, + context: input.context, + image, + dockerfilePath, + buildContext, + buildArgs: input.runtime.build_args ?? {} + }); + await input.spec.state?.templates.put("docker", { + hash, + image, + runtime_type: "docker", + dockerfile_path: dockerfilePath, + built_at: new Date().toISOString() + }); + + return image; +} + +function hashDockerTemplate(dockerfileBytes: Buffer, buildArgs: Record): string { + const hash = createHash("sha256"); + hash.update(dockerfileBytes); + hash.update("\0"); + for (const [key, value] of sortedBuildArgs(buildArgs)) { + hash.update(key); + hash.update("="); + hash.update(value); + hash.update("\0"); + } + return hash.digest("hex"); +} + +async function buildImage(input: { + runner: Runner; + engine: Engine; + context: string | null; + image: string; + dockerfilePath: string; + buildContext: string; + buildArgs: Record; +}): Promise { + await runOrThrow(input.runner, { + command: input.engine, + args: [ + ...buildContextArgs(input.engine, input.context), + "build", + "--tag", + input.image, + "-f", + input.dockerfilePath, + ...sortedBuildArgs(input.buildArgs).flatMap(([key, value]) => [ + "--build-arg", + `${key}=${value}` + ]), + input.buildContext + ], + stdout: "pipe", + stderr: "pipe" + }); +} + +function parseDockerRuntime(runtime: unknown): DockerRuntime { + if (!runtime || typeof runtime !== "object" || Array.isArray(runtime)) { + throw new Error("docker runtime must be an object"); + } + const record = runtime as Record; + if (record.type !== "docker") { + throw new Error('docker runtime type must be "docker"'); + } + return record as unknown as DockerRuntime; +} + +async function runAndRead(runner: Runner, spec: RunSpec): Promise { + const handle = runner.exec(spec); + const stdout = readStream(handle.stdout); + const stderr = readStream(handle.stderr); + const result = await handle.result; + const output = await stdout; + if (result.exitCode !== 0) { + const errorOutput = await stderr; + throw new Error( + `Command failed with exit code ${result.exitCode}: ${spec.command} ${(spec.args ?? []).join(" ")}${errorOutput ? `\n${errorOutput}` : ""}` + ); + } + return output; +} + +async function runOrThrow(runner: Runner, spec: RunSpec): Promise { + await runAndRead(runner, spec); +} + +async function readStream(stream: NodeJS.ReadableStream | null): Promise { + if (stream === null) { + return ""; + } + + stream.setEncoding("utf8"); + const chunks: string[] = []; + for await (const chunk of stream) { + chunks.push(String(chunk)); + } + return chunks.join(""); +} + +function sortedBuildArgs(buildArgs: Record): Array<[string, string]> { + return Object.entries(buildArgs).sort(([left], [right]) => left.localeCompare(right)); +} + +function buildEnvArgs(env: RunSpec["env"]): string[] { + if (env === undefined) { + return []; + } + + return Object.entries(env).flatMap(([key, value]) => ["-e", `${key}=${value}`]); +} + +function createContainerName(): string { + return `poe-env-${randomBytes(6).toString("hex")}`; +} + +async function createContainerJob( + containerId: string, + runner: Runner, + engine: Engine, + context: string | null +) { + return { + id: containerId, + envId: containerId, + tool: "docker", + argv: ["attach", containerId], + async status() { + const handle = runner.exec({ + command: engine, + args: [ + ...buildContextArgs(engine, context), + "inspect", + "-f", + "{{.State.Status}}", + containerId + ], + stdout: "pipe", + stderr: "pipe" + }); + const stdout = await readStream(handle.stdout); + const result = await handle.result; + if (result.exitCode !== 0) { + return "lost" as const; + } + return stdout.trim() === "running" ? ("running" as const) : ("exited" as const); + }, + async *stream() {}, + async wait() { + const handle = runner.exec({ + command: engine, + args: [...buildContextArgs(engine, context), "wait", containerId], + stdout: "pipe", + stderr: "pipe" + }); + const stdout = await readStream(handle.stdout); + const result = await handle.result; + return { exitCode: Number.parseInt(stdout.trim(), 10) || result.exitCode }; + }, + async kill(signal?: NodeJS.Signals) { + const args = + signal === undefined || signal === "SIGTERM" + ? ["stop", containerId] + : ["kill", ...(signal === "SIGKILL" ? [] : [`--signal=${signal}`]), containerId]; + await runOrThrow(runner, { + command: engine, + args: [...buildContextArgs(engine, context), ...args], + stdout: "pipe", + stderr: "pipe" + }); + } + }; +} + +function createAttachedSpec(): OpenSpec { + return { + cwd: "/workspace", + runtime: { + type: "docker", + image: "attached", + build_args: {}, + mounts: [] + }, + env: {}, + uploadIgnoreFiles: [], + jobLabel: { + tool: "docker", + argv: [] + } + }; +} + +function shellQuote(value: string): string { + return `'${value.replaceAll("'", "'\\''")}'`; +} diff --git a/packages/process-runner/src/index.test.ts b/packages/process-runner/src/index.test.ts index e11a8b08c0..7b53e3a937 100644 --- a/packages/process-runner/src/index.test.ts +++ b/packages/process-runner/src/index.test.ts @@ -4,6 +4,7 @@ import * as api from "./index.js"; import { buildContextArgs, detectContext } from "./docker/context.js"; import { detectEngine, isEngineAvailable } from "./docker/engine.js"; import { createDockerRunner } from "./docker/docker-runner.js"; +import { dockerExecutionEnvFactory } from "./docker/docker-execution-env.js"; import { hostExecutionEnvFactory } from "./host/host-execution-env.js"; import { createHostRunner } from "./host/host-runner.js"; import { createMockRunner, createMockRunnerByCommand } from "./testing/index.js"; @@ -14,6 +15,7 @@ import type { DockerRunArgs, DockerRunnerOptions, Engine, + ExecutionState, ExecutionEnvFactory, HostRunnerOptions, JobHandle, @@ -23,6 +25,7 @@ import type { RunHandle, Runner, RunSpec, + TemplateEntry, UploadResult } from "@poe-code/process-runner"; @@ -102,6 +105,21 @@ describe("@poe-code/process-runner public exports", () => { stderr: ["warn"], stdoutInterval: 10 }; + const templateEntry: TemplateEntry = { + hash: "hash", + image: "poe-code/local:hash", + runtime_type: "docker", + dockerfile_path: "/repo/Dockerfile", + built_at: "2026-05-03T00:00:00.000Z" + }; + const state: ExecutionState = { + templates: { + async get() { + return templateEntry; + }, + async put() {} + } + }; const runner: Runner = { name: "host", exec() { @@ -111,6 +129,8 @@ describe("@poe-code/process-runner public exports", () => { const openSpec: OpenSpec = { cwd: "/repo", runtime: { type: "host" }, + state, + hostRunner: runner, env: {}, uploadIgnoreFiles: [], jobLabel: { @@ -190,6 +210,7 @@ describe("@poe-code/process-runner public exports", () => { expect(api.detectContext).toBe(detectContext); expect(api.detectEngine).toBe(detectEngine); expect(api.isEngineAvailable).toBe(isEngineAvailable); + expect(api.dockerExecutionEnvFactory).toBe(dockerExecutionEnvFactory); expect(api.hostExecutionEnvFactory).toBe(hostExecutionEnvFactory); expect(api.createHostRunner).toBe(createHostRunner); expect(api.createDockerRunner).toBe(createDockerRunner); @@ -201,6 +222,7 @@ describe("@poe-code/process-runner public exports", () => { "detectEngine", "isEngineAvailable", "createDockerRunner", + "dockerExecutionEnvFactory", "hostExecutionEnvFactory", "createHostRunner", "createMockRunner", diff --git a/packages/process-runner/src/index.ts b/packages/process-runner/src/index.ts index b7332b4e77..964a4688d5 100644 --- a/packages/process-runner/src/index.ts +++ b/packages/process-runner/src/index.ts @@ -1,6 +1,7 @@ export { buildContextArgs, detectContext } from "./docker/context.js"; export { detectEngine, isEngineAvailable } from "./docker/engine.js"; export { createDockerRunner } from "./docker/docker-runner.js"; +export { dockerExecutionEnvFactory } from "./docker/docker-execution-env.js"; export { hostExecutionEnvFactory } from "./host/host-execution-env.js"; export { createHostRunner } from "./host/host-runner.js"; export { createMockRunner, createMockRunnerByCommand } from "./testing/index.js"; @@ -12,6 +13,7 @@ export type { DockerRunArgs, DockerRunnerOptions, Engine, + ExecutionState, ExecutionEnvFactory, ExecutionEnvType, HostRunnerOptions, @@ -25,5 +27,6 @@ export type { RunResult, Runner, RunSpec, + TemplateEntry, UploadResult } from "./types.js"; diff --git a/packages/process-runner/src/types.ts b/packages/process-runner/src/types.ts index f8a30013fc..3cbb442869 100644 --- a/packages/process-runner/src/types.ts +++ b/packages/process-runner/src/types.ts @@ -48,6 +48,8 @@ export interface OpenSpec { cwd: string; runtime: unknown; runner?: unknown; + state?: ExecutionState; + hostRunner?: Runner; env: Record; uploadIgnoreFiles: string[]; jobLabel: { tool: string; argv: string[] }; @@ -67,6 +69,22 @@ export interface OpenSpec { shellSpec?: RunSpec; } +export interface ExecutionState { + templates: { + get(backend: "docker" | "e2b", hash: string): Promise; + put(backend: "docker" | "e2b", entry: TemplateEntry): Promise; + }; +} + +export interface TemplateEntry { + hash: string; + template_id?: string; + image?: string; + runtime_type: string; + dockerfile_path: string; + built_at: string; +} + export interface UploadResult { files: number; bytes: number; From af40a6ac8ba5c126a9cf17360d4da80b67c8a82e Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 19:17:16 -0500 Subject: [PATCH 017/111] feat: add runtime template commands --- docs/plans/e2b-integration.md | 6 +- docs/plans/e2b-integration.md.lock | 2 +- .../src/docker/docker-execution-env.test.ts | 65 ++-- .../src/docker/docker-execution-env.ts | 59 +++- packages/process-runner/src/index.test.ts | 7 +- packages/process-runner/src/index.ts | 5 +- .../__snapshots__/runtime.test.ts.snap | 16 + src/cli/commands/runtime.test.ts | 278 ++++++++++++++++++ src/cli/commands/runtime/build.ts | 185 ++++++++++++ src/cli/commands/runtime/index.ts | 15 + src/cli/commands/runtime/init.ts | 62 ++++ src/cli/commands/runtime/shared.ts | 98 ++++++ src/cli/commands/runtime/templates/clear.ts | 79 +++++ src/cli/commands/runtime/templates/index.ts | 17 ++ src/cli/commands/runtime/templates/ls.ts | 76 +++++ src/cli/program.ts | 29 +- 16 files changed, 957 insertions(+), 42 deletions(-) create mode 100644 src/cli/commands/__snapshots__/runtime.test.ts.snap create mode 100644 src/cli/commands/runtime.test.ts create mode 100644 src/cli/commands/runtime/build.ts create mode 100644 src/cli/commands/runtime/index.ts create mode 100644 src/cli/commands/runtime/init.ts create mode 100644 src/cli/commands/runtime/shared.ts create mode 100644 src/cli/commands/runtime/templates/clear.ts create mode 100644 src/cli/commands/runtime/templates/index.ts create mode 100644 src/cli/commands/runtime/templates/ls.ts diff --git a/docs/plans/e2b-integration.md b/docs/plans/e2b-integration.md index 5206c42299..2fba7a6cc2 100644 --- a/docs/plans/e2b-integration.md +++ b/docs/plans/e2b-integration.md @@ -374,7 +374,7 @@ tasks: status: implement: done test: done - commit: open + commit: done - id: cli-runtime-init-build-templates title: Add poe-code runtime init/build/templates commands @@ -404,8 +404,8 @@ tasks: Snapshot/screenshot tests for ls + clear output. status: - implement: open - test: open + implement: done + test: done commit: open - id: runner-e2b-package diff --git a/docs/plans/e2b-integration.md.lock b/docs/plans/e2b-integration.md.lock index 6432db5305..f2b869a5fc 100644 --- a/docs/plans/e2b-integration.md.lock +++ b/docs/plans/e2b-integration.md.lock @@ -1 +1 @@ -{"pid":82216,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T00:02:46.660Z"} \ No newline at end of file +{"pid":82216,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T00:15:46.242Z"} \ No newline at end of file diff --git a/packages/process-runner/src/docker/docker-execution-env.test.ts b/packages/process-runner/src/docker/docker-execution-env.test.ts index 90e06e8dde..731cc2bb3b 100644 --- a/packages/process-runner/src/docker/docker-execution-env.test.ts +++ b/packages/process-runner/src/docker/docker-execution-env.test.ts @@ -33,9 +33,7 @@ describe("dockerExecutionEnvFactory", () => { }); it("opens a persistent container from a configured image with runtime mounts", async () => { - const runner = createCapturingRunner([ - { exitCode: 0, stdout: ["container-from-image\n"] } - ]); + const runner = createCapturingRunner([{ exitCode: 0, stdout: ["container-from-image\n"] }]); const state = createState(null); const { dockerExecutionEnvFactory } = await import("./docker-execution-env.js"); @@ -103,9 +101,7 @@ describe("dockerExecutionEnvFactory", () => { }); it("uses a cached dockerfile image when the template hash exists", async () => { - const runner = createCapturingRunner([ - { exitCode: 0, stdout: ["cached-container\n"] } - ]); + const runner = createCapturingRunner([{ exitCode: 0, stdout: ["cached-container\n"] }]); vi.mocked(readFile).mockResolvedValue(Buffer.from("FROM alpine\n")); const state = createState({ image: "poe-code/local:cached", @@ -191,6 +187,44 @@ describe("dockerExecutionEnvFactory", () => { }); }); + it("exposes a build helper that can force rebuilds past the template cache", async () => { + const runner = createCapturingRunner([{ exitCode: 0 }]); + vi.mocked(readFile).mockResolvedValue(Buffer.from("FROM alpine\n")); + const state = createState({ + image: "poe-code/local:cached", + hash: "unused", + runtime_type: "docker", + dockerfile_path: "/repo/Dockerfile", + built_at: "2026-05-03T00:00:00.000Z" + }); + const { buildDockerRuntimeTemplate } = await import("./docker-execution-env.js"); + + const result = await buildDockerRuntimeTemplate({ + cwd: "/repo", + runtime: { + type: "docker", + dockerfile: "Dockerfile", + build_context: ".", + build_args: {} + }, + state, + runner, + force: true + }); + + expect(result).toEqual({ + backend: "docker", + cached: false, + hash: expect.any(String), + image: expect.stringMatching(/^poe-code\/local:[a-f0-9]{64}$/) + }); + expect(runner.specs[0]).toMatchObject({ + command: "docker", + args: ["build", "--tag", result.image, "-f", "/repo/Dockerfile", "/repo"] + }); + expect(state.putCalls).toHaveLength(1); + }); + it("executes commands inside the opened container", async () => { const runner = createCapturingRunner([ { exitCode: 0, stdout: ["container-id\n"] }, @@ -222,18 +256,7 @@ describe("dockerExecutionEnvFactory", () => { expect(runner.specs[1]).toEqual({ command: "docker", - args: [ - "exec", - "-i", - "-t", - "-w", - "/workspace", - "-e", - "A=1", - "container-id", - "printf", - "ok" - ], + args: ["exec", "-i", "-t", "-w", "/workspace", "-e", "A=1", "container-id", "printf", "ok"], stdin: "pipe", stdout: "pipe", stderr: "pipe", @@ -430,7 +453,11 @@ function createCapturingRunner( return runner; } -function createHandle(result: { exitCode: number; stdout?: string[]; stderr?: string[] }): RunHandle { +function createHandle(result: { + exitCode: number; + stdout?: string[]; + stderr?: string[]; +}): RunHandle { return { pid: 123, stdin: null, diff --git a/packages/process-runner/src/docker/docker-execution-env.ts b/packages/process-runner/src/docker/docker-execution-env.ts index ce8c62d81f..06d51642ab 100644 --- a/packages/process-runner/src/docker/docker-execution-env.ts +++ b/packages/process-runner/src/docker/docker-execution-env.ts @@ -10,6 +10,7 @@ import { createHostRunner } from "../host/host-runner.js"; import type { DockerMount, Engine, + ExecutionState, ExecutionEnvFactory, OpenSpec, OpenedEnv, @@ -29,6 +30,21 @@ interface DockerRuntime { extra_args?: string[]; } +export interface BuildDockerRuntimeTemplateInput { + cwd: string; + runtime: DockerRuntime; + state?: ExecutionState; + runner?: Runner; + force?: boolean; +} + +export interface BuildDockerRuntimeTemplateResult { + backend: "docker"; + hash: string; + image: string; + cached: boolean; +} + const containerCommand = ["sh", "-c", "while :; do sleep 3600; done"] as const; export const dockerExecutionEnvFactory: ExecutionEnvFactory = { @@ -244,30 +260,50 @@ async function resolveImage(input: { return input.runtime.image; } + const result = await buildDockerRuntimeTemplate({ + cwd: input.spec.cwd, + runtime: input.runtime, + state: input.spec.state, + runner: input.runner + }); + return result.image; +} + +export async function buildDockerRuntimeTemplate( + input: BuildDockerRuntimeTemplateInput +): Promise { + const runner = input.runner ?? createHostRunner(); + const engine = input.runtime.engine ?? detectEngine(); + const context = detectContext(); const dockerfilePath = path.resolve( - input.spec.cwd, + input.cwd, input.runtime.dockerfile ?? path.join(".poe-code", "Dockerfile") ); - const buildContext = path.resolve(input.spec.cwd, input.runtime.build_context ?? "."); + const buildContext = path.resolve(input.cwd, input.runtime.build_context ?? "."); const dockerfileBytes = await readFile(dockerfilePath); const hash = hashDockerTemplate(dockerfileBytes, input.runtime.build_args ?? {}); - const cached = await input.spec.state?.templates.get("docker", hash); + const cached = input.force ? null : await input.state?.templates.get("docker", hash); if (cached?.image !== undefined) { - return cached.image; + return { + backend: "docker", + hash, + image: cached.image, + cached: true + }; } const image = `poe-code/local:${hash}`; await buildImage({ - runner: input.runner, - engine: input.engine, - context: input.context, + runner, + engine, + context, image, dockerfilePath, buildContext, buildArgs: input.runtime.build_args ?? {} }); - await input.spec.state?.templates.put("docker", { + await input.state?.templates.put("docker", { hash, image, runtime_type: "docker", @@ -275,7 +311,12 @@ async function resolveImage(input: { built_at: new Date().toISOString() }); - return image; + return { + backend: "docker", + hash, + image, + cached: false + }; } function hashDockerTemplate(dockerfileBytes: Buffer, buildArgs: Record): string { diff --git a/packages/process-runner/src/index.test.ts b/packages/process-runner/src/index.test.ts index 7b53e3a937..82a7ef3c25 100644 --- a/packages/process-runner/src/index.test.ts +++ b/packages/process-runner/src/index.test.ts @@ -4,7 +4,10 @@ import * as api from "./index.js"; import { buildContextArgs, detectContext } from "./docker/context.js"; import { detectEngine, isEngineAvailable } from "./docker/engine.js"; import { createDockerRunner } from "./docker/docker-runner.js"; -import { dockerExecutionEnvFactory } from "./docker/docker-execution-env.js"; +import { + buildDockerRuntimeTemplate, + dockerExecutionEnvFactory +} from "./docker/docker-execution-env.js"; import { hostExecutionEnvFactory } from "./host/host-execution-env.js"; import { createHostRunner } from "./host/host-runner.js"; import { createMockRunner, createMockRunnerByCommand } from "./testing/index.js"; @@ -210,6 +213,7 @@ describe("@poe-code/process-runner public exports", () => { expect(api.detectContext).toBe(detectContext); expect(api.detectEngine).toBe(detectEngine); expect(api.isEngineAvailable).toBe(isEngineAvailable); + expect(api.buildDockerRuntimeTemplate).toBe(buildDockerRuntimeTemplate); expect(api.dockerExecutionEnvFactory).toBe(dockerExecutionEnvFactory); expect(api.hostExecutionEnvFactory).toBe(hostExecutionEnvFactory); expect(api.createHostRunner).toBe(createHostRunner); @@ -222,6 +226,7 @@ describe("@poe-code/process-runner public exports", () => { "detectEngine", "isEngineAvailable", "createDockerRunner", + "buildDockerRuntimeTemplate", "dockerExecutionEnvFactory", "hostExecutionEnvFactory", "createHostRunner", diff --git a/packages/process-runner/src/index.ts b/packages/process-runner/src/index.ts index 964a4688d5..9b4162d46e 100644 --- a/packages/process-runner/src/index.ts +++ b/packages/process-runner/src/index.ts @@ -1,7 +1,10 @@ export { buildContextArgs, detectContext } from "./docker/context.js"; export { detectEngine, isEngineAvailable } from "./docker/engine.js"; export { createDockerRunner } from "./docker/docker-runner.js"; -export { dockerExecutionEnvFactory } from "./docker/docker-execution-env.js"; +export { + buildDockerRuntimeTemplate, + dockerExecutionEnvFactory +} from "./docker/docker-execution-env.js"; export { hostExecutionEnvFactory } from "./host/host-execution-env.js"; export { createHostRunner } from "./host/host-runner.js"; export { createMockRunner, createMockRunnerByCommand } from "./testing/index.js"; diff --git a/src/cli/commands/__snapshots__/runtime.test.ts.snap b/src/cli/commands/__snapshots__/runtime.test.ts.snap new file mode 100644 index 0000000000..183802d59e --- /dev/null +++ b/src/cli/commands/__snapshots__/runtime.test.ts.snap @@ -0,0 +1,16 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`runtime command > snapshots runtime templates clear output and removes local template entries 1`] = ` +"runtime templates clear +Cleared 1 local runtime template cache entry." +`; + +exports[`runtime command > snapshots runtime templates ls output grouped by backend 1`] = ` +"runtime templates ls +┌────────────┬──────────────────┬──────────────────────────────────┬──────────────────────────────────────┬──────────────────────────┐ +│ Backend │ Hash │ Artifact │ Dockerfile │ Built │ +├────────────┼──────────────────┼──────────────────────────────────┼──────────────────────────────────────┼──────────────────────────┤ +│ docker │ abc123 │ poe-code/local:abc123 │ /repo/.poe-code/Dockerfile │ 2026-05-03T10:00:00.000Z │ +│ e2b │ def456 │ tmpl_def456 │ /repo/.poe-code/Dockerfile │ 2026-05-03T11:00:00.000Z │ +└────────────┴──────────────────┴──────────────────────────────────┴──────────────────────────────────────┴──────────────────────────┘" +`; diff --git a/src/cli/commands/runtime.test.ts b/src/cli/commands/runtime.test.ts new file mode 100644 index 0000000000..a277b521d5 --- /dev/null +++ b/src/cli/commands/runtime.test.ts @@ -0,0 +1,278 @@ +import path from "node:path"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { Command } from "commander"; +import { Volume, createFsFromVolume } from "memfs"; +import { resolveProjectConfigPath } from "@poe-code/poe-code-config"; +import { buildDockerRuntimeTemplate } from "@poe-code/process-runner"; +import { createCliContainer } from "../container.js"; +import type { FileSystem } from "../../utils/file-system.js"; +import { registerRuntimeCommand } from "./runtime/index.js"; + +vi.mock("@poe-code/process-runner", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + buildDockerRuntimeTemplate: vi.fn(async () => ({ + backend: "docker", + hash: "mock-hash", + image: "poe-code/local:mock-hash", + cached: false + })) + }; +}); + +const cwd = "/repo"; +const homeDir = "/home/test"; +const projectConfigPath = resolveProjectConfigPath(cwd); +const dockerfilePath = path.join(cwd, ".poe-code", "Dockerfile"); +const statePath = path.join(homeDir, ".poe-code", "state", "templates.json"); +const buildDockerRuntimeTemplateMock = vi.mocked(buildDockerRuntimeTemplate); + +function createBaseProgram(): Command { + const program = new Command(); + program.exitOverride(); + program.name("poe-code").option("-y, --yes").option("--dry-run").option("--verbose"); + return program; +} + +function createMemFs(files: Record = {}): FileSystem { + const volume = Volume.fromJSON(files, "/"); + volume.mkdirSync(cwd, { recursive: true }); + volume.mkdirSync(homeDir, { recursive: true }); + return createFsFromVolume(volume).promises as unknown as FileSystem; +} + +function createContainer( + fs: FileSystem, + logs: string[] = [], + prompts = vi.fn().mockResolvedValue({}) +) { + return createCliContainer({ + fs, + prompts, + env: { + cwd, + homeDir, + variables: {} + }, + logger: (message) => logs.push(message) + }); +} + +function stripAnsi(input: string): string { + let result = ""; + let index = 0; + + while (index < input.length) { + const char = input[index]; + if (char === "\u001b" && input[index + 1] === "[") { + index += 2; + while (index < input.length && input[index] !== "m") { + index += 1; + } + index += 1; + continue; + } + result += char; + index += 1; + } + + return result; +} + +describe("runtime command", () => { + beforeEach(() => { + buildDockerRuntimeTemplateMock.mockClear(); + }); + + it("initializes runtime config and default Dockerfile with --yes defaults", async () => { + const fs = createMemFs(); + const container = createContainer(fs); + const program = createBaseProgram(); + registerRuntimeCommand(program, container); + + await program.parseAsync(["node", "cli", "--yes", "runtime", "init"]); + + await expect(fs.readFile(projectConfigPath, "utf8")).resolves.toContain('"type": "docker"'); + await expect(fs.readFile(dockerfilePath, "utf8")).resolves.toContain( + "npm i -g @poe-code/cli @anthropic-ai/claude-code" + ); + }); + + it("deep-merges only runtime.type on an initialized project", async () => { + const fs = createMemFs({ + [projectConfigPath]: `${JSON.stringify( + { + runtime: { + type: "docker", + build_args: { NODE_ENV: "test" }, + runner: { workspace: { exclude: ["coverage"] } } + } + }, + null, + 2 + )}\n`, + [dockerfilePath]: "FROM custom\n" + }); + const container = createContainer(fs); + const program = createBaseProgram(); + registerRuntimeCommand(program, container); + + await program.parseAsync(["node", "cli", "runtime", "init", "--type", "e2b", "--yes"]); + + await expect(fs.readFile(dockerfilePath, "utf8")).resolves.toBe("FROM custom\n"); + await expect(fs.readFile(projectConfigPath, "utf8")).resolves.toMatchInlineSnapshot(` + "{ + "runtime": { + "type": "e2b", + "build_args": { + "NODE_ENV": "test" + }, + "runner": { + "workspace": { + "exclude": [ + "coverage" + ] + } + } + } + } + " + `); + }); + + it("snapshots runtime templates ls output grouped by backend", async () => { + const fs = createMemFs({ + [statePath]: `${JSON.stringify( + { + docker: { + abc123: { + hash: "abc123", + image: "poe-code/local:abc123", + runtime_type: "docker", + dockerfile_path: "/repo/.poe-code/Dockerfile", + built_at: "2026-05-03T10:00:00.000Z" + } + }, + e2b: { + def456: { + hash: "def456", + template_id: "tmpl_def456", + runtime_type: "e2b", + dockerfile_path: "/repo/.poe-code/Dockerfile", + built_at: "2026-05-03T11:00:00.000Z" + } + } + }, + null, + 2 + )}\n` + }); + const logs: string[] = []; + const container = createContainer(fs, logs); + const program = createBaseProgram(); + registerRuntimeCommand(program, container); + + await program.parseAsync(["node", "cli", "runtime", "templates", "ls"]); + + expect(stripAnsi(logs.join("\n"))).toMatchSnapshot(); + }); + + it("snapshots runtime templates clear output and removes local template entries", async () => { + const fs = createMemFs({ + [statePath]: `${JSON.stringify( + { + docker: { + abc123: { + hash: "abc123", + image: "poe-code/local:abc123", + runtime_type: "docker", + dockerfile_path: "/repo/.poe-code/Dockerfile", + built_at: "2026-05-03T10:00:00.000Z" + } + }, + e2b: {} + }, + null, + 2 + )}\n` + }); + const logs: string[] = []; + const container = createContainer(fs, logs); + const program = createBaseProgram(); + registerRuntimeCommand(program, container); + + await program.parseAsync(["node", "cli", "--yes", "runtime", "templates", "clear"]); + + expect(stripAnsi(logs.join("\n"))).toMatchSnapshot(); + await expect(fs.readFile(statePath, "utf8")).resolves.toMatchInlineSnapshot(` + "{ + "docker": {}, + "e2b": {} + } + " + `); + }); + + it("builds docker runtime templates through the exposed helper", async () => { + const fs = createMemFs({ + [projectConfigPath]: `${JSON.stringify({ runtime: { type: "docker" } }, null, 2)}\n`, + [dockerfilePath]: "FROM custom\n" + }); + const logs: string[] = []; + const container = createContainer(fs, logs); + const program = createBaseProgram(); + registerRuntimeCommand(program, container); + + await program.parseAsync(["node", "cli", "runtime", "build", "--force"]); + + expect(buildDockerRuntimeTemplateMock).toHaveBeenCalledWith( + expect.objectContaining({ + cwd, + runtime: expect.objectContaining({ type: "docker" }), + force: true, + state: expect.any(Object) + }) + ); + expect(stripAnsi(logs.join("\n"))).toContain("Built Docker image poe-code/local:mock-hash"); + }); + + it("does not build when a docker image is pinned in config", async () => { + const fs = createMemFs({ + [projectConfigPath]: `${JSON.stringify( + { runtime: { type: "docker", image: "ghcr.io/example/poe-runtime:1" } }, + null, + 2 + )}\n` + }); + const logs: string[] = []; + const container = createContainer(fs, logs); + const program = createBaseProgram(); + registerRuntimeCommand(program, container); + + await program.parseAsync(["node", "cli", "runtime", "build"]); + + expect(buildDockerRuntimeTemplateMock).not.toHaveBeenCalled(); + expect(stripAnsi(logs.join("\n"))).toContain( + "Docker runtime uses pinned image ghcr.io/example/poe-runtime:1." + ); + }); + + it("does not load the e2b builder when a template id is pinned in config", async () => { + const fs = createMemFs({ + [projectConfigPath]: `${JSON.stringify( + { runtime: { type: "e2b", template_id: "tmpl_pinned" } }, + null, + 2 + )}\n` + }); + const logs: string[] = []; + const container = createContainer(fs, logs); + const program = createBaseProgram(); + registerRuntimeCommand(program, container); + + await program.parseAsync(["node", "cli", "runtime", "build"]); + + expect(stripAnsi(logs.join("\n"))).toContain("E2B runtime uses pinned template tmpl_pinned."); + }); +}); diff --git a/src/cli/commands/runtime/build.ts b/src/cli/commands/runtime/build.ts new file mode 100644 index 0000000000..8699548b37 --- /dev/null +++ b/src/cli/commands/runtime/build.ts @@ -0,0 +1,185 @@ +import path from "node:path"; +import type { Command } from "commander"; +import { + createStateManager, + parseRuntime, + readMergedDocument, + runtimeConfigScope, + resolveScope, + type E2bRuntime +} from "@poe-code/poe-code-config"; +import { pathExists } from "@poe-code/config-mutations"; +import { buildDockerRuntimeTemplate } from "@poe-code/process-runner"; +import type { ExecutionState, Runner } from "@poe-code/process-runner"; +import type { CliContainer } from "../../container.js"; +import { createExecutionResources, resolveCommandFlags } from "../shared.js"; + +export interface RuntimeBuildOptions { + force?: boolean; +} + +interface BuildE2bRuntimeTemplateResult { + backend: "e2b"; + hash: string; + templateId: string; + cached: boolean; +} + +type BuildE2bRuntimeTemplate = (input: { + cwd: string; + runtime: E2bRuntime; + dockerfilePath: string; + buildContext: string; + state?: ExecutionState; + runner?: Runner; + force?: boolean; +}) => Promise; + +export function registerRuntimeBuildCommand( + runtime: Command, + root: Command, + container: CliContainer +): void { + runtime + .command("build") + .description("Build the configured runtime template.") + .option("--force", "Ignore the local template cache and rebuild.") + .action(async (options: RuntimeBuildOptions) => { + await executeRuntimeBuild(root, container, options); + }); +} + +async function executeRuntimeBuild( + program: Command, + container: CliContainer, + options: RuntimeBuildOptions +): Promise { + const flags = resolveCommandFlags(program); + const resources = createExecutionResources(container, flags, "runtime:build"); + const state = createStateManager( + container.env.homeDir, + container.fs as unknown as Parameters[1] + ); + const document = await readMergedDocument( + container.fs, + container.env.configPath, + container.env.projectConfigPath + ); + const runtimeScope = resolveScope( + runtimeConfigScope.schema, + document.runtime, + container.env.variables + ); + const runtimeConfig = parseRuntime(runtimeScope); + + resources.logger.intro("runtime build"); + + if (runtimeConfig.type === "host") { + resources.logger.info("Host runtime does not require a template build."); + return; + } + + if (runtimeConfig.type === "docker") { + if (runtimeConfig.image !== undefined) { + resources.logger.info(`Docker runtime uses pinned image ${runtimeConfig.image}.`); + return; + } + if (flags.dryRun) { + resources.logger.dryRun("Dry run: would build docker runtime template."); + return; + } + await requireRuntimeBuildPaths(container, runtimeConfig, "Docker"); + const result = await buildDockerRuntimeTemplate({ + cwd: container.env.cwd, + runtime: runtimeConfig, + state, + force: options.force === true + }); + resources.logger.success( + result.cached + ? `Using cached Docker image ${result.image}` + : `Built Docker image ${result.image}` + ); + return; + } + + if (runtimeConfig.template_id !== undefined) { + resources.logger.info(`E2B runtime uses pinned template ${runtimeConfig.template_id}.`); + return; + } + if (flags.dryRun) { + resources.logger.dryRun("Dry run: would build e2b runtime template."); + return; + } + const paths = await requireRuntimeBuildPaths(container, runtimeConfig, "E2B"); + const buildE2bRuntimeTemplate = await loadE2bRuntimeTemplateBuilder(); + const result = await buildE2bRuntimeTemplate({ + cwd: container.env.cwd, + runtime: runtimeConfig, + dockerfilePath: paths.dockerfilePath, + buildContext: paths.buildContext, + state, + force: options.force === true + }); + resources.logger.success( + result.cached + ? `Using cached E2B template ${result.templateId}` + : `Built E2B template ${result.templateId}` + ); +} + +async function requireRuntimeBuildPaths( + container: CliContainer, + runtime: { dockerfile?: string; build_context?: string }, + label: string +): Promise<{ dockerfilePath: string; buildContext: string }> { + const dockerfilePath = path.resolve( + container.env.cwd, + runtime.dockerfile ?? path.join(".poe-code", "Dockerfile") + ); + if (!(await pathExists(container.fs, dockerfilePath))) { + throw new Error(`${label} runtime requires a Dockerfile at ${dockerfilePath}.`); + } + return { + dockerfilePath, + buildContext: path.resolve(container.env.cwd, runtime.build_context ?? ".") + }; +} + +async function loadE2bRuntimeTemplateBuilder(): Promise { + const dynamicImport = new Function("specifier", "return import(specifier)") as ( + specifier: string + ) => Promise; + + try { + const module = await dynamicImport("@poe-code/runner-e2b"); + if ( + module && + typeof module === "object" && + "buildE2bRuntimeTemplate" in module && + typeof module.buildE2bRuntimeTemplate === "function" + ) { + return module.buildE2bRuntimeTemplate as BuildE2bRuntimeTemplate; + } + } catch (error) { + if (isModuleNotFound(error)) { + throw new Error( + "E2B runtime builds require @poe-code/runner-e2b. The E2B runner package is not installed in this checkout." + ); + } + throw error; + } + + throw new Error( + "E2B runtime builds require @poe-code/runner-e2b to export buildE2bRuntimeTemplate." + ); +} + +function isModuleNotFound(error: unknown): boolean { + return Boolean( + error && + typeof error === "object" && + "code" in error && + (error as { code?: unknown }).code === "ERR_MODULE_NOT_FOUND" + ); +} diff --git a/src/cli/commands/runtime/index.ts b/src/cli/commands/runtime/index.ts new file mode 100644 index 0000000000..5d4d5c5f57 --- /dev/null +++ b/src/cli/commands/runtime/index.ts @@ -0,0 +1,15 @@ +import type { Command } from "commander"; +import type { CliContainer } from "../../container.js"; +import { registerRuntimeBuildCommand } from "./build.js"; +import { registerRuntimeInitCommand } from "./init.js"; +import { registerRuntimeTemplatesCommand } from "./templates/index.js"; + +export function registerRuntimeCommand(program: Command, container: CliContainer): void { + const runtime = program + .command("runtime") + .description("Manage project runtime templates and cache."); + + registerRuntimeInitCommand(runtime, program, container); + registerRuntimeBuildCommand(runtime, program, container); + registerRuntimeTemplatesCommand(runtime, program, container); +} diff --git a/src/cli/commands/runtime/init.ts b/src/cli/commands/runtime/init.ts new file mode 100644 index 0000000000..675ef32908 --- /dev/null +++ b/src/cli/commands/runtime/init.ts @@ -0,0 +1,62 @@ +import { Option, type Command } from "commander"; +import type { CliContainer } from "../../container.js"; +import { createExecutionResources, resolveCommandFlags } from "../shared.js"; +import { + resolveRuntimeType, + updateRuntimeScope, + writeDefaultDockerfileIfNeeded +} from "./shared.js"; + +export interface RuntimeInitOptions { + type?: string; + dockerfile?: boolean; +} + +export function registerRuntimeInitCommand( + runtime: Command, + root: Command, + container: CliContainer +): void { + runtime + .command("init") + .description("Initialize project runtime configuration.") + .addOption(new Option("--type ", "Runtime backend").choices(["host", "docker", "e2b"])) + .option("--no-dockerfile", "Do not create .poe-code/Dockerfile.") + .action(async (options: RuntimeInitOptions) => { + await executeRuntimeInit(root, container, options); + }); +} + +async function executeRuntimeInit( + program: Command, + container: CliContainer, + options: RuntimeInitOptions +): Promise { + const flags = resolveCommandFlags(program); + const resources = createExecutionResources(container, flags, "runtime:init"); + const type = await resolveRuntimeType({ + value: options.type, + assumeYes: flags.assumeYes + }); + + resources.logger.intro("runtime init"); + + if (flags.dryRun) { + resources.logger.dryRun(`Dry run: would set runtime.type to "${type}".`); + if (options.dockerfile !== false) { + resources.logger.dryRun("Dry run: would create .poe-code/Dockerfile if missing."); + } + return; + } + + await updateRuntimeScope({ container, type }); + const wroteDockerfile = await writeDefaultDockerfileIfNeeded({ + container, + enabled: options.dockerfile !== false + }); + + resources.logger.success(`Updated ${container.env.projectConfigPath}: runtime.type = "${type}"`); + if (wroteDockerfile) { + resources.logger.success("Created .poe-code/Dockerfile"); + } +} diff --git a/src/cli/commands/runtime/shared.ts b/src/cli/commands/runtime/shared.ts new file mode 100644 index 0000000000..70dff450cd --- /dev/null +++ b/src/cli/commands/runtime/shared.ts @@ -0,0 +1,98 @@ +import path from "node:path"; +import { deepMergeDocuments, readDocument, writeScope } from "@poe-code/poe-code-config"; +import { pathExists } from "@poe-code/config-mutations"; +import { cancel as dsCancel, isCancel, select as dsSelect } from "@poe-code/design-system"; +import { OperationCancelledError } from "../../errors.js"; +import type { CliContainer } from "../../container.js"; + +export const runtimeTypes = ["host", "docker", "e2b"] as const; +export type RuntimeType = (typeof runtimeTypes)[number]; + +export const defaultRuntimeType: RuntimeType = "docker"; +export const defaultDockerfile = [ + "FROM node:22-bookworm-slim", + "", + "RUN apt-get update \\", + " && apt-get install -y --no-install-recommends git ca-certificates \\", + " && rm -rf /var/lib/apt/lists/*", + "", + "RUN npm i -g @poe-code/cli @anthropic-ai/claude-code", + "" +].join("\n"); + +export function resolveDockerfilePath(container: CliContainer): string { + return path.join(container.env.cwd, ".poe-code", "Dockerfile"); +} + +export async function resolveRuntimeType(input: { + value?: string; + assumeYes: boolean; +}): Promise { + if (input.value !== undefined) { + return parseRuntimeType(input.value); + } + + if (input.assumeYes) { + return defaultRuntimeType; + } + + const result = await dsSelect({ + message: "Runtime backend", + initialValue: defaultRuntimeType, + options: [ + { value: "docker", label: "Docker", hint: "Build from .poe-code/Dockerfile" }, + { value: "host", label: "Host", hint: "Run commands on this machine" }, + { value: "e2b", label: "E2B", hint: "Use a cloud sandbox template" } + ] + }); + + if (isCancel(result)) { + dsCancel("Operation cancelled."); + throw new OperationCancelledError(); + } + + return result; +} + +export async function updateRuntimeScope(input: { + container: CliContainer; + type: RuntimeType; +}): Promise { + const document = await readDocument(input.container.fs, input.container.env.projectConfigPath); + const merged = deepMergeDocuments(document, { runtime: { type: input.type } }); + await writeScope( + input.container.fs, + input.container.env.projectConfigPath, + "runtime", + merged.runtime ?? {} + ); +} + +export async function writeDefaultDockerfileIfNeeded(input: { + container: CliContainer; + enabled: boolean; +}): Promise { + if (!input.enabled) { + return false; + } + + const dockerfilePath = resolveDockerfilePath(input.container); + if (await pathExists(input.container.fs, dockerfilePath)) { + return false; + } + + await input.container.fs.mkdir(path.dirname(dockerfilePath), { recursive: true }); + await input.container.fs.writeFile(dockerfilePath, defaultDockerfile, { encoding: "utf8" }); + return true; +} + +export function parseRuntimeType(value: string): RuntimeType { + if (runtimeTypes.includes(value as RuntimeType)) { + return value as RuntimeType; + } + throw new Error(`Invalid runtime type "${value}". Expected host, docker, or e2b.`); +} + +export function isRecord(value: unknown): value is Record { + return Boolean(value && typeof value === "object" && !Array.isArray(value)); +} diff --git a/src/cli/commands/runtime/templates/clear.ts b/src/cli/commands/runtime/templates/clear.ts new file mode 100644 index 0000000000..6183198951 --- /dev/null +++ b/src/cli/commands/runtime/templates/clear.ts @@ -0,0 +1,79 @@ +import { cancel as dsCancel, confirm as dsConfirm, isCancel } from "@poe-code/design-system"; +import { createStateManager, type TemplateBackend } from "@poe-code/poe-code-config"; +import type { Command } from "commander"; +import { OperationCancelledError } from "../../../errors.js"; +import type { CliContainer } from "../../../container.js"; +import { createExecutionResources, resolveCommandFlags } from "../../shared.js"; + +const backends: TemplateBackend[] = ["docker", "e2b"]; + +export function registerRuntimeTemplatesClearCommand( + templates: Command, + root: Command, + container: CliContainer +): void { + templates + .command("clear") + .description("Clear locally built runtime template cache entries.") + .action(async () => { + await executeRuntimeTemplatesClear(root, container); + }); +} + +async function executeRuntimeTemplatesClear( + program: Command, + container: CliContainer +): Promise { + const flags = resolveCommandFlags(program); + const resources = createExecutionResources(container, flags, "runtime:templates:clear"); + const state = createStateManager( + container.env.homeDir, + container.fs as unknown as Parameters[1] + ); + const entriesByBackend = await Promise.all( + backends.map(async (backend) => ({ + backend, + entries: await state.templates.list(backend) + })) + ); + const total = entriesByBackend.reduce((sum, group) => sum + group.entries.length, 0); + + resources.logger.intro("runtime templates clear"); + + if (total === 0) { + resources.logger.info("No local runtime template cache entries to clear."); + return; + } + + if (!flags.assumeYes) { + const confirmed = await dsConfirm({ + message: `Clear ${total} local runtime template cache ${total === 1 ? "entry" : "entries"}?`, + initialValue: false + }); + if (isCancel(confirmed)) { + dsCancel("Operation cancelled."); + throw new OperationCancelledError(); + } + if (confirmed !== true) { + resources.logger.info("Runtime template cache unchanged."); + return; + } + } + + if (flags.dryRun) { + resources.logger.dryRun( + `Dry run: would clear ${total} local runtime template cache ${total === 1 ? "entry" : "entries"}.` + ); + return; + } + + for (const group of entriesByBackend) { + for (const entry of group.entries) { + await state.templates.remove(group.backend, entry.hash); + } + } + + resources.logger.success( + `Cleared ${total} local runtime template cache ${total === 1 ? "entry" : "entries"}.` + ); +} diff --git a/src/cli/commands/runtime/templates/index.ts b/src/cli/commands/runtime/templates/index.ts new file mode 100644 index 0000000000..bac408f985 --- /dev/null +++ b/src/cli/commands/runtime/templates/index.ts @@ -0,0 +1,17 @@ +import type { Command } from "commander"; +import type { CliContainer } from "../../../container.js"; +import { registerRuntimeTemplatesClearCommand } from "./clear.js"; +import { registerRuntimeTemplatesLsCommand } from "./ls.js"; + +export function registerRuntimeTemplatesCommand( + runtime: Command, + root: Command, + container: CliContainer +): void { + const templates = runtime + .command("templates") + .description("Inspect and clear locally built runtime templates."); + + registerRuntimeTemplatesLsCommand(templates, root, container); + registerRuntimeTemplatesClearCommand(templates, root, container); +} diff --git a/src/cli/commands/runtime/templates/ls.ts b/src/cli/commands/runtime/templates/ls.ts new file mode 100644 index 0000000000..b95fcbb2c8 --- /dev/null +++ b/src/cli/commands/runtime/templates/ls.ts @@ -0,0 +1,76 @@ +import { getTheme, renderTable, text, type TableColumn } from "@poe-code/design-system"; +import { + createStateManager, + type TemplateBackend, + type TemplateEntry +} from "@poe-code/poe-code-config"; +import type { Command } from "commander"; +import type { CliContainer } from "../../../container.js"; +import { createExecutionResources, resolveCommandFlags } from "../../shared.js"; + +const backends: TemplateBackend[] = ["docker", "e2b"]; + +export function registerRuntimeTemplatesLsCommand( + templates: Command, + root: Command, + container: CliContainer +): void { + templates + .command("ls") + .description("List cached runtime templates.") + .action(async () => { + await executeRuntimeTemplatesLs(root, container); + }); +} + +async function executeRuntimeTemplatesLs(program: Command, container: CliContainer): Promise { + const flags = resolveCommandFlags(program); + const resources = createExecutionResources(container, flags, "runtime:templates:ls"); + const state = createStateManager( + container.env.homeDir, + container.fs as unknown as Parameters[1] + ); + const theme = getTheme(); + const rows: Record[] = []; + + for (const backend of backends) { + const entries = await state.templates.list(backend); + if (entries.length === 0) { + rows.push({ + Backend: theme.accent(backend), + Hash: text.muted("(empty)"), + Artifact: text.muted("-"), + Dockerfile: text.muted("-"), + Built: text.muted("-") + }); + continue; + } + + rows.push(...entries.map((entry) => formatEntryRow(backend, entry, theme))); + } + + resources.logger.intro("runtime templates ls"); + resources.logger.info(renderTable({ theme, columns, rows })); +} + +function formatEntryRow( + backend: TemplateBackend, + entry: TemplateEntry, + theme: ReturnType +): Record { + return { + Backend: theme.accent(backend), + Hash: entry.hash, + Artifact: entry.image ?? entry.template_id ?? text.muted("-"), + Dockerfile: entry.dockerfile_path, + Built: entry.built_at + }; +} + +const columns: TableColumn[] = [ + { name: "Backend", title: "Backend", alignment: "left", maxLen: 10 }, + { name: "Hash", title: "Hash", alignment: "left", maxLen: 16 }, + { name: "Artifact", title: "Artifact", alignment: "left", maxLen: 32 }, + { name: "Dockerfile", title: "Dockerfile", alignment: "left", maxLen: 36 }, + { name: "Built", title: "Built", alignment: "left", maxLen: 24 } +]; diff --git a/src/cli/program.ts b/src/cli/program.ts index fc3b8f7c1c..77647d306a 100644 --- a/src/cli/program.ts +++ b/src/cli/program.ts @@ -31,6 +31,7 @@ import { registerExperimentCommand } from "./commands/experiment.js"; import { registerLaunchCommand } from "./commands/launch.js"; import { registerMemoryCommand } from "./commands/memory.js"; import { registerProviderCommand } from "./commands/provider.js"; +import { registerRuntimeCommand } from "./commands/runtime/index.js"; import packageJson from "../../package.json" with { type: "json" }; import { throwCommandNotFound } from "./command-not-found.js"; import { @@ -92,6 +93,10 @@ const ROOT_HELP_COMMAND_SPECS: readonly RootHelpCommandSpec[] = [ { path: ["provider", "list"] }, { path: ["provider", "login"], args: "" }, { path: ["provider", "logout"], args: "" }, + { path: ["runtime", "init"] }, + { path: ["runtime", "build"] }, + { path: ["runtime", "templates", "ls"] }, + { path: ["runtime", "templates", "clear"] }, { path: ["experiment", "install"] }, { path: ["experiment", "run"] }, { path: ["experiment", "journal"] }, @@ -200,7 +205,8 @@ function formatHelpItem(input: { const paddedTerm = input.term.padEnd( input.termWidth + input.term.length - input.helper.displayWidth(input.term) ); - const remainingWidth = (input.helper.helpWidth ?? 80) - input.termWidth - spacerWidth - itemIndent; + const remainingWidth = + (input.helper.helpWidth ?? 80) - input.termWidth - spacerWidth - itemIndent; const descriptionIndent = `${indent}${" ".repeat(spacerWidth)}`; if (remainingWidth < input.helper.minWidthToWrap) { @@ -229,10 +235,7 @@ function formatHelpText(input: { helper: Help; }): string { const commandRows = buildRootHelpRows(input.command); - const nameWidth = Math.max( - 0, - ...commandRows.map((row) => row.name.length) - ); + const nameWidth = Math.max(0, ...commandRows.map((row) => row.name.length)); const argsWidth = Math.max(0, ...commandRows.map((row) => row.args.length)); const termWidth = nameWidth + 1 + argsWidth; const cmd = (row: (typeof commandRows)[number]) => { @@ -266,7 +269,11 @@ function formatHelpText(input: { function formatSubcommandHelp(cmd: Command, helper: Help): string { const termWidth = helper.padWidth(cmd, helper); - const formatItem = (term: string, description: string, style: (value: string) => string): string => + const formatItem = ( + term: string, + description: string, + style: (value: string) => string + ): string => formatHelpItem({ term: style(term), termWidth, @@ -278,7 +285,10 @@ function formatSubcommandHelp(cmd: Command, helper: Help): string { const output: string[] = []; output.push(text.heading(formatCommandHeader(cmd)), ""); - output.push(`${text.section("Usage:")} ${text.usageCommand(formatCanonicalCommandUsage(cmd))}`, ""); + output.push( + `${text.section("Usage:")} ${text.usageCommand(formatCanonicalCommandUsage(cmd))}`, + "" + ); const commandDescription = helper.commandDescription(cmd); if (commandDescription.length > 0) { @@ -350,7 +360,9 @@ function buildToolcraftArgv(argv: string[], commandNames: readonly string[]): st return [entry, script]; } - const forwardedFlags = argv.slice(2, commandIndex).filter((value) => FORWARDABLE_TOOLCRAFT_FLAGS.has(value)); + const forwardedFlags = argv + .slice(2, commandIndex) + .filter((value) => FORWARDABLE_TOOLCRAFT_FLAGS.has(value)); const commandArgs = argv.slice(commandIndex); if (commandArgs.length === 1) { @@ -474,6 +486,7 @@ function bootstrapProgram(container: CliContainer): Command { registerLaunchCommand(program, container); registerMemoryCommand(program, container); registerProviderCommand(program, container); + registerRuntimeCommand(program, container); registerForwardedToolcraftCommand( program, container, From 252ab0f2415f3990073acd90068c73bfc269576a Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 19:42:25 -0500 Subject: [PATCH 018/111] feat: add e2b runner --- .github/workflows/e2b-runner-integration.yml | 19 + docs/plans/e2b-integration.md | 6 +- docs/plans/e2b-integration.md.lock | 2 +- eslint.config.js | 17 + package-lock.json | 328 +++++++++++++++++- package.json | 1 + .../src/run-poe-command.test.ts | 76 +++- .../src/run-poe-command.ts | 29 +- packages/agent-spawn/package.json | 3 +- packages/agent-spawn/src/acp/acp.test.ts | 4 +- packages/agent-spawn/src/agent-spawn.test.ts | 4 +- .../agent-spawn/src/register-factories.ts | 8 +- .../agent-spawn/src/spawn-interactive.test.ts | 2 +- .../agent-spawn/src/spawn-log-options.test.ts | 2 +- packages/runner-e2b/README.md | 15 + packages/runner-e2b/package.json | 34 ++ .../src/e2b-execution-env.integration.ts | 42 +++ packages/runner-e2b/src/factory.test.ts | 146 ++++++++ packages/runner-e2b/src/factory.ts | 115 ++++++ packages/runner-e2b/src/index.ts | 4 + packages/runner-e2b/src/job-handle.ts | 89 +++++ packages/runner-e2b/src/opened-env.test.ts | 164 +++++++++ packages/runner-e2b/src/opened-env.ts | 327 +++++++++++++++++ packages/runner-e2b/src/sdk-imports.test.ts | 16 + packages/runner-e2b/src/sdk.ts | 155 +++++++++ .../runner-e2b/src/template-build.test.ts | 164 +++++++++ packages/runner-e2b/src/template-build.ts | 105 ++++++ packages/runner-e2b/tsconfig.json | 11 + .../runner-e2b/vitest.integration.config.ts | 10 + .../src/index.ts | 45 ++- 30 files changed, 1904 insertions(+), 39 deletions(-) create mode 100644 .github/workflows/e2b-runner-integration.yml create mode 100644 packages/runner-e2b/README.md create mode 100644 packages/runner-e2b/package.json create mode 100644 packages/runner-e2b/src/e2b-execution-env.integration.ts create mode 100644 packages/runner-e2b/src/factory.test.ts create mode 100644 packages/runner-e2b/src/factory.ts create mode 100644 packages/runner-e2b/src/index.ts create mode 100644 packages/runner-e2b/src/job-handle.ts create mode 100644 packages/runner-e2b/src/opened-env.test.ts create mode 100644 packages/runner-e2b/src/opened-env.ts create mode 100644 packages/runner-e2b/src/sdk-imports.test.ts create mode 100644 packages/runner-e2b/src/sdk.ts create mode 100644 packages/runner-e2b/src/template-build.test.ts create mode 100644 packages/runner-e2b/src/template-build.ts create mode 100644 packages/runner-e2b/tsconfig.json create mode 100644 packages/runner-e2b/vitest.integration.config.ts diff --git a/.github/workflows/e2b-runner-integration.yml b/.github/workflows/e2b-runner-integration.yml new file mode 100644 index 0000000000..74dd3dc2a8 --- /dev/null +++ b/.github/workflows/e2b-runner-integration.yml @@ -0,0 +1,19 @@ +name: E2B Runner Integration +on: + workflow_dispatch: + schedule: + - cron: "17 9 * * *" +jobs: + e2b-runner-integration: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: actions/setup-node@v4 + with: + node-version: 20 + - run: npm ci + - run: npm run test:integration -w @poe-code/runner-e2b + env: + E2B_API_KEY: ${{ secrets.E2B_API_KEY }} diff --git a/docs/plans/e2b-integration.md b/docs/plans/e2b-integration.md index 2fba7a6cc2..b907343794 100644 --- a/docs/plans/e2b-integration.md +++ b/docs/plans/e2b-integration.md @@ -406,7 +406,7 @@ tasks: status: implement: done test: done - commit: open + commit: done - id: runner-e2b-package title: Create runner-e2b package implementing e2bExecutionEnvFactory @@ -466,8 +466,8 @@ tasks: Register the factory in the same `register-factories` module as host and docker. status: - implement: open - test: open + implement: done + test: done commit: open - id: cli-runtime-jobs diff --git a/docs/plans/e2b-integration.md.lock b/docs/plans/e2b-integration.md.lock index f2b869a5fc..782f84c595 100644 --- a/docs/plans/e2b-integration.md.lock +++ b/docs/plans/e2b-integration.md.lock @@ -1 +1 @@ -{"pid":82216,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T00:15:46.242Z"} \ No newline at end of file +{"pid":82216,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T00:35:15.891Z"} \ No newline at end of file diff --git a/eslint.config.js b/eslint.config.js index b19352d7b9..0a0578cb4a 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -65,5 +65,22 @@ export default tseslint.config( }, ], }, + }, + { + files: ['packages/runner-e2b/src/**/*.ts'], + ignores: ['packages/runner-e2b/src/sdk.ts'], + rules: { + 'no-restricted-imports': [ + 'error', + { + paths: [ + { + name: 'e2b', + message: 'Import the E2B SDK only from packages/runner-e2b/src/sdk.ts.', + }, + ], + }, + ], + }, } ); diff --git a/package-lock.json b/package-lock.json index 1269da08bd..e34785c69d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -72,6 +72,7 @@ "@poe-code/providers": "*", "@poe-code/py-poe-spawn": "*", "@poe-code/ralph": "*", + "@poe-code/runner-e2b": "*", "@poe-code/superintendent": "*", "@poe-code/task-list": "*", "@poe-code/workspace-resolver": "*", @@ -175,6 +176,12 @@ "node": ">=18" } }, + "node_modules/@bufbuild/protobuf": { + "version": "2.12.0", + "resolved": "https://registry.npmjs.org/@bufbuild/protobuf/-/protobuf-2.12.0.tgz", + "integrity": "sha512-B/XlCaFIP8LOwzo+bz5uFzATYokcwCKQcghqnlfwSmM5eX/qTkvDBnDPs+gXtX/RyjxJ4DRikECcPJbyALA8FA==", + "license": "(Apache-2.0 AND BSD-3-Clause)" + }, "node_modules/@clack/core": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/@clack/core/-/core-1.2.0.tgz", @@ -197,6 +204,25 @@ "sisteransi": "^1.0.5" } }, + "node_modules/@connectrpc/connect": { + "version": "2.0.0-rc.3", + "resolved": "https://registry.npmjs.org/@connectrpc/connect/-/connect-2.0.0-rc.3.tgz", + "integrity": "sha512-ARBt64yEyKbanyRETTjcjJuHr2YXorzQo0etyS5+P6oSeW8xEuzajA9g+zDnMcj1hlX2dQE93foIWQGfpru7gQ==", + "license": "Apache-2.0", + "peerDependencies": { + "@bufbuild/protobuf": "^2.2.0" + } + }, + "node_modules/@connectrpc/connect-web": { + "version": "2.0.0-rc.3", + "resolved": "https://registry.npmjs.org/@connectrpc/connect-web/-/connect-web-2.0.0-rc.3.tgz", + "integrity": "sha512-w88P8Lsn5CCsA7MFRl2e6oLY4J/5toiNtJns/YJrlyQaWOy3RO8pDgkz+iIkG98RPMhj2thuBvsd3Cn4DKKCkw==", + "license": "Apache-2.0", + "peerDependencies": { + "@bufbuild/protobuf": "^2.2.0", + "@connectrpc/connect": "2.0.0-rc.3" + } + }, "node_modules/@emnapi/core": { "version": "1.10.0", "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz", @@ -933,6 +959,27 @@ "url": "https://github.com/sponsors/nzakas" } }, + "node_modules/@isaacs/cliui": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-9.0.0.tgz", + "integrity": "sha512-AokJm4tuBHillT+FpMtxQ60n8ObyXBatq7jD2/JA9dxbDDokKQm8KMht5ibGzLVU9IJDIKK4TPKgMHEYMn3lMg==", + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/@isaacs/fs-minipass": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz", + "integrity": "sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==", + "license": "ISC", + "dependencies": { + "minipass": "^7.0.4" + }, + "engines": { + "node": ">=18.0.0" + } + }, "node_modules/@jridgewell/resolve-uri": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", @@ -1738,6 +1785,10 @@ "resolved": "packages/ralph", "link": true }, + "node_modules/@poe-code/runner-e2b": { + "resolved": "packages/runner-e2b", + "link": true + }, "node_modules/@poe-code/superintendent": { "resolved": "packages/superintendent", "link": true @@ -3244,6 +3295,15 @@ "url": "https://github.com/chalk/chalk?sponsor=1" } }, + "node_modules/chownr": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz", + "integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==", + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=18" + } + }, "node_modules/code-block-writer": { "version": "13.0.3", "resolved": "https://registry.npmjs.org/code-block-writer/-/code-block-writer-13.0.3.tgz", @@ -3280,6 +3340,12 @@ "node": ">=20" } }, + "node_modules/compare-versions": { + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/compare-versions/-/compare-versions-6.1.1.tgz", + "integrity": "sha512-4hm4VPpIecmlg59CHXnRDnqGplJFrbLG4aFEl5vl6cK1u76ws3LLvX7ikFnTDl5vo39sjWD6AaDPYodJp/NNHg==", + "license": "MIT" + }, "node_modules/concat-map": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", @@ -3369,7 +3435,6 @@ "version": "7.0.6", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", - "dev": true, "license": "MIT", "dependencies": { "path-key": "^3.1.0", @@ -3474,6 +3539,19 @@ "node": ">=0.3.1" } }, + "node_modules/dockerfile-ast": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/dockerfile-ast/-/dockerfile-ast-0.7.1.tgz", + "integrity": "sha512-oX/A4I0EhSkGqrFv0YuvPkBUSYp1XiY8O8zAKc8Djglx8ocz+JfOr8gP0ryRMC2myqvDLagmnZaU9ot1vG2ijw==", + "license": "MIT", + "dependencies": { + "vscode-languageserver-textdocument": "^1.0.8", + "vscode-languageserver-types": "^3.17.3" + }, + "engines": { + "node": "*" + } + }, "node_modules/dunder-proto": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", @@ -3489,6 +3567,27 @@ "node": ">= 0.4" } }, + "node_modules/e2b": { + "version": "2.19.4", + "resolved": "https://registry.npmjs.org/e2b/-/e2b-2.19.4.tgz", + "integrity": "sha512-9RefLykkjzVu+kUQfX5RxBonmZb08jcXIrRCRmZ8zutbG2bKV6PPyhV9O7mcyB1ZVHHO9UD2G8Z0VtY0lC+AAQ==", + "license": "MIT", + "dependencies": { + "@bufbuild/protobuf": "^2.6.2", + "@connectrpc/connect": "2.0.0-rc.3", + "@connectrpc/connect-web": "2.0.0-rc.3", + "chalk": "^5.3.0", + "compare-versions": "^6.1.0", + "dockerfile-ast": "^0.7.1", + "glob": "^11.1.0", + "openapi-fetch": "^0.14.1", + "platform": "^1.3.6", + "tar": "^7.5.11" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/ee-first": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", @@ -4193,6 +4292,22 @@ "dev": true, "license": "ISC" }, + "node_modules/foreground-child": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz", + "integrity": "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==", + "license": "ISC", + "dependencies": { + "cross-spawn": "^7.0.6", + "signal-exit": "^4.0.1" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/forwarded": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", @@ -4290,6 +4405,30 @@ "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1" } }, + "node_modules/glob": { + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/glob/-/glob-11.1.0.tgz", + "integrity": "sha512-vuNwKSaKiqm7g0THUBu2x7ckSs3XJLXE+2ssL7/MfTGPLLcrJQ/4Uq1CjPTtO5cCIiRxqvN6Twy1qOwhL0Xjcw==", + "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", + "license": "BlueOak-1.0.0", + "dependencies": { + "foreground-child": "^3.3.1", + "jackspeak": "^4.1.1", + "minimatch": "^10.1.1", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^2.0.0" + }, + "bin": { + "glob": "dist/esm/bin.mjs" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/glob-parent": { "version": "6.0.2", "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", @@ -4320,6 +4459,42 @@ "tslib": "2" } }, + "node_modules/glob/node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/glob/node_modules/brace-expansion": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.5.tgz", + "integrity": "sha512-VZznLgtwhn+Mact9tfiwx64fA9erHH/MCXEUfB/0bX/6Fz6ny5EGTXYltMocqg4xFAQZtnO3DHWWXi8RiuN7cQ==", + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/glob/node_modules/minimatch": { + "version": "10.2.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz", + "integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==", + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.5" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/globals": { "version": "17.5.0", "resolved": "https://registry.npmjs.org/globals/-/globals-17.5.0.tgz", @@ -4672,7 +4847,6 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", - "dev": true, "license": "ISC" }, "node_modules/istanbul-lib-coverage": { @@ -4714,6 +4888,21 @@ "node": ">=8" } }, + "node_modules/jackspeak": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-4.2.3.tgz", + "integrity": "sha512-ykkVRwrYvFm1nb2AJfKKYPr0emF6IiXDYUaFx4Zn9ZuIH7MrzEZ3sD5RlqGXNRpHtvUHJyOnCEFxOlNDtGo7wg==", + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/cliui": "^9.0.0" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/jetbrains-mono": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/jetbrains-mono/-/jetbrains-mono-1.0.6.tgz", @@ -5283,6 +5472,27 @@ "node": "*" } }, + "node_modules/minipass": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", + "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/minizlib": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz", + "integrity": "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==", + "license": "MIT", + "dependencies": { + "minipass": "^7.1.2" + }, + "engines": { + "node": ">= 18" + } + }, "node_modules/ms": { "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", @@ -5503,6 +5713,21 @@ } } }, + "node_modules/openapi-fetch": { + "version": "0.14.1", + "resolved": "https://registry.npmjs.org/openapi-fetch/-/openapi-fetch-0.14.1.tgz", + "integrity": "sha512-l7RarRHxlEZYjMLd/PR0slfMVse2/vvIAGm75/F7J6MlQ8/b9uUQmUF2kCPrQhJqMXSxmYWObVgeYXbFYzZR+A==", + "license": "MIT", + "dependencies": { + "openapi-typescript-helpers": "^0.0.15" + } + }, + "node_modules/openapi-typescript-helpers": { + "version": "0.0.15", + "resolved": "https://registry.npmjs.org/openapi-typescript-helpers/-/openapi-typescript-helpers-0.0.15.tgz", + "integrity": "sha512-opyTPaunsklCBpTK8JGef6mfPhLSnyy5a0IN9vKtx3+4aExf+KxEqYwIy3hqkedXIB97u357uLMJsOnm3GVjsw==", + "license": "MIT" + }, "node_modules/opencode-poe-auth": { "resolved": "packages/opencode-poe-auth", "link": true @@ -5557,6 +5782,12 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/package-json-from-dist": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz", + "integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==", + "license": "BlueOak-1.0.0" + }, "node_modules/parent-module": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", @@ -5607,12 +5838,27 @@ "version": "3.1.1", "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", - "dev": true, "license": "MIT", "engines": { "node": ">=8" } }, + "node_modules/path-scurry": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz", + "integrity": "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==", + "license": "BlueOak-1.0.0", + "dependencies": { + "lru-cache": "^11.0.0", + "minipass": "^7.1.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/path-to-regexp": { "version": "8.4.2", "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz", @@ -5660,6 +5906,12 @@ "node": ">=16.20.0" } }, + "node_modules/platform": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/platform/-/platform-1.3.6.tgz", + "integrity": "sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg==", + "license": "MIT" + }, "node_modules/poe-oauth": { "resolved": "packages/poe-oauth", "link": true @@ -6038,7 +6290,6 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", - "dev": true, "license": "MIT", "dependencies": { "shebang-regex": "^3.0.0" @@ -6051,7 +6302,6 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", - "dev": true, "license": "MIT", "engines": { "node": ">=8" @@ -6152,6 +6402,18 @@ "dev": true, "license": "ISC" }, + "node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/simple-wcswidth": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/simple-wcswidth/-/simple-wcswidth-1.1.2.tgz", @@ -6251,6 +6513,22 @@ "node": ">=8" } }, + "node_modules/tar": { + "version": "7.5.13", + "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.13.tgz", + "integrity": "sha512-tOG/7GyXpFevhXVh8jOPJrmtRpOTsYqUIkVdVooZYJS/z8WhfQUX8RJILmeuJNinGAMSu1veBr4asSHFt5/hng==", + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/fs-minipass": "^4.0.0", + "chownr": "^3.0.0", + "minipass": "^7.1.2", + "minizlib": "^3.1.0", + "yallist": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/terminal-pilot": { "resolved": "packages/terminal-pilot", "link": true @@ -6847,11 +7125,22 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/vscode-languageserver-textdocument": { + "version": "1.0.12", + "resolved": "https://registry.npmjs.org/vscode-languageserver-textdocument/-/vscode-languageserver-textdocument-1.0.12.tgz", + "integrity": "sha512-cxWNPesCnQCcMPeenjKKsOCKQZ/L6Tv19DTRIGuLWe32lyzWhihGVJ/rcckZXJxfdKCFvRLS3fpBIsV/ZGX4zA==", + "license": "MIT" + }, + "node_modules/vscode-languageserver-types": { + "version": "3.17.5", + "resolved": "https://registry.npmjs.org/vscode-languageserver-types/-/vscode-languageserver-types-3.17.5.tgz", + "integrity": "sha512-Ld1VelNuX9pdF39h2Hgaeb5hEZM2Z3jUrrMgWQAu82jMtZp7p3vJT3BzToKtZI7NgQssZje5o0zryOrhQvzQAg==", + "license": "MIT" + }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", - "dev": true, "license": "ISC", "dependencies": { "isexe": "^2.0.0" @@ -6912,6 +7201,15 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/yallist": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz", + "integrity": "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==", + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=18" + } + }, "node_modules/yaml": { "version": "2.8.3", "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.3.tgz", @@ -6991,7 +7289,10 @@ }, "packages/agent-script": { "name": "@poe-code/agent-script", - "version": "0.0.1" + "version": "0.0.1", + "bin": { + "poe-agent-script": "dist/cli.js" + } }, "packages/agent-skill-config": { "name": "@poe-code/agent-skill-config", @@ -7010,7 +7311,8 @@ "@poe-code/design-system": "*", "@poe-code/poe-acp-client": "*", "@poe-code/poe-code-config": "*", - "@poe-code/process-runner": "*" + "@poe-code/process-runner": "*", + "@poe-code/runner-e2b": "*" } }, "packages/auth-store": { @@ -7253,6 +7555,16 @@ "yaml": "^2.8.3" } }, + "packages/runner-e2b": { + "name": "@poe-code/runner-e2b", + "version": "0.0.1", + "dependencies": { + "@poe-code/agent-harness-tools": "*", + "@poe-code/poe-code-config": "*", + "@poe-code/process-runner": "*", + "e2b": "^2.19.4" + } + }, "packages/superintendent": { "name": "@poe-code/superintendent", "version": "0.0.1", diff --git a/package.json b/package.json index fbb35ca5be..5223e36710 100644 --- a/package.json +++ b/package.json @@ -151,6 +151,7 @@ "@poe-code/providers": "*", "@poe-code/py-poe-spawn": "*", "@poe-code/ralph": "*", + "@poe-code/runner-e2b": "*", "@poe-code/superintendent": "*", "@poe-code/task-list": "*", "@poe-code/workspace-resolver": "*", diff --git a/packages/agent-harness-tools/src/run-poe-command.test.ts b/packages/agent-harness-tools/src/run-poe-command.test.ts index e6f4e325e3..1edb7bf476 100644 --- a/packages/agent-harness-tools/src/run-poe-command.test.ts +++ b/packages/agent-harness-tools/src/run-poe-command.test.ts @@ -25,9 +25,12 @@ interface RecordingState { interface MockEnv extends OpenedEnv { closed: boolean; + detached: boolean; + detachedJobContext: { id: string; tool: string; argv: string[] } | null; downloads: { conflictPolicy: "refuse" | "overwrite" }[]; execSpecs: RunSpec[]; fs: LogStreamFs; + setDetachedJobContext(context: { id: string; tool: string; argv: string[] }): void; uploads: number; } @@ -78,11 +81,13 @@ function createOpenSpec(overrides: Partial = {}): OpenSpec { }; } -function createMockEnv(opts: { - result?: Promise; - commandExitCode?: number; - download?: DownloadResult; -} = {}): MockEnv { +function createMockEnv( + opts: { + result?: Promise; + commandExitCode?: number; + download?: DownloadResult; + } = {} +): MockEnv { const result = opts.result ?? Promise.resolve({ exitCode: 0 }); const commandExitCode = opts.commandExitCode ?? 0; const download = opts.download ?? { files: 0, bytes: 0, conflicts: [] }; @@ -91,6 +96,8 @@ function createMockEnv(opts: { id: "env-1", job: null, closed: false, + detached: false, + detachedJobContext: null, downloads: [], execSpecs: [], fs: rawFs as unknown as LogStreamFs, @@ -116,7 +123,24 @@ function createMockEnv(opts: { }; }, async detach() { - throw new Error("detach is not used by runPoeCommand"); + env.detached = true; + return { + id: env.detachedJobContext?.id ?? "job", + envId: env.id, + tool: env.detachedJobContext?.tool ?? "poe-code", + argv: env.detachedJobContext?.argv ?? [], + async status() { + return "running" as const; + }, + async *stream() {}, + async wait() { + return { exitCode: 0 }; + }, + async kill() {} + }; + }, + setDetachedJobContext(context) { + env.detachedJobContext = context; }, shell(): RunHandle { throw new Error("shell is not used by runPoeCommand"); @@ -236,9 +260,49 @@ describe("runPoeCommand", () => { expect(result.jobId).toMatch(/^[0-9A-HJKMNP-TV-Z]{26}$/); expect(statuses).toEqual(["pending", "running"]); expect(env.closed).toBe(false); + expect(env.detached).toBe(true); + expect(env.detachedJobContext).toEqual({ + id: result.jobId, + tool: "poe-code", + argv: ["poe-code", "--help"] + }); expect(env.downloads).toEqual([]); }); + it("waits for workspace upload before starting the command", async () => { + const { state } = createRecordingState(); + const upload = deferred(); + const env = createMockEnv(); + const exec = env.exec.bind(env); + let uploadResolved = false; + let execStarted = false; + + env.uploadWorkspace = async () => { + const result = await upload.promise; + uploadResolved = true; + return result; + }; + env.exec = (spec): RunHandle => { + execStarted = true; + expect(uploadResolved).toBe(true); + return exec(spec); + }; + + const run = runPoeCommand({ + factory: createFactory(env), + openSpec: createOpenSpec(), + detach: false, + state + }); + + await new Promise((resolve) => setImmediate(resolve)); + expect(execStarted).toBe(false); + + upload.resolve({ files: 1, bytes: 12, skipped: [] }); + await expect(run).resolves.toMatchObject({ kind: "sync", exitCode: 0 }); + expect(execStarted).toBe(true); + }); + it("returns the download result with conflicts from sync mode", async () => { const { state } = createRecordingState(); const env = createMockEnv({ diff --git a/packages/agent-harness-tools/src/run-poe-command.ts b/packages/agent-harness-tools/src/run-poe-command.ts index 1a399cc516..931bc8418a 100644 --- a/packages/agent-harness-tools/src/run-poe-command.ts +++ b/packages/agent-harness-tools/src/run-poe-command.ts @@ -43,6 +43,7 @@ export async function runPoeCommand(opts: { try { const upload = env.uploadWorkspace(); + await Promise.all([pendingJob, upload]); const argv = wrapCommand ? wrapForLogTee(opts.openSpec.jobLabel.argv, jobId) : opts.openSpec.jobLabel.argv; @@ -64,16 +65,20 @@ export async function runPoeCommand(opts: { handle.stdin?.end(execution.input); } - const runningJob = Promise.all([pendingJob, upload]).then(() => - opts.state.jobs.update(jobId, { - status: "running", - env_id: env.id, - started_at: new Date().toISOString() - }) - ); + const runningJob = opts.state.jobs.update(jobId, { + status: "running", + env_id: env.id, + started_at: new Date().toISOString() + }); if (opts.detach) { await runningJob; + setDetachedJobContext(env, { + id: jobId, + tool: opts.openSpec.jobLabel.tool, + argv: opts.openSpec.jobLabel.argv + }); + await env.detach(); shouldClose = false; return { kind: "detached", jobId, envId: env.id }; } @@ -328,6 +333,16 @@ function toLogStreamEnv(env: OpenedEnv): LogStreamEnv { return candidate.fs === undefined ? {} : { fs: candidate.fs }; } +function setDetachedJobContext( + env: OpenedEnv, + context: { id: string; tool: string; argv: string[] } +): void { + const candidate = env as OpenedEnv & { + setDetachedJobContext?: (value: { id: string; tool: string; argv: string[] }) => void; + }; + candidate.setDetachedJobContext?.(context); +} + function isPromiseLike(value: T | Promise): value is Promise { return typeof (value as Promise).then === "function"; } diff --git a/packages/agent-spawn/package.json b/packages/agent-spawn/package.json index 7540cff8a2..5db0a9f22c 100644 --- a/packages/agent-spawn/package.json +++ b/packages/agent-spawn/package.json @@ -33,6 +33,7 @@ "@poe-code/design-system": "*", "@poe-code/poe-acp-client": "*", "@poe-code/poe-code-config": "*", - "@poe-code/process-runner": "*" + "@poe-code/process-runner": "*", + "@poe-code/runner-e2b": "*" } } diff --git a/packages/agent-spawn/src/acp/acp.test.ts b/packages/agent-spawn/src/acp/acp.test.ts index e49c4d4a16..33847eaf2e 100644 --- a/packages/agent-spawn/src/acp/acp.test.ts +++ b/packages/agent-spawn/src/acp/acp.test.ts @@ -183,7 +183,7 @@ function createMockChildProcess( const error = options.error; if (options.autoClose !== false) { - queueMicrotask(() => { + setImmediate(() => { for (const line of lines) { stdout.write(`${line}\n`, "utf8"); } @@ -1283,6 +1283,8 @@ describe("acp/spawnStreaming", () => { const eventsPromise = collect(events); + await vi.waitFor(() => expect(spawnChildProcess).toHaveBeenCalledTimes(1)); + mock.child.stdout.end(); mock.child.stderr.end(); mock.child.emit("close", 0, null); diff --git a/packages/agent-spawn/src/agent-spawn.test.ts b/packages/agent-spawn/src/agent-spawn.test.ts index 8bab53dae0..a253bcb03c 100644 --- a/packages/agent-spawn/src/agent-spawn.test.ts +++ b/packages/agent-spawn/src/agent-spawn.test.ts @@ -63,7 +63,7 @@ function createMockChildProcess( const errorOutput = options.stderr ?? ""; if (options.autoClose !== false) { - queueMicrotask(() => { + setImmediate(() => { if (output) { stdout.write(output, "utf8"); } @@ -899,6 +899,8 @@ describe("spawn", () => { activityTimeoutMs: 5000 }); + await vi.waitFor(() => expect(spawnChildProcess).toHaveBeenCalledTimes(1)); + // Process exits before timeout streams.stdout.end(); streams.stderr.end(); diff --git a/packages/agent-spawn/src/register-factories.ts b/packages/agent-spawn/src/register-factories.ts index 13939d3d3b..2c7a653f74 100644 --- a/packages/agent-spawn/src/register-factories.ts +++ b/packages/agent-spawn/src/register-factories.ts @@ -2,14 +2,20 @@ import { spawn as spawnChildProcess } from "node:child_process"; import { registerExecutionEnvFactory } from "@poe-code/agent-harness-tools"; import type { ExecutionEnvFactory, OpenedEnv, RunSpec } from "@poe-code/agent-harness-tools"; import { dockerExecutionEnvFactory, hostExecutionEnvFactory } from "@poe-code/process-runner"; +import { e2bExecutionEnvFactory } from "@poe-code/runner-e2b"; registerExecutionEnvFactory(hostExecutionEnvFactory); registerExecutionEnvFactory(dockerExecutionEnvFactory); +registerExecutionEnvFactory(e2bExecutionEnvFactory); -if (process.env.VITEST === "true") { +if (isVitest()) { registerExecutionEnvFactory(createTestHostExecutionEnvFactory()); } +function isVitest(): boolean { + return process.env.VITEST !== undefined || process.env.VITEST_POOL_ID !== undefined; +} + function createTestHostExecutionEnvFactory(): ExecutionEnvFactory { return { type: "host", diff --git a/packages/agent-spawn/src/spawn-interactive.test.ts b/packages/agent-spawn/src/spawn-interactive.test.ts index 7cd4055332..0351bdc69d 100644 --- a/packages/agent-spawn/src/spawn-interactive.test.ts +++ b/packages/agent-spawn/src/spawn-interactive.test.ts @@ -28,7 +28,7 @@ function createMockInheritProcess(exitCode = 0): ChildProcess { (child as any).stdout = null; (child as any).stderr = null; - queueMicrotask(() => { + setImmediate(() => { child.emit("close", exitCode, null); }); diff --git a/packages/agent-spawn/src/spawn-log-options.test.ts b/packages/agent-spawn/src/spawn-log-options.test.ts index 9e0dd69f09..40bdcf3452 100644 --- a/packages/agent-spawn/src/spawn-log-options.test.ts +++ b/packages/agent-spawn/src/spawn-log-options.test.ts @@ -35,7 +35,7 @@ function createMockChildProcess({ return true; }; - queueMicrotask(() => { + setImmediate(() => { if (stdout) stdoutStream.write(stdout); stdoutStream.end(); if (stderr) stderrStream.write(stderr); diff --git a/packages/runner-e2b/README.md b/packages/runner-e2b/README.md new file mode 100644 index 0000000000..3150d3fbec --- /dev/null +++ b/packages/runner-e2b/README.md @@ -0,0 +1,15 @@ +# @poe-code/runner-e2b + +E2B execution environment runner for poe-code. + +## Environment Variables + +- `E2B_API_KEY` - E2B API key used by default when `runtime.api_key_env` is not configured. + +## Runtime Config + +- `runtime.api_key_env` - Host environment variable containing the E2B API key. Defaults to `E2B_API_KEY`. +- `runtime.cpu` - CPU count used when building an E2B template. +- `runtime.memory_mb` - Memory in megabytes used when building an E2B template. +- `runtime.timeout_minutes` - Sandbox timeout in minutes. +- `runtime.preserve_after_exit_hours` - Hours to keep a detached sandbox alive after job exit. Defaults to `24`; valid range is `0` to `168`. diff --git a/packages/runner-e2b/package.json b/packages/runner-e2b/package.json new file mode 100644 index 0000000000..c7a31c358f --- /dev/null +++ b/packages/runner-e2b/package.json @@ -0,0 +1,34 @@ +{ + "name": "@poe-code/runner-e2b", + "version": "0.0.1", + "private": true, + "type": "module", + "main": "dist/index.js", + "types": "dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.js" + } + }, + "scripts": { + "build": "tsc", + "test": "cd ../.. && vitest run --config vitest.config.ts packages/runner-e2b/src", + "test:unit": "cd ../.. && vitest run --config vitest.config.ts packages/runner-e2b/src", + "test:integration": "cd ../.. && vitest run --config packages/runner-e2b/vitest.integration.config.ts" + }, + "dependencies": { + "@poe-code/agent-harness-tools": "*", + "@poe-code/poe-code-config": "*", + "@poe-code/process-runner": "*", + "e2b": "^2.19.4" + }, + "files": [ + "dist" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/poe-platform/poe-code.git", + "directory": "packages/runner-e2b" + } +} diff --git a/packages/runner-e2b/src/e2b-execution-env.integration.ts b/packages/runner-e2b/src/e2b-execution-env.integration.ts new file mode 100644 index 0000000000..e61e8b1e14 --- /dev/null +++ b/packages/runner-e2b/src/e2b-execution-env.integration.ts @@ -0,0 +1,42 @@ +import { mkdtemp, readFile, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { describe, expect, it } from "vitest"; +import { e2bExecutionEnvFactory } from "./factory.js"; + +describe.skipIf(!process.env.E2B_API_KEY)("e2bExecutionEnvFactory integration", () => { + it("builds a minimal template, opens a sandbox, runs echo, downloads, and closes", async () => { + const cwd = await mkdtemp(path.join(tmpdir(), "poe-e2b-integration-")); + await writeFile(path.join(cwd, "Dockerfile"), "FROM node:22-slim\n", "utf8"); + const env = await e2bExecutionEnvFactory.open({ + cwd, + runtime: { + type: "e2b", + dockerfile: "Dockerfile", + build_context: ".", + build_args: {}, + mounts: [], + timeout_minutes: 10 + }, + env: {}, + uploadIgnoreFiles: [], + jobLabel: { tool: "node", argv: ["node", "-e", "console.log('ok')"] } + }); + + try { + await env.uploadWorkspace(); + const handle = env.exec({ + command: "sh", + args: ["-c", "echo ok > e2b-output.txt"], + cwd + }); + await expect(handle.result).resolves.toEqual({ exitCode: 0 }); + await expect(env.downloadWorkspace({ conflictPolicy: "overwrite" })).resolves.toMatchObject({ + conflicts: [] + }); + await expect(readFile(path.join(cwd, "e2b-output.txt"), "utf8")).resolves.toBe("ok\n"); + } finally { + await env.close(); + } + }, 300_000); +}); diff --git a/packages/runner-e2b/src/factory.test.ts b/packages/runner-e2b/src/factory.test.ts new file mode 100644 index 0000000000..c8d28a803d --- /dev/null +++ b/packages/runner-e2b/src/factory.test.ts @@ -0,0 +1,146 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { buildOrResolveTemplate } from "./template-build.js"; +import { createSandbox, connectSandbox } from "./sdk.js"; + +vi.mock("./template-build.js", () => ({ + buildOrResolveTemplate: vi.fn() +})); + +vi.mock("./sdk.js", () => ({ + createSandbox: vi.fn(), + connectSandbox: vi.fn() +})); + +describe("e2bExecutionEnvFactory", () => { + beforeEach(() => { + vi.clearAllMocks(); + delete process.env.E2B_API_KEY; + delete process.env.CUSTOM_E2B_API_KEY; + vi.mocked(buildOrResolveTemplate).mockResolvedValue({ + templateId: "tmpl_built", + cached: false + }); + vi.mocked(createSandbox).mockResolvedValue(createSandboxMock("sb_open")); + vi.mocked(connectSandbox).mockResolvedValue(createSandboxMock("sb_attached")); + }); + + it("opens a sandbox from a direct template id and runtime api key env", async () => { + process.env.CUSTOM_E2B_API_KEY = "key_from_env"; + const { e2bExecutionEnvFactory } = await import("./factory.js"); + + const env = await e2bExecutionEnvFactory.open({ + cwd: "/repo", + runtime: { + type: "e2b", + template_id: "tmpl_configured", + build_args: {}, + mounts: [], + api_key_env: "CUSTOM_E2B_API_KEY", + timeout_minutes: 30 + }, + env: { NODE_ENV: "test" }, + uploadIgnoreFiles: [], + jobLabel: { tool: "node", argv: ["node", "--version"] } + }); + + expect(env.id).toBe("sb_open"); + expect(buildOrResolveTemplate).not.toHaveBeenCalled(); + expect(createSandbox).toHaveBeenCalledWith({ + apiKey: "key_from_env", + templateId: "tmpl_configured", + env: { NODE_ENV: "test" }, + timeoutMinutes: 30 + }); + }); + + it("prefers auth.providers.e2b over runtime api key env", async () => { + process.env.E2B_API_KEY = "key_from_env"; + const { e2bExecutionEnvFactory } = await import("./factory.js"); + + await e2bExecutionEnvFactory.open({ + cwd: "/repo", + runtime: { + type: "e2b", + template_id: "tmpl_configured", + build_args: {}, + mounts: [] + }, + auth: { providers: { e2b: { api_key: "key_from_auth" } } }, + env: {}, + uploadIgnoreFiles: [], + jobLabel: { tool: "node", argv: ["node"] } + } as Parameters[0]); + + expect(createSandbox).toHaveBeenCalledWith( + expect.objectContaining({ apiKey: "key_from_auth" }) + ); + }); + + it("builds a template when template_id is absent", async () => { + process.env.E2B_API_KEY = "key_from_env"; + const state = { templates: { get: vi.fn(), put: vi.fn() }, jobs: {} }; + const { e2bExecutionEnvFactory } = await import("./factory.js"); + + await e2bExecutionEnvFactory.open({ + cwd: "/repo", + runtime: { + type: "e2b", + dockerfile: "Dockerfile", + build_context: "sandbox", + build_args: {}, + mounts: [] + }, + state: state as Parameters[0]["state"], + env: {}, + uploadIgnoreFiles: [], + jobLabel: { tool: "node", argv: ["node"] } + }); + + expect(buildOrResolveTemplate).toHaveBeenCalledWith({ + runtime: expect.objectContaining({ type: "e2b" }), + dockerfilePath: "/repo/Dockerfile", + buildContext: "/repo/sandbox", + state, + apiKey: "key_from_env" + }); + expect(createSandbox).toHaveBeenCalledWith( + expect.objectContaining({ templateId: "tmpl_built" }) + ); + }); + + it("attaches to an existing sandbox id", async () => { + process.env.E2B_API_KEY = "key_from_env"; + const { e2bExecutionEnvFactory } = await import("./factory.js"); + + const env = await e2bExecutionEnvFactory.attach("sb_existing"); + + expect(env.id).toBe("sb_attached"); + expect(connectSandbox).toHaveBeenCalledWith("sb_existing", "key_from_env"); + }); +}); + +function createSandboxMock(id: string) { + return { + sandboxId: id, + commands: { + list: vi.fn(), + run: vi.fn(), + connect: vi.fn(), + sendStdin: vi.fn(), + closeStdin: vi.fn(), + kill: vi.fn() + }, + files: { + read: vi.fn(), + write: vi.fn(), + watchDir: vi.fn() + }, + pty: { + create: vi.fn(), + sendInput: vi.fn(), + kill: vi.fn() + }, + setTimeout: vi.fn(), + kill: vi.fn() + }; +} diff --git a/packages/runner-e2b/src/factory.ts b/packages/runner-e2b/src/factory.ts new file mode 100644 index 0000000000..851c78a9d0 --- /dev/null +++ b/packages/runner-e2b/src/factory.ts @@ -0,0 +1,115 @@ +import path from "node:path"; +import type { E2bRuntime } from "@poe-code/poe-code-config"; +import type { ExecutionEnvFactory, OpenSpec, OpenedEnv } from "@poe-code/agent-harness-tools"; +import { createSandbox, connectSandbox } from "./sdk.js"; +import { buildOrResolveTemplate } from "./template-build.js"; +import { createOpenedE2bEnv } from "./opened-env.js"; + +export const e2bExecutionEnvFactory: ExecutionEnvFactory = { + type: "e2b", + supportsDetach: true, + async open(spec): Promise { + const runtime = parseE2bRuntime(spec.runtime); + const apiKey = resolveApiKey(spec, runtime); + const templateId = + runtime.template_id ?? + ( + await buildOrResolveTemplate({ + runtime, + dockerfilePath: path.resolve( + spec.cwd, + runtime.dockerfile ?? path.join(".poe-code", "Dockerfile") + ), + buildContext: path.resolve(spec.cwd, runtime.build_context ?? "."), + state: spec.state, + apiKey + }) + ).templateId; + const sandbox = await createSandbox({ + apiKey, + templateId, + env: spec.env, + timeoutMinutes: runtime.timeout_minutes + }); + + return createOpenedE2bEnv({ sandbox, spec, runtime }); + }, + async attach(envId): Promise { + const apiKey = process.env.E2B_API_KEY?.trim(); + const sandbox = await connectSandbox(envId, apiKey && apiKey.length > 0 ? apiKey : undefined); + return createOpenedE2bEnv({ + sandbox, + spec: { + cwd: "/workspace", + runtime: { + type: "e2b", + build_args: {}, + mounts: [], + api_key_env: "E2B_API_KEY", + preserve_after_exit_hours: 24 + }, + env: {}, + uploadIgnoreFiles: [], + jobLabel: { tool: "e2b", argv: [] } + }, + runtime: { + type: "e2b", + build_args: {}, + mounts: [], + api_key_env: "E2B_API_KEY", + preserve_after_exit_hours: 24 + } + }); + } +}; + +function parseE2bRuntime(runtime: unknown): E2bRuntime { + if (!runtime || typeof runtime !== "object" || Array.isArray(runtime)) { + throw new Error("e2b runtime must be an object"); + } + const record = runtime as Record; + if (record.type !== "e2b") { + throw new Error('e2b runtime type must be "e2b"'); + } + return record as unknown as E2bRuntime; +} + +function resolveApiKey(spec: OpenSpec, runtime: E2bRuntime): string { + const authKey = readAuthProviderKey(spec); + if (authKey !== null) { + return authKey; + } + + const envName = runtime.api_key_env ?? "E2B_API_KEY"; + const apiKey = process.env[envName]?.trim(); + if (apiKey && apiKey.length > 0) { + return apiKey; + } + + throw new Error(`No E2B API key found. Set ${envName} or configure auth.providers.e2b.`); +} + +function readAuthProviderKey(spec: OpenSpec): string | null { + const auth = (spec as OpenSpec & { auth?: unknown }).auth; + if (!auth || typeof auth !== "object" || Array.isArray(auth)) { + return null; + } + const providers = (auth as { providers?: unknown }).providers; + if (!providers || typeof providers !== "object" || Array.isArray(providers)) { + return null; + } + const e2b = (providers as { e2b?: unknown }).e2b; + if (typeof e2b === "string") { + const trimmed = e2b.trim(); + return trimmed.length > 0 ? trimmed : null; + } + if (!e2b || typeof e2b !== "object" || Array.isArray(e2b)) { + return null; + } + const apiKey = (e2b as { api_key?: unknown }).api_key; + if (typeof apiKey !== "string") { + return null; + } + const trimmed = apiKey.trim(); + return trimmed.length > 0 ? trimmed : null; +} diff --git a/packages/runner-e2b/src/index.ts b/packages/runner-e2b/src/index.ts new file mode 100644 index 0000000000..c16ad1245c --- /dev/null +++ b/packages/runner-e2b/src/index.ts @@ -0,0 +1,4 @@ +import type { ExecutionEnvFactory } from "@poe-code/agent-harness-tools"; +import { e2bExecutionEnvFactory as factory } from "./factory.js"; + +export const e2bExecutionEnvFactory: ExecutionEnvFactory = factory; diff --git a/packages/runner-e2b/src/job-handle.ts b/packages/runner-e2b/src/job-handle.ts new file mode 100644 index 0000000000..0715b6b873 --- /dev/null +++ b/packages/runner-e2b/src/job-handle.ts @@ -0,0 +1,89 @@ +import path from "node:path"; +import type { JobHandle, JobStatus, LogChunk } from "@poe-code/agent-harness-tools"; +import { streamLogFile, waitForExit, type LogStreamFs } from "@poe-code/agent-harness-tools"; +import type { E2bSandbox } from "./sdk.js"; + +const JOB_DIR = "/tmp/poe-jobs"; + +export function createE2bJobHandle(input: { + sandbox: E2bSandbox; + envId: string; + jobId: string; + tool: string; + argv: string[]; + pid: number; + preserveAfterExitHours: number; +}): JobHandle { + const fs = createE2bLogStreamFs(input.sandbox); + + return { + id: input.jobId, + envId: input.envId, + tool: input.tool, + argv: input.argv, + async status(): Promise { + const exit = await readExitCode(input.sandbox, input.jobId); + if (exit !== null) { + return "exited"; + } + + const processes = await input.sandbox.commands.list(); + return processes.some((process) => process.pid === input.pid) ? "running" : "lost"; + }, + stream(opts = {}): AsyncIterable { + return streamLogFile({ fs }, input.jobId, opts); + }, + async wait(): Promise<{ exitCode: number }> { + const result = await waitForExit({ fs }, input.jobId); + const preserveMs = input.preserveAfterExitHours * 60 * 60 * 1000; + if (preserveMs > 0) { + await input.sandbox.setTimeout(preserveMs); + } + return result; + }, + async kill(): Promise { + await input.sandbox.commands.kill(input.pid); + } + }; +} + +export function createE2bLogStreamFs(sandbox: E2bSandbox): LogStreamFs { + return { + promises: { + async readFile(filePath) { + return Buffer.from(await sandbox.files.read(filePath, { format: "bytes" })); + } + }, + watch(filePath, listener) { + let closed = false; + let stop: (() => void) | null = null; + void sandbox.files + .watchDir(path.dirname(filePath), listener, { recursive: false }) + .then((handle) => { + if (closed) { + void handle.stop(); + return; + } + stop = () => { + void handle.stop(); + }; + }); + return { + close() { + closed = true; + stop?.(); + } + } as ReturnType>; + } + }; +} + +async function readExitCode(sandbox: E2bSandbox, jobId: string): Promise { + try { + const contents = await sandbox.files.read(`${JOB_DIR}/${jobId}.exit`); + const exitCode = Number(contents.trim()); + return Number.isInteger(exitCode) ? exitCode : null; + } catch { + return null; + } +} diff --git a/packages/runner-e2b/src/opened-env.test.ts b/packages/runner-e2b/src/opened-env.test.ts new file mode 100644 index 0000000000..31b3ddc48e --- /dev/null +++ b/packages/runner-e2b/src/opened-env.test.ts @@ -0,0 +1,164 @@ +import { describe, expect, it, vi } from "vitest"; +import { createOpenedE2bEnv } from "./opened-env.js"; + +describe("createOpenedE2bEnv", () => { + it("executes commands with E2B command run and returns a RunHandle", async () => { + const commandHandle = { + pid: 321, + wait: vi.fn().mockResolvedValue({ exitCode: 0 }), + kill: vi.fn() + }; + const sandbox = createSandboxMock(); + sandbox.commands.run.mockResolvedValue(commandHandle); + const env = createOpenedE2bEnv({ + sandbox, + runtime: createRuntime(), + spec: createSpec() + }); + + const handle = env.exec({ + command: "printf", + args: ["ok"], + cwd: "/repo", + env: { A: "1" }, + stdin: "pipe", + stdout: "pipe", + stderr: "pipe" + }); + + await expect(handle.result).resolves.toEqual({ exitCode: 0 }); + expect(sandbox.commands.run).toHaveBeenCalledWith("'printf' 'ok'", { + background: true, + cwd: "/repo", + envs: { A: "1" }, + stdin: true, + onStdout: expect.any(Function), + onStderr: expect.any(Function) + }); + }); + + it("creates a job handle for the last running command and preserves sandbox timeout on wait", async () => { + const commandHandle = { + pid: 321, + wait: vi.fn().mockResolvedValue({ exitCode: 0 }), + kill: vi.fn() + }; + const sandbox = createSandboxMock(); + sandbox.commands.run.mockResolvedValue(commandHandle); + sandbox.commands.list.mockResolvedValue([{ pid: 321, cmd: "node", args: [] }]); + sandbox.files.read.mockImplementation(async (filePath: string) => { + if (filePath.endsWith(".exit")) { + return "7\n"; + } + return new Uint8Array(); + }); + const env = createOpenedE2bEnv({ + sandbox, + runtime: { ...createRuntime(), preserve_after_exit_hours: 2 }, + spec: createSpec() + }); + + const handle = env.exec({ command: "node", args: ["agent.js"] }); + await new Promise((resolve) => setImmediate(resolve)); + env.setDetachedJobContext({ id: "job-1", tool: "node", argv: ["node", "agent.js"] }); + const job = await env.detach(); + + expect(job.id).toBe("job-1"); + expect(sandbox.setTimeout).toHaveBeenCalledWith(2 * 60 * 60 * 1000); + expect(sandbox.setTimeout).toHaveBeenCalledTimes(1); + await expect(job.status()).resolves.toBe("exited"); + await expect(job.wait()).resolves.toEqual({ exitCode: 7 }); + expect(sandbox.setTimeout).toHaveBeenCalledWith(2 * 60 * 60 * 1000); + expect(sandbox.setTimeout).toHaveBeenCalledTimes(2); + handle.kill(); + expect(commandHandle.kill).toHaveBeenCalled(); + }); + + it("opens shell through E2B PTY", async () => { + const ptyHandle = { + pid: 12, + wait: vi.fn().mockResolvedValue({ exitCode: 0 }), + kill: vi.fn() + }; + const sandbox = createSandboxMock(); + sandbox.pty.create.mockResolvedValue(ptyHandle); + const env = createOpenedE2bEnv({ + sandbox, + runtime: createRuntime(), + spec: createSpec() + }); + + const handle = env.shell(); + + await expect(handle.result).resolves.toEqual({ exitCode: 0 }); + expect(sandbox.pty.create).toHaveBeenCalledWith({ + cols: expect.any(Number), + rows: expect.any(Number), + cwd: "/repo", + envs: {}, + onData: expect.any(Function) + }); + }); + + it("exposes remote job log files for wrapped sync execution", async () => { + const sandbox = createSandboxMock(); + sandbox.files.read.mockResolvedValue(new Uint8Array(Buffer.from("log\n"))); + const env = createOpenedE2bEnv({ + sandbox, + runtime: createRuntime(), + spec: createSpec() + }); + + const contents = await env.fs.promises.readFile("/tmp/poe-jobs/job-1.log"); + + expect(contents.toString("utf8")).toBe("log\n"); + expect(sandbox.files.read).toHaveBeenCalledWith("/tmp/poe-jobs/job-1.log", { + format: "bytes" + }); + }); +}); + +function createRuntime() { + return { + type: "e2b" as const, + build_args: {}, + mounts: [], + preserve_after_exit_hours: 24 + }; +} + +function createSpec() { + return { + cwd: "/repo", + runtime: createRuntime(), + env: {}, + uploadIgnoreFiles: [], + jobLabel: { tool: "node", argv: ["node", "agent.js"] } + }; +} + +function createSandboxMock() { + return { + sandboxId: "sb_test", + commands: { + list: vi.fn(), + run: vi.fn(), + connect: vi.fn(), + sendStdin: vi.fn(), + closeStdin: vi.fn(), + kill: vi.fn() + }, + files: { + read: vi.fn(), + write: vi.fn(), + watchDir: vi.fn().mockResolvedValue({ stop: vi.fn() }) + }, + pty: { + create: vi.fn(), + sendInput: vi.fn(), + kill: vi.fn() + }, + setTimeout: vi.fn(), + kill: vi.fn() + }; +} diff --git a/packages/runner-e2b/src/opened-env.ts b/packages/runner-e2b/src/opened-env.ts new file mode 100644 index 0000000000..895ff776ab --- /dev/null +++ b/packages/runner-e2b/src/opened-env.ts @@ -0,0 +1,327 @@ +import { mkdtempSync, rmSync } from "node:fs"; +import { readFile, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { PassThrough, Writable } from "node:stream"; +import type { E2bRuntime } from "@poe-code/poe-code-config"; +import type { + LogStreamFs, + OpenSpec, + OpenedEnv, + RunHandle, + RunSpec +} from "@poe-code/agent-harness-tools"; +import { createHostRunner, type Runner } from "@poe-code/process-runner"; +import { createE2bJobHandle, createE2bLogStreamFs } from "./job-handle.js"; +import { readableToString, toArrayBuffer, type E2bCommandHandle, type E2bSandbox } from "./sdk.js"; + +interface DetachedJobContext { + id: string; + tool: string; + argv: string[]; +} + +export interface E2bOpenedEnv extends OpenedEnv { + fs: LogStreamFs; + setDetachedJobContext(context: DetachedJobContext): void; +} + +export function createOpenedE2bEnv(input: { + sandbox: E2bSandbox; + spec: OpenSpec; + runtime: E2bRuntime; +}): E2bOpenedEnv { + const hostRunner = input.spec.hostRunner ?? createHostRunner(); + let lastProcess: { started: Promise } | null = null; + let detachedJobContext: DetachedJobContext | null = null; + + const env: E2bOpenedEnv = { + id: input.sandbox.sandboxId, + job: null, + fs: createE2bLogStreamFs(input.sandbox), + setDetachedJobContext(context) { + detachedJobContext = context; + }, + async uploadWorkspace() { + const tempDir = mkdtempSync(path.join(tmpdir(), "poe-e2b-upload-")); + const archivePath = path.join(tempDir, "workspace.tar"); + try { + await runOrThrow(hostRunner, { + command: "tar", + args: [ + ...input.spec.uploadIgnoreFiles.flatMap((ignored) => ["--exclude", ignored]), + "-cf", + archivePath, + "-C", + input.spec.cwd, + "." + ], + stdout: "pipe", + stderr: "pipe" + }); + await input.sandbox.files.write( + "/tmp/poe-workspace-upload.tar", + toArrayBuffer(await readFile(archivePath)) + ); + await runRemoteOrThrow( + input.sandbox, + `mkdir -p ${shellQuote(input.spec.cwd)} && tar -xf /tmp/poe-workspace-upload.tar -C ${shellQuote(input.spec.cwd)}` + ); + return { files: 0, bytes: 0, skipped: [] }; + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } + }, + async downloadWorkspace(opts) { + const tempDir = mkdtempSync(path.join(tmpdir(), "poe-e2b-download-")); + const archivePath = path.join(tempDir, "workspace.tar"); + try { + await runRemoteOrThrow( + input.sandbox, + `tar -cf /tmp/poe-workspace-download.tar -C ${shellQuote(input.spec.cwd)} .` + ); + const archive = await input.sandbox.files.read("/tmp/poe-workspace-download.tar", { + format: "bytes" + }); + await writeFile(archivePath, Buffer.from(archive)); + await runOrThrow(hostRunner, { + command: "tar", + args: [ + opts.conflictPolicy === "refuse" ? "-xkf" : "-xf", + archivePath, + "-C", + input.spec.cwd + ], + stdout: "pipe", + stderr: "pipe" + }); + return { files: 0, bytes: archive.byteLength, conflicts: [] }; + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } + }, + exec(spec) { + const handle = runE2bCommand(input.sandbox, spec); + lastProcess = { started: handle.started }; + return handle; + }, + async detach() { + if (detachedJobContext === null) { + throw new Error("Cannot detach E2B environment before a job context is registered."); + } + if (lastProcess === null) { + throw new Error("Cannot detach E2B environment before a command is running."); + } + const command = await lastProcess.started; + const preserveAfterExitHours = input.runtime.preserve_after_exit_hours ?? 24; + const preserveMs = preserveAfterExitHours * 60 * 60 * 1000; + if (preserveMs > 0) { + await input.sandbox.setTimeout(preserveMs); + } + return createE2bJobHandle({ + sandbox: input.sandbox, + envId: input.sandbox.sandboxId, + jobId: detachedJobContext.id, + tool: detachedJobContext.tool, + argv: detachedJobContext.argv, + pid: command.pid, + preserveAfterExitHours + }); + }, + shell() { + const shellSpec = input.spec.shellSpec; + const command = shellSpec?.command ?? input.spec.env.SHELL ?? "sh"; + return runE2bPty(input.sandbox, { + command, + ...(shellSpec?.args ? { args: shellSpec.args } : {}), + cwd: input.spec.cwd, + env: shellSpec && "env" in shellSpec ? shellSpec.env : input.spec.env, + stdin: "inherit", + stdout: "inherit", + stderr: "inherit", + tty: true + }); + }, + async close() { + await input.sandbox.kill(); + } + }; + + return env; +} + +function runE2bCommand( + sandbox: E2bSandbox, + spec: RunSpec +): RunHandle & { e2bHandle: E2bCommandHandle | null; started: Promise } { + const stdout = spec.stdout === "inherit" ? null : new PassThrough(); + const stderr = spec.stderr === "inherit" ? null : new PassThrough(); + let e2bHandle: E2bCommandHandle | null = null; + const stdin = + spec.stdin === "pipe" + ? new Writable({ + write(chunk, _encoding, callback) { + if (e2bHandle === null) { + callback(new Error("E2B command stdin is not ready.")); + return; + } + sandbox.commands + .sendStdin(e2bHandle.pid, Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk))) + .then(() => callback(), callback); + }, + final(callback) { + if (e2bHandle === null || sandbox.commands.closeStdin === undefined) { + callback(); + return; + } + sandbox.commands.closeStdin(e2bHandle.pid).then(() => callback(), callback); + } + }) + : null; + const command = shellCommand([spec.command, ...(spec.args ?? [])]); + const started = sandbox.commands.run(command, { + background: true, + cwd: spec.cwd, + envs: spec.env, + stdin: spec.stdin === "pipe", + onStdout(data) { + stdout?.write(data); + if (spec.stdout === "inherit") { + process.stdout.write(data); + } + }, + onStderr(data) { + stderr?.write(data); + if (spec.stderr === "inherit") { + process.stderr.write(data); + } + } + }) as Promise; + const result = started + .then((handle) => { + e2bHandle = handle; + return handle.wait(); + }) + .then( + (result) => { + stdout?.end(); + stderr?.end(); + return { exitCode: result.exitCode ?? 0 }; + }, + (error: unknown) => { + stdout?.end(); + stderr?.end(); + if (isExitError(error)) { + return { exitCode: error.exitCode }; + } + return { exitCode: 1 }; + } + ); + + return { + get pid() { + return e2bHandle?.pid ?? null; + }, + stdin, + stdout, + stderr, + result, + kill() { + void e2bHandle?.kill(); + }, + get e2bHandle() { + return e2bHandle; + }, + started + }; +} + +function runE2bPty(sandbox: E2bSandbox, spec: RunSpec): RunHandle { + const stdout = new PassThrough(); + let handleRef: E2bCommandHandle | null = null; + const stdin = new Writable({ + write(chunk, _encoding, callback) { + if (handleRef === null) { + callback(new Error("E2B PTY stdin is not ready.")); + return; + } + sandbox.pty + .sendInput(handleRef.pid, Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk))) + .then(() => callback(), callback); + } + }); + const started = sandbox.pty.create({ + cols: process.stdout.columns || 80, + rows: process.stdout.rows || 24, + cwd: spec.cwd, + envs: spec.env, + onData(data) { + stdout.write(Buffer.from(data)); + if (spec.stdout === "inherit") { + process.stdout.write(Buffer.from(data)); + } + } + }); + const result = started + .then((handle) => { + handleRef = handle; + return handle.wait(); + }) + .then( + (result) => { + stdout.end(); + return { exitCode: result.exitCode ?? 0 }; + }, + () => { + stdout.end(); + return { exitCode: 1 }; + } + ); + + return { + get pid() { + return handleRef?.pid ?? null; + }, + stdin: spec.stdin === "inherit" ? process.stdin : stdin, + stdout: spec.stdout === "inherit" ? null : stdout, + stderr: null, + result, + kill() { + void (handleRef === null ? undefined : sandbox.pty.kill(handleRef.pid)); + } + }; +} + +async function runRemoteOrThrow(sandbox: E2bSandbox, command: string): Promise { + const result = await sandbox.commands.run(command); + if ("exitCode" in result && result.exitCode !== 0) { + throw new Error(`E2B command failed with exit code ${result.exitCode}: ${command}`); + } +} + +async function runOrThrow(runner: Runner, spec: RunSpec): Promise { + const handle = runner.exec(spec); + const stderr = readableToString(handle.stderr); + const result = await handle.result; + if (result.exitCode !== 0) { + throw new Error( + `Command failed with exit code ${result.exitCode}: ${spec.command} ${(spec.args ?? []).join(" ")}\n${await stderr}` + ); + } +} + +function shellCommand(argv: string[]): string { + return argv.map(shellQuote).join(" "); +} + +function shellQuote(value: string): string { + return `'${value.replaceAll("'", "'\\''")}'`; +} + +function isExitError(error: unknown): error is { exitCode: number } { + return Boolean( + error && + typeof error === "object" && + typeof (error as { exitCode?: unknown }).exitCode === "number" + ); +} diff --git a/packages/runner-e2b/src/sdk-imports.test.ts b/packages/runner-e2b/src/sdk-imports.test.ts new file mode 100644 index 0000000000..b855703b94 --- /dev/null +++ b/packages/runner-e2b/src/sdk-imports.test.ts @@ -0,0 +1,16 @@ +import { readFile } from "node:fs/promises"; +import path from "node:path"; +import { describe, expect, it } from "vitest"; + +describe("E2B SDK import boundary", () => { + it("keeps e2b SDK imports isolated to sdk.ts", async () => { + const srcDir = path.resolve("packages/runner-e2b/src"); + const files = ["factory.ts", "index.ts", "job-handle.ts", "opened-env.ts", "template-build.ts"]; + + for (const file of files) { + const source = await readFile(path.join(srcDir, file), "utf8"); + expect(source).not.toContain('from "e2b"'); + expect(source).not.toContain("from 'e2b'"); + } + }); +}); diff --git a/packages/runner-e2b/src/sdk.ts b/packages/runner-e2b/src/sdk.ts new file mode 100644 index 0000000000..3c3ae7d22e --- /dev/null +++ b/packages/runner-e2b/src/sdk.ts @@ -0,0 +1,155 @@ +import { Template, Sandbox } from "e2b"; +import type { Readable } from "node:stream"; + +export interface E2bSandbox { + readonly sandboxId: string; + readonly commands: E2bCommands; + readonly files: E2bFiles; + readonly pty: E2bPty; + setTimeout(timeoutMs: number): Promise; + kill(): Promise; +} + +export interface E2bCommands { + list(): Promise; + run(command: string, opts?: E2bCommandOptions): Promise; + connect(pid: number, opts?: E2bCommandConnectOptions): Promise; + sendStdin(pid: number, data: string | Uint8Array): Promise; + closeStdin?(pid: number): Promise; + kill(pid: number): Promise; +} + +export interface E2bPty { + create(opts: E2bPtyOptions): Promise; + sendInput(pid: number, data: Uint8Array): Promise; + kill(pid: number): Promise; +} + +export interface E2bFiles { + read(path: string, opts: { format: "bytes" }): Promise; + read(path: string): Promise; + write(path: string, data: string | ArrayBuffer | Blob | ReadableStream): Promise; + watchDir( + path: string, + onEvent: () => void | Promise, + opts?: { recursive?: boolean; onExit?: (error?: Error) => void | Promise } + ): Promise<{ stop(): Promise }>; +} + +export interface E2bProcessInfo { + pid: number; + cmd: string; + args: string[]; +} + +export interface E2bCommandOptions { + background?: boolean; + cwd?: string; + envs?: Record; + stdin?: boolean; + timeoutMs?: number; + onStdout?: (data: string) => void | Promise; + onStderr?: (data: string) => void | Promise; +} + +export interface E2bPtyOptions { + cols: number; + rows: number; + cwd?: string; + envs?: Record; + timeoutMs?: number; + onData: (data: Uint8Array) => void | Promise; +} + +export interface E2bCommandConnectOptions { + timeoutMs?: number; + onStdout?: (data: string) => void | Promise; + onStderr?: (data: string) => void | Promise; +} + +export interface E2bCommandResult { + exitCode?: number; + stdout?: string; + stderr?: string; +} + +export interface E2bCommandHandle { + readonly pid: number; + wait(): Promise; + kill(): Promise; +} + +export interface CreateSandboxOptions { + apiKey: string; + templateId: string; + env: Record; + timeoutMinutes?: number; +} + +export interface BuildTemplateOptions { + apiKey: string; + name: string; + dockerfilePath: string; + buildContext: string; + cpu?: number; + memoryMb?: number; +} + +export interface BuildTemplateResult { + templateId: string; +} + +export interface SandboxInfo { + sandboxId: string; +} + +export async function createSandbox(opts: CreateSandboxOptions): Promise { + return Sandbox.create(opts.templateId, { + apiKey: opts.apiKey, + envs: opts.env, + ...(opts.timeoutMinutes === undefined ? {} : { timeoutMs: opts.timeoutMinutes * 60_000 }) + }) as Promise; +} + +export async function connectSandbox(id: string, apiKey?: string): Promise { + return Sandbox.connect(id, apiKey === undefined ? undefined : { apiKey }) as Promise; +} + +export async function buildTemplate(opts: BuildTemplateOptions): Promise { + const template = Template({ fileContextPath: opts.buildContext }).fromDockerfile( + opts.dockerfilePath + ); + const result = await Template.build(template, opts.name, { + apiKey: opts.apiKey, + ...(opts.cpu === undefined ? {} : { cpuCount: opts.cpu }), + ...(opts.memoryMb === undefined ? {} : { memoryMB: opts.memoryMb }) + }); + return { templateId: result.templateId }; +} + +export async function listSandboxes(apiKey?: string): Promise { + const paginator = Sandbox.list(apiKey === undefined ? undefined : { apiKey }); + const sandboxes: SandboxInfo[] = []; + while (paginator.hasNext) { + sandboxes.push(...((await paginator.nextItems()) as SandboxInfo[])); + } + return sandboxes; +} + +export function toArrayBuffer(buffer: Buffer): ArrayBuffer { + const output = new ArrayBuffer(buffer.byteLength); + new Uint8Array(output).set(buffer); + return output; +} + +export async function readableToString(stream: Readable | null): Promise { + if (stream === null) { + return ""; + } + stream.setEncoding("utf8"); + const chunks: string[] = []; + for await (const chunk of stream) { + chunks.push(String(chunk)); + } + return chunks.join(""); +} diff --git a/packages/runner-e2b/src/template-build.test.ts b/packages/runner-e2b/src/template-build.test.ts new file mode 100644 index 0000000000..4e2e78c1dc --- /dev/null +++ b/packages/runner-e2b/src/template-build.test.ts @@ -0,0 +1,164 @@ +import { readdir, readFile } from "node:fs/promises"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { buildTemplate } from "./sdk.js"; + +vi.mock("node:fs/promises", () => ({ + readdir: vi.fn(), + readFile: vi.fn() +})); + +vi.mock("./sdk.js", () => ({ + buildTemplate: vi.fn() +})); + +describe("buildOrResolveTemplate", () => { + const files = new Map(); + + beforeEach(() => { + vi.clearAllMocks(); + files.clear(); + files.set("/repo/Dockerfile", "FROM node:22\n"); + files.set("/repo/package.json", "{\"name\":\"test\"}\n"); + files.set("/repo/src/index.js", "console.log('one')\n"); + vi.mocked(readFile).mockImplementation(async (filePath) => { + const contents = files.get(String(filePath)); + if (contents === undefined) { + throw Object.assign(new Error(`ENOENT: ${String(filePath)}`), { code: "ENOENT" }); + } + return Buffer.from(contents); + }); + vi.mocked(readdir).mockImplementation(async (dirPath) => { + if (String(dirPath) === "/repo") { + return [dirent("Dockerfile", "file"), dirent("package.json", "file"), dirent("src", "dir")]; + } + if (String(dirPath) === "/repo/src") { + return [dirent("index.js", "file")]; + } + return []; + }); + vi.mocked(buildTemplate).mockResolvedValue({ templateId: "tmpl_built" }); + }); + + it("uses the cached E2B template for matching dockerfile and build args", async () => { + const state = createState({ + hash: "unused", + template_id: "tmpl_cached", + runtime_type: "e2b", + dockerfile_path: "/repo/Dockerfile", + built_at: "2026-05-03T00:00:00.000Z" + }); + const { buildOrResolveTemplate } = await import("./template-build.js"); + + const result = await buildOrResolveTemplate({ + apiKey: "e2b_key", + runtime: { + type: "e2b", + build_args: { ZED: "last", ALPHA: "first" }, + mounts: [] + }, + dockerfilePath: "/repo/Dockerfile", + buildContext: "/repo", + state + }); + + expect(result).toEqual({ templateId: "tmpl_cached", cached: true }); + expect(state.getCalls).toEqual([{ backend: "e2b", hash: expect.any(String) }]); + expect(buildTemplate).not.toHaveBeenCalled(); + }); + + it("builds and caches an E2B template on cache miss", async () => { + const state = createState(null); + const { buildOrResolveTemplate } = await import("./template-build.js"); + + const result = await buildOrResolveTemplate({ + apiKey: "e2b_key", + runtime: { + type: "e2b", + build_args: { A: "1" }, + mounts: [], + cpu: 4, + memory_mb: 4096 + }, + dockerfilePath: "/repo/Dockerfile", + buildContext: "/repo", + state + }); + + expect(result).toEqual({ templateId: "tmpl_built", cached: false }); + expect(buildTemplate).toHaveBeenCalledWith({ + apiKey: "e2b_key", + name: expect.stringMatching(/^poe-code-[a-f0-9]{32}$/), + dockerfilePath: "/repo/Dockerfile", + buildContext: "/repo", + cpu: 4, + memoryMb: 4096 + }); + expect(state.putCalls[0]).toMatchObject({ + backend: "e2b", + entry: { + hash: expect.any(String), + template_id: "tmpl_built", + runtime_type: "e2b", + dockerfile_path: "/repo/Dockerfile" + } + }); + }); + + it("changes the template cache hash when build context file contents change", async () => { + const state = createState(null); + const { buildOrResolveTemplate } = await import("./template-build.js"); + + await buildOrResolveTemplate({ + apiKey: "e2b_key", + runtime: { + type: "e2b", + build_args: {}, + mounts: [] + }, + dockerfilePath: "/repo/Dockerfile", + buildContext: "/repo", + state + }); + files.set("/repo/src/index.js", "console.log('two')\n"); + await buildOrResolveTemplate({ + apiKey: "e2b_key", + runtime: { + type: "e2b", + build_args: {}, + mounts: [] + }, + dockerfilePath: "/repo/Dockerfile", + buildContext: "/repo", + state + }); + + expect(state.getCalls[0]?.hash).not.toBe(state.getCalls[1]?.hash); + }); +}); + +function dirent(name: string, type: "dir" | "file") { + return { + name, + isDirectory: () => type === "dir", + isFile: () => type === "file" + }; +} + +function createState(template: unknown) { + const getCalls: Array<{ backend: string; hash: string }> = []; + const putCalls: Array<{ backend: string; entry: Record }> = []; + + return { + getCalls, + putCalls, + templates: { + async get(backend: string, hash: string) { + getCalls.push({ backend, hash }); + return template; + }, + async put(backend: string, entry: Record) { + putCalls.push({ backend, entry }); + } + } + }; +} diff --git a/packages/runner-e2b/src/template-build.ts b/packages/runner-e2b/src/template-build.ts new file mode 100644 index 0000000000..867b2e8af7 --- /dev/null +++ b/packages/runner-e2b/src/template-build.ts @@ -0,0 +1,105 @@ +import { createHash } from "node:crypto"; +import { readdir, readFile } from "node:fs/promises"; +import path from "node:path"; +import type { E2bRuntime, StateManager } from "@poe-code/poe-code-config"; +import { buildTemplate } from "./sdk.js"; + +export interface BuildOrResolveTemplateInput { + runtime: E2bRuntime; + dockerfilePath: string; + buildContext: string; + state?: Pick; + apiKey: string; +} + +export async function buildOrResolveTemplate( + input: BuildOrResolveTemplateInput +): Promise<{ templateId: string; cached: boolean }> { + const dockerfileBytes = await readFile(input.dockerfilePath); + const buildContextFiles = await readBuildContextFiles(input.buildContext); + const hash = hashTemplate(dockerfileBytes, buildContextFiles, input.runtime.build_args); + const cached = await input.state?.templates.get("e2b", hash); + + if (cached?.template_id !== undefined) { + return { templateId: cached.template_id, cached: true }; + } + + const built = await buildTemplate({ + apiKey: input.apiKey, + name: `poe-code-${hash.slice(0, 32)}`, + dockerfilePath: input.dockerfilePath, + buildContext: input.buildContext, + cpu: input.runtime.cpu, + memoryMb: input.runtime.memory_mb + }); + + await input.state?.templates.put("e2b", { + hash, + template_id: built.templateId, + runtime_type: "e2b", + dockerfile_path: input.dockerfilePath, + built_at: new Date().toISOString() + }); + + return { templateId: built.templateId, cached: false }; +} + +function hashTemplate( + dockerfileBytes: Buffer, + buildContextFiles: BuildContextFile[], + buildArgs: Record +): string { + const hash = createHash("sha256"); + hash.update(dockerfileBytes); + hash.update("\0"); + for (const file of buildContextFiles) { + hash.update(file.relativePath); + hash.update("\0"); + hash.update(file.bytes); + hash.update("\0"); + } + for (const [key, value] of Object.entries(buildArgs).sort(([left], [right]) => + left.localeCompare(right) + )) { + hash.update(key); + hash.update("="); + hash.update(value); + hash.update("\0"); + } + return hash.digest("hex"); +} + +interface BuildContextFile { + relativePath: string; + bytes: Buffer; +} + +async function readBuildContextFiles(buildContext: string): Promise { + const files: BuildContextFile[] = []; + await collectBuildContextFiles(buildContext, "", files); + return files.sort((left, right) => left.relativePath.localeCompare(right.relativePath)); +} + +async function collectBuildContextFiles( + buildContext: string, + relativeDir: string, + files: BuildContextFile[] +): Promise { + const absoluteDir = path.join(buildContext, relativeDir); + const entries = await readdir(absoluteDir, { withFileTypes: true }); + + for (const entry of entries) { + const relativePath = path.join(relativeDir, entry.name); + if (entry.isDirectory()) { + await collectBuildContextFiles(buildContext, relativePath, files); + continue; + } + if (!entry.isFile()) { + continue; + } + files.push({ + relativePath: relativePath.split(path.sep).join("/"), + bytes: await readFile(path.join(buildContext, relativePath)) + }); + } +} diff --git a/packages/runner-e2b/tsconfig.json b/packages/runner-e2b/tsconfig.json new file mode 100644 index 0000000000..84e5844380 --- /dev/null +++ b/packages/runner-e2b/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "outDir": "dist", + "rootDir": "src", + "noEmit": false, + "declaration": true + }, + "include": ["src"], + "exclude": ["**/*.test.ts", "**/*.integration.ts"] +} diff --git a/packages/runner-e2b/vitest.integration.config.ts b/packages/runner-e2b/vitest.integration.config.ts new file mode 100644 index 0000000000..5c59dce23b --- /dev/null +++ b/packages/runner-e2b/vitest.integration.config.ts @@ -0,0 +1,10 @@ +import { defineConfig } from "vitest/config"; +import rootConfig from "../../vitest.config.js"; + +export default defineConfig({ + ...rootConfig, + test: { + ...rootConfig.test, + include: ["packages/runner-e2b/src/e2b-execution-env.integration.ts"] + } +}); diff --git a/packages/tiny-http-mcp-oauth-test-server/src/index.ts b/packages/tiny-http-mcp-oauth-test-server/src/index.ts index 4c18ff6685..6377168a91 100644 --- a/packages/tiny-http-mcp-oauth-test-server/src/index.ts +++ b/packages/tiny-http-mcp-oauth-test-server/src/index.ts @@ -175,6 +175,27 @@ export function createMcpOAuthTestServer( const hostname = listenOptions.hostname ?? "127.0.0.1"; const requestedPort = listenOptions.port ?? 0; + let lastError: unknown; + + for (let attempt = 0; attempt < 10; attempt += 1) { + try { + return await listenOnce(hostname, requestedPort); + } catch (error) { + lastError = error; + if (requestedPort !== 0 || !isAddressInUseError(error)) { + throw error; + } + } + } + + throw lastError; + }, + }; + + async function listenOnce( + hostname: string, + requestedPort: number + ): Promise { const oauthHostname = configuredIssuer === undefined ? hostname @@ -215,15 +236,16 @@ export function createMcpOAuthTestServer( scopes, }, }); - const oauthHandle = await oauth.listen({ - port: oauthPort, - hostname: oauthHostname, - }); + let oauthHandle: Awaited> | undefined; let mcpHandle: | Awaited["listenHttp"]>> | undefined; try { + oauthHandle = await oauth.listen({ + port: oauthPort, + hostname: oauthHostname, + }); const resource = options.resource ?? buildUrl(hostname, fixedPort, mcpPath); const jwksVerifier = createJwksTokenVerifier({ jwksUrl: `${oauth.issuer}/.well-known/jwks.json`, @@ -276,7 +298,7 @@ export function createMcpOAuthTestServer( const results = await Promise.allSettled([ mcpHandle?.close(), - oauthHandle.close(), + oauthHandle?.close(), ]); const rejected = results.find( (result): result is PromiseRejectedResult => result.status === "rejected" @@ -290,7 +312,7 @@ export function createMcpOAuthTestServer( return currentHandle; } catch (error) { - const closeOperations = [oauthHandle.close()]; + const closeOperations = oauthHandle === undefined ? [] : [oauthHandle.close()]; if (mcpHandle !== undefined) { closeOperations.unshift(mcpHandle.close()); @@ -299,6 +321,13 @@ export function createMcpOAuthTestServer( await Promise.allSettled(closeOperations); throw error; } - }, - }; + } +} + +function isAddressInUseError(error: unknown): boolean { + return Boolean( + error && + typeof error === "object" && + (error as { code?: unknown }).code === "EADDRINUSE" + ); } From 48e6e93dd21dd8723eb529ec7d7b5f7011477e1c Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 19:54:37 -0500 Subject: [PATCH 019/111] feat: add runtime job controls --- docs/plans/e2b-integration.md | 6 +- docs/plans/e2b-integration.md.lock | 2 +- .../src/execution-env.test.ts | 3 +- .../agent-harness-tools/src/execution-env.ts | 19 +- .../agent-harness-tools/src/log-stream.ts | 24 +- packages/agent-spawn/src/acp/spawn.ts | 7 +- packages/agent-spawn/src/spawn-interactive.ts | 5 +- packages/agent-spawn/src/spawn.ts | 1 + packages/agent-spawn/src/types.ts | 1 + .../src/docker/docker-execution-env.ts | 45 ++- packages/process-runner/src/types.ts | 11 +- packages/runner-e2b/src/factory.ts | 9 +- packages/runner-e2b/src/job-handle.ts | 38 ++- packages/runner-e2b/src/opened-env.ts | 12 +- .../__snapshots__/runtime.test.ts.snap | 15 + src/cli/commands/runtime.test.ts | 280 ++++++++++++++++++ src/cli/commands/runtime/index.ts | 2 + src/cli/commands/runtime/jobs/attach.ts | 61 ++++ src/cli/commands/runtime/jobs/index.ts | 23 ++ src/cli/commands/runtime/jobs/logs.ts | 40 +++ src/cli/commands/runtime/jobs/ls.ts | 72 +++++ src/cli/commands/runtime/jobs/sandbox.ts | 21 ++ src/cli/commands/runtime/jobs/shared.ts | 177 +++++++++++ src/cli/commands/runtime/jobs/stop.ts | 57 ++++ src/cli/commands/runtime/jobs/sync.ts | 43 +++ src/cli/commands/spawn-command.test.ts | 31 ++ src/cli/commands/spawn.ts | 13 +- src/sdk/types.ts | 2 + 28 files changed, 986 insertions(+), 34 deletions(-) create mode 100644 src/cli/commands/runtime/jobs/attach.ts create mode 100644 src/cli/commands/runtime/jobs/index.ts create mode 100644 src/cli/commands/runtime/jobs/logs.ts create mode 100644 src/cli/commands/runtime/jobs/ls.ts create mode 100644 src/cli/commands/runtime/jobs/sandbox.ts create mode 100644 src/cli/commands/runtime/jobs/shared.ts create mode 100644 src/cli/commands/runtime/jobs/stop.ts create mode 100644 src/cli/commands/runtime/jobs/sync.ts diff --git a/docs/plans/e2b-integration.md b/docs/plans/e2b-integration.md index b907343794..4338d9ccab 100644 --- a/docs/plans/e2b-integration.md +++ b/docs/plans/e2b-integration.md @@ -468,7 +468,7 @@ tasks: status: implement: done test: done - commit: open + commit: done - id: cli-runtime-jobs title: Add poe-code runtime jobs ls/attach/logs/stop/sandbox commands @@ -520,8 +520,8 @@ tasks: Snapshot/screenshot tests for `runtime jobs ls` (mock state), `jobs logs` output, and `--detach` output. status: - implement: open - test: open + implement: done + test: done commit: open - id: qa-and-readmes diff --git a/docs/plans/e2b-integration.md.lock b/docs/plans/e2b-integration.md.lock index 782f84c595..d41d3ae65a 100644 --- a/docs/plans/e2b-integration.md.lock +++ b/docs/plans/e2b-integration.md.lock @@ -1 +1 @@ -{"pid":82216,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T00:35:15.891Z"} \ No newline at end of file +{"pid":82216,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T00:53:16.771Z"} \ No newline at end of file diff --git a/packages/agent-harness-tools/src/execution-env.test.ts b/packages/agent-harness-tools/src/execution-env.test.ts index 0e7cd3a604..b113acc6eb 100644 --- a/packages/agent-harness-tools/src/execution-env.test.ts +++ b/packages/agent-harness-tools/src/execution-env.test.ts @@ -78,8 +78,7 @@ describe("execution env registry", () => { expect(branchSites).toMatchInlineSnapshot(` [ - "execution-env.ts:89:const factory = executionEnvFactories.get(runtime.type);", - "execution-env.ts:92:\`No execution environment factory registered for runtime type "\${runtime.type}".\`", + "execution-env.ts:96:return selectExecutionEnvFactory(runtime.type);", ] `); }); diff --git a/packages/agent-harness-tools/src/execution-env.ts b/packages/agent-harness-tools/src/execution-env.ts index f166412492..973b44d7ab 100644 --- a/packages/agent-harness-tools/src/execution-env.ts +++ b/packages/agent-harness-tools/src/execution-env.ts @@ -12,7 +12,7 @@ export interface ExecutionEnvFactory { readonly type: ExecutionEnvType; readonly supportsDetach?: boolean; open(spec: OpenSpec): Promise; - attach(envId: string): Promise; + attach(envId: string, context?: AttachedJobContext): Promise; } export interface OpenSpec { @@ -57,6 +57,13 @@ export interface LogChunk { data: string; } +export interface AttachedJobContext { + jobId: string; + tool: string; + argv: string[]; + cwd: string; +} + export interface OpenedEnv { readonly id: string; readonly job: JobHandle | null; @@ -74,7 +81,7 @@ export interface JobHandle { readonly tool: string; readonly argv: string[]; status(): Promise; - stream(opts?: { sinceByte?: number }): AsyncIterable; + stream(opts?: { sinceByte?: number; since?: Date }): AsyncIterable; wait(): Promise<{ exitCode: number }>; kill(signal?: NodeJS.Signals): Promise; } @@ -86,10 +93,14 @@ export function registerExecutionEnvFactory(factory: ExecutionEnvFactory): void } export function selectExecutionEnv(runtime: RuntimeConfig): ExecutionEnvFactory { - const factory = executionEnvFactories.get(runtime.type); + return selectExecutionEnvFactory(runtime.type); +} + +export function selectExecutionEnvFactory(type: ExecutionEnvType): ExecutionEnvFactory { + const factory = executionEnvFactories.get(type); if (factory === undefined) { throw new Error( - `No execution environment factory registered for runtime type "${runtime.type}".` + `No execution environment factory registered for runtime type "${type}".` ); } return factory; diff --git a/packages/agent-harness-tools/src/log-stream.ts b/packages/agent-harness-tools/src/log-stream.ts index 1573bccce8..bb66d59d9a 100644 --- a/packages/agent-harness-tools/src/log-stream.ts +++ b/packages/agent-harness-tools/src/log-stream.ts @@ -12,6 +12,7 @@ export interface LogStreamEnv { export interface LogStreamFs { promises: { readFile(path: string): Promise; + stat?(path: string): Promise<{ mtimeMs: number }>; }; watch?: (path: string, listener: () => void) => FSWatcher; } @@ -36,13 +37,18 @@ export function wrapForLogTee(argv: string[], jobId: string): string[] { export async function* streamLogFile( env: LogStreamEnv, jobId: string, - opts: { sinceByte?: number } + opts: { sinceByte?: number; since?: Date } ): AsyncIterable { const fs = env.fs ?? nodeFs; const file = jobLogPath(jobId); let byteOffset = opts.sinceByte ?? 0; while (true) { + if (opts.since !== undefined && !(await wasModifiedSince(fs, file, opts.since))) { + await waitForLogChange(fs, file); + continue; + } + const result = await readLogChunk(fs, file, byteOffset); if (result !== null) { byteOffset = result.nextByteOffset; @@ -54,6 +60,22 @@ export async function* streamLogFile( } } +async function wasModifiedSince(fs: LogStreamFs, file: string, since: Date): Promise { + if (fs.promises.stat === undefined) { + return true; + } + + try { + const stat = await fs.promises.stat(file); + return stat.mtimeMs >= since.getTime(); + } catch (error) { + if (isNodeError(error) && error.code === "ENOENT") { + return false; + } + throw error; + } +} + export async function waitForExit( env: LogStreamEnv, jobId: string, diff --git a/packages/agent-spawn/src/acp/spawn.ts b/packages/agent-spawn/src/acp/spawn.ts index 6c55ece997..c101904d7d 100644 --- a/packages/agent-spawn/src/acp/spawn.ts +++ b/packages/agent-spawn/src/acp/spawn.ts @@ -240,7 +240,12 @@ export function spawnStreaming(options: SpawnStreamingOptions): SpawnStreamingRe }); if (runResult.kind === "detached") { - return { stdout: "", stderr: "", exitCode: 0 }; + return { + stdout: "", + stderr: "", + exitCode: 0, + detached: { jobId: runResult.jobId, envId: runResult.envId } + }; } result.stderr = runResult.stderr ?? ""; diff --git a/packages/agent-spawn/src/spawn-interactive.ts b/packages/agent-spawn/src/spawn-interactive.ts index 94e4b6e2cc..7f625af5a2 100644 --- a/packages/agent-spawn/src/spawn-interactive.ts +++ b/packages/agent-spawn/src/spawn-interactive.ts @@ -114,6 +114,9 @@ export async function spawnInteractive( return { stdout: "", stderr: "", - exitCode: result.kind === "sync" ? result.exitCode : 0 + exitCode: result.kind === "sync" ? result.exitCode : 0, + ...(result.kind === "detached" + ? { detached: { jobId: result.jobId, envId: result.envId } } + : {}) }; } diff --git a/packages/agent-spawn/src/spawn.ts b/packages/agent-spawn/src/spawn.ts index 34c736fda8..8f19b21d5a 100644 --- a/packages/agent-spawn/src/spawn.ts +++ b/packages/agent-spawn/src/spawn.ts @@ -221,6 +221,7 @@ export async function spawn( stdout: "", stderr: "", exitCode: 0, + detached: { jobId: result.jobId, envId: result.envId }, ...(logFilePath ? { logFile: logFilePath } : {}) }; } diff --git a/packages/agent-spawn/src/types.ts b/packages/agent-spawn/src/types.ts index 4dd6388450..3a602d0c7c 100644 --- a/packages/agent-spawn/src/types.ts +++ b/packages/agent-spawn/src/types.ts @@ -92,6 +92,7 @@ export interface SpawnResult { threadId?: string; usage?: SpawnUsage; logFile?: string; + detached?: { jobId: string; envId: string }; } export interface AutonomousResult { diff --git a/packages/process-runner/src/docker/docker-execution-env.ts b/packages/process-runner/src/docker/docker-execution-env.ts index 06d51642ab..a3a73f88f0 100644 --- a/packages/process-runner/src/docker/docker-execution-env.ts +++ b/packages/process-runner/src/docker/docker-execution-env.ts @@ -92,14 +92,15 @@ export const dockerExecutionEnvFactory: ExecutionEnvFactory = { context }); }, - async attach(envId): Promise { + async attach(envId, context): Promise { const engine = detectEngine(); return createDockerEnv({ id: envId, - spec: createAttachedSpec(), + spec: createAttachedSpec(context?.cwd), runner: createHostRunner(), engine, - context: detectContext() + context: detectContext(), + attachedJobId: context?.jobId }); } }; @@ -110,12 +111,16 @@ function createDockerEnv(input: { runner: Runner; engine: Engine; context: string | null; + attachedJobId?: string; }): OpenedEnv { const containerRef = input.id; return { id: containerRef, - job: null, + job: + input.attachedJobId === undefined + ? null + : createContainerJob(containerRef, input.runner, input.engine, input.context, input.attachedJobId), async uploadWorkspace() { const tempDir = mkdtempSync(path.join(tmpdir(), "poe-docker-upload-")); const archivePath = path.join(tempDir, "workspace.tar"); @@ -420,14 +425,15 @@ function createContainerName(): string { return `poe-env-${randomBytes(6).toString("hex")}`; } -async function createContainerJob( +function createContainerJob( containerId: string, runner: Runner, engine: Engine, - context: string | null + context: string | null, + jobId = containerId ) { return { - id: containerId, + id: jobId, envId: containerId, tool: "docker", argv: ["attach", containerId], @@ -451,7 +457,26 @@ async function createContainerJob( } return stdout.trim() === "running" ? ("running" as const) : ("exited" as const); }, - async *stream() {}, + async *stream(opts?: { sinceByte?: number }) { + const handle = runner.exec({ + command: engine, + args: [ + ...buildContextArgs(engine, context), + "exec", + containerId, + "sh", + "-c", + `test -f ${shellQuote(`/tmp/poe-jobs/${jobId}.log`)} && tail -c +${(opts?.sinceByte ?? 0) + 1} ${shellQuote(`/tmp/poe-jobs/${jobId}.log`)} || true` + ], + stdout: "pipe", + stderr: "pipe" + }); + const stdout = await readStream(handle.stdout); + await handle.result; + if (stdout.length > 0) { + yield { byteOffset: opts?.sinceByte ?? 0, data: stdout }; + } + }, async wait() { const handle = runner.exec({ command: engine, @@ -478,9 +503,9 @@ async function createContainerJob( }; } -function createAttachedSpec(): OpenSpec { +function createAttachedSpec(cwd = "/workspace"): OpenSpec { return { - cwd: "/workspace", + cwd, runtime: { type: "docker", image: "attached", diff --git a/packages/process-runner/src/types.ts b/packages/process-runner/src/types.ts index 3cbb442869..fb9d4ce4e0 100644 --- a/packages/process-runner/src/types.ts +++ b/packages/process-runner/src/types.ts @@ -41,7 +41,7 @@ export interface ExecutionEnvFactory { readonly type: ExecutionEnvType; readonly supportsDetach?: boolean; open(spec: OpenSpec): Promise; - attach(envId: string): Promise; + attach(envId: string, context?: AttachedJobContext): Promise; } export interface OpenSpec { @@ -102,6 +102,13 @@ export interface LogChunk { data: string; } +export interface AttachedJobContext { + jobId: string; + tool: string; + argv: string[]; + cwd: string; +} + export interface OpenedEnv { readonly id: string; readonly job: JobHandle | null; @@ -119,7 +126,7 @@ export interface JobHandle { readonly tool: string; readonly argv: string[]; status(): Promise; - stream(opts?: { sinceByte?: number }): AsyncIterable; + stream(opts?: { sinceByte?: number; since?: Date }): AsyncIterable; wait(): Promise<{ exitCode: number }>; kill(signal?: NodeJS.Signals): Promise; } diff --git a/packages/runner-e2b/src/factory.ts b/packages/runner-e2b/src/factory.ts index 851c78a9d0..175cc10f3f 100644 --- a/packages/runner-e2b/src/factory.ts +++ b/packages/runner-e2b/src/factory.ts @@ -34,13 +34,13 @@ export const e2bExecutionEnvFactory: ExecutionEnvFactory = { return createOpenedE2bEnv({ sandbox, spec, runtime }); }, - async attach(envId): Promise { + async attach(envId, context): Promise { const apiKey = process.env.E2B_API_KEY?.trim(); const sandbox = await connectSandbox(envId, apiKey && apiKey.length > 0 ? apiKey : undefined); return createOpenedE2bEnv({ sandbox, spec: { - cwd: "/workspace", + cwd: context?.cwd ?? "/workspace", runtime: { type: "e2b", build_args: {}, @@ -50,8 +50,9 @@ export const e2bExecutionEnvFactory: ExecutionEnvFactory = { }, env: {}, uploadIgnoreFiles: [], - jobLabel: { tool: "e2b", argv: [] } - }, + jobLabel: { tool: context?.tool ?? "e2b", argv: context?.argv ?? [] }, + ...(context?.jobId ? { detachedJobId: context.jobId } : {}) + } as OpenSpec & { detachedJobId?: string }, runtime: { type: "e2b", build_args: {}, diff --git a/packages/runner-e2b/src/job-handle.ts b/packages/runner-e2b/src/job-handle.ts index 0715b6b873..08e31af9ee 100644 --- a/packages/runner-e2b/src/job-handle.ts +++ b/packages/runner-e2b/src/job-handle.ts @@ -11,7 +11,7 @@ export function createE2bJobHandle(input: { jobId: string; tool: string; argv: string[]; - pid: number; + pid?: number; preserveAfterExitHours: number; }): JobHandle { const fs = createE2bLogStreamFs(input.sandbox); @@ -28,7 +28,11 @@ export function createE2bJobHandle(input: { } const processes = await input.sandbox.commands.list(); - return processes.some((process) => process.pid === input.pid) ? "running" : "lost"; + const isRunning = + input.pid === undefined + ? processes.some((process) => processMentionsJob(process, input.jobId)) + : processes.some((process) => process.pid === input.pid); + return isRunning ? "running" : "lost"; }, stream(opts = {}): AsyncIterable { return streamLogFile({ fs }, input.jobId, opts); @@ -42,7 +46,13 @@ export function createE2bJobHandle(input: { return result; }, async kill(): Promise { - await input.sandbox.commands.kill(input.pid); + const pids = + input.pid === undefined + ? (await input.sandbox.commands.list()) + .filter((process) => processMentionsJob(process, input.jobId)) + .map((process) => process.pid) + : [input.pid]; + await Promise.all(pids.map((pid) => input.sandbox.commands.kill(pid))); } }; } @@ -52,6 +62,19 @@ export function createE2bLogStreamFs(sandbox: E2bSandbox): LogStreamFs { promises: { async readFile(filePath) { return Buffer.from(await sandbox.files.read(filePath, { format: "bytes" })); + }, + async stat(filePath) { + const result = await sandbox.commands.run( + `stat -c %Y ${shellQuote(filePath)} 2>/dev/null || stat -f %m ${shellQuote(filePath)}` + ); + if (!("stdout" in result)) { + throw new Error(`Unable to stat ${filePath}`); + } + const seconds = Number(result.stdout?.trim()); + if (!Number.isFinite(seconds)) { + throw new Error(`Unable to stat ${filePath}`); + } + return { mtimeMs: seconds * 1000 }; } }, watch(filePath, listener) { @@ -78,6 +101,15 @@ export function createE2bLogStreamFs(sandbox: E2bSandbox): LogStreamFs { }; } +function processMentionsJob(process: { cmd: string; args: string[] }, jobId: string): boolean { + const needle = `/tmp/poe-jobs/${jobId}`; + return process.cmd.includes(needle) || process.args.some((arg) => arg.includes(needle)); +} + +function shellQuote(value: string): string { + return `'${value.replaceAll("'", "'\\''")}'`; +} + async function readExitCode(sandbox: E2bSandbox, jobId: string): Promise { try { const contents = await sandbox.files.read(`${JOB_DIR}/${jobId}.exit`); diff --git a/packages/runner-e2b/src/opened-env.ts b/packages/runner-e2b/src/opened-env.ts index 895ff776ab..7081cc297e 100644 --- a/packages/runner-e2b/src/opened-env.ts +++ b/packages/runner-e2b/src/opened-env.ts @@ -35,9 +35,19 @@ export function createOpenedE2bEnv(input: { let lastProcess: { started: Promise } | null = null; let detachedJobContext: DetachedJobContext | null = null; + const attachedJobId = (input.spec as OpenSpec & { detachedJobId?: string }).detachedJobId; const env: E2bOpenedEnv = { id: input.sandbox.sandboxId, - job: null, + job: attachedJobId + ? createE2bJobHandle({ + sandbox: input.sandbox, + envId: input.sandbox.sandboxId, + jobId: attachedJobId, + tool: input.spec.jobLabel.tool, + argv: input.spec.jobLabel.argv, + preserveAfterExitHours: input.runtime.preserve_after_exit_hours ?? 24 + }) + : null, fs: createE2bLogStreamFs(input.sandbox), setDetachedJobContext(context) { detachedJobContext = context; diff --git a/src/cli/commands/__snapshots__/runtime.test.ts.snap b/src/cli/commands/__snapshots__/runtime.test.ts.snap index 183802d59e..e9852649dc 100644 --- a/src/cli/commands/__snapshots__/runtime.test.ts.snap +++ b/src/cli/commands/__snapshots__/runtime.test.ts.snap @@ -1,5 +1,20 @@ // Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html +exports[`runtime command > snapshots runtime jobs logs output 1`] = ` +"first line +second line" +`; + +exports[`runtime command > snapshots runtime jobs ls output and marks missing running sandboxes as lost 1`] = ` +"runtime jobs ls +┌──────────────────────────────┬──────────────────┬────────────┬────────────┬──────────────────────────┬──────────────────────────────┐ +│ JOB │ TOOL │ RUNTIME │ STATUS │ STARTED │ SANDBOX │ +├──────────────────────────────┼──────────────────┼────────────┼────────────┼──────────────────────────┼──────────────────────────────┤ +│ job-missing │ codex │ docker │ lost │ 2026-05-03T12:00:00.000Z │ env-missing │ +│ job-running │ codex │ docker │ running │ 2026-05-03T12:00:00.000Z │ env-running │ +└──────────────────────────────┴──────────────────┴────────────┴────────────┴──────────────────────────┴──────────────────────────────┘" +`; + exports[`runtime command > snapshots runtime templates clear output and removes local template entries 1`] = ` "runtime templates clear Cleared 1 local runtime template cache entry." diff --git a/src/cli/commands/runtime.test.ts b/src/cli/commands/runtime.test.ts index a277b521d5..a65ee3ca2f 100644 --- a/src/cli/commands/runtime.test.ts +++ b/src/cli/commands/runtime.test.ts @@ -3,6 +3,12 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; import { Command } from "commander"; import { Volume, createFsFromVolume } from "memfs"; import { resolveProjectConfigPath } from "@poe-code/poe-code-config"; +import { + registerExecutionEnvFactory, + type ExecutionEnvFactory, + type JobHandle, + type OpenedEnv +} from "@poe-code/agent-harness-tools"; import { buildDockerRuntimeTemplate } from "@poe-code/process-runner"; import { createCliContainer } from "../container.js"; import type { FileSystem } from "../../utils/file-system.js"; @@ -26,6 +32,7 @@ const homeDir = "/home/test"; const projectConfigPath = resolveProjectConfigPath(cwd); const dockerfilePath = path.join(cwd, ".poe-code", "Dockerfile"); const statePath = path.join(homeDir, ".poe-code", "state", "templates.json"); +const jobsDir = path.join(homeDir, ".poe-code", "state", "jobs"); const buildDockerRuntimeTemplateMock = vi.mocked(buildDockerRuntimeTemplate); function createBaseProgram(): Command { @@ -80,9 +87,119 @@ function stripAnsi(input: string): string { return result; } +function createJobEntry(overrides: { + id: string; + env_id: string; + status: "pending" | "running" | "exited" | "killed" | "lost"; + started_at?: string; +}) { + return { + id: overrides.id, + env_id: overrides.env_id, + env_kind: "docker", + tool: "codex", + argv: ["codex", "hello"], + cwd, + started_at: overrides.started_at ?? "2026-05-03T12:00:00.000Z", + status: overrides.status + }; +} + +function createJobHandle(input: { + status: Awaited>; + chunks?: string[]; + wait?: () => Promise<{ exitCode: number }>; + kill?: (signal?: NodeJS.Signals) => Promise; +}): JobHandle { + return { + id: "job", + envId: "env", + tool: "codex", + argv: ["codex", "hello"], + async status() { + return input.status; + }, + async *stream() { + for (const [index, chunk] of (input.chunks ?? []).entries()) { + yield { byteOffset: index, data: chunk }; + } + }, + async wait() { + if (input.wait) { + return await input.wait(); + } + return { exitCode: 0 }; + }, + async kill(signal) { + await input.kill?.(signal); + } + }; +} + +interface RuntimeFactoryEvents { + attached: Array<{ envId: string; context: unknown }>; + downloads: Array<{ envId: string; conflictPolicy: "refuse" | "overwrite" }>; + closed: string[]; +} + +function createTestRuntimeFactory( + handles: Map, + events: RuntimeFactoryEvents +): ExecutionEnvFactory { + return { + type: "docker", + supportsDetach: true, + async open() { + throw new Error("open is not used by runtime jobs tests"); + }, + async attach(envId, context) { + const handle = handles.get(envId); + if (!handle) { + throw new Error(`missing sandbox ${envId}`); + } + events.attached.push({ envId, context }); + return { + id: envId, + job: handle, + async uploadWorkspace() { + return { files: 0, bytes: 0, skipped: [] }; + }, + async downloadWorkspace(options) { + events.downloads.push({ envId, conflictPolicy: options.conflictPolicy }); + return { files: 0, bytes: 0, conflicts: [] }; + }, + exec() { + throw new Error("exec is not used by runtime jobs tests"); + }, + async detach() { + return handle; + }, + shell() { + throw new Error("shell is not used by runtime jobs tests"); + }, + async close() { + events.closed.push(envId); + } + } as OpenedEnv; + } + }; +} + describe("runtime command", () => { + const jobHandles = new Map(); + const runtimeEvents: RuntimeFactoryEvents = { + attached: [], + downloads: [], + closed: [] + }; + beforeEach(() => { buildDockerRuntimeTemplateMock.mockClear(); + jobHandles.clear(); + runtimeEvents.attached = []; + runtimeEvents.downloads = []; + runtimeEvents.closed = []; + registerExecutionEnvFactory(createTestRuntimeFactory(jobHandles, runtimeEvents)); }); it("initializes runtime config and default Dockerfile with --yes defaults", async () => { @@ -214,6 +331,169 @@ describe("runtime command", () => { `); }); + it("snapshots runtime jobs ls output and marks missing running sandboxes as lost", async () => { + const fs = createMemFs({ + [path.join(jobsDir, "job-running.json")]: `${JSON.stringify( + createJobEntry({ id: "job-running", env_id: "env-running", status: "running" }), + null, + 2 + )}\n`, + [path.join(jobsDir, "job-missing.json")]: `${JSON.stringify( + createJobEntry({ id: "job-missing", env_id: "env-missing", status: "running" }), + null, + 2 + )}\n` + }); + jobHandles.set("env-running", createJobHandle({ status: "running" })); + const logs: string[] = []; + const container = createContainer(fs, logs); + const program = createBaseProgram(); + registerRuntimeCommand(program, container); + + await program.parseAsync(["node", "cli", "runtime", "jobs", "ls"]); + + expect(stripAnsi(logs.join("\n"))).toMatchSnapshot(); + await expect(fs.readFile(path.join(jobsDir, "job-missing.json"), "utf8")).resolves.toContain( + '"status": "lost"' + ); + }); + + it("snapshots runtime jobs logs output", async () => { + const fs = createMemFs({ + [path.join(jobsDir, "job-logs.json")]: `${JSON.stringify( + createJobEntry({ id: "job-logs", env_id: "env-logs", status: "exited" }), + null, + 2 + )}\n` + }); + jobHandles.set( + "env-logs", + createJobHandle({ + status: "exited", + chunks: ["first line\n", "second line\n"] + }) + ); + const logs: string[] = []; + const container = createContainer(fs, logs); + const program = createBaseProgram(); + registerRuntimeCommand(program, container); + + await program.parseAsync(["node", "cli", "runtime", "jobs", "logs"]); + + expect(stripAnsi(logs.join("\n"))).toMatchSnapshot(); + }); + + it("errors with candidate jobs when the omitted job id is ambiguous", async () => { + const fs = createMemFs({ + [path.join(jobsDir, "job-one.json")]: `${JSON.stringify( + createJobEntry({ + id: "job-one", + env_id: "env-one", + status: "running", + started_at: "2026-05-03T12:00:00.000Z" + }), + null, + 2 + )}\n`, + [path.join(jobsDir, "job-two.json")]: `${JSON.stringify( + createJobEntry({ + id: "job-two", + env_id: "env-two", + status: "running", + started_at: "2026-05-03T13:00:00.000Z" + }), + null, + 2 + )}\n` + }); + const container = createContainer(fs); + const program = createBaseProgram(); + registerRuntimeCommand(program, container); + + await expect(program.parseAsync(["node", "cli", "runtime", "jobs", "logs"])).rejects.toThrow( + [ + "More than one detached runtime job matches this command. Pass a job id.", + "- job-two codex running 2026-05-03T13:00:00.000Z", + "- job-one codex running 2026-05-03T12:00:00.000Z" + ].join("\n") + ); + }); + + it("syncs with overwrite policy and closes the sandbox when requested", async () => { + const fs = createMemFs({ + [path.join(jobsDir, "job-sync.json")]: `${JSON.stringify( + createJobEntry({ id: "job-sync", env_id: "env-sync", status: "exited" }), + null, + 2 + )}\n` + }); + jobHandles.set("env-sync", createJobHandle({ status: "exited" })); + const container = createContainer(fs); + const program = createBaseProgram(); + registerRuntimeCommand(program, container); + + await program.parseAsync([ + "node", + "cli", + "runtime", + "jobs", + "sync", + "job-sync", + "--force-sync", + "--close" + ]); + + expect(runtimeEvents.downloads).toEqual([ + { envId: "env-sync", conflictPolicy: "overwrite" } + ]); + expect(runtimeEvents.closed).toEqual(["env-sync"]); + }); + + it("stops a job, marks it killed, and syncs through the shared primitive", async () => { + const fs = createMemFs({ + [path.join(jobsDir, "job-stop.json")]: `${JSON.stringify( + createJobEntry({ id: "job-stop", env_id: "env-stop", status: "running" }), + null, + 2 + )}\n` + }); + const signals: Array = []; + jobHandles.set( + "env-stop", + createJobHandle({ + status: "running", + kill: async (signal) => { + signals.push(signal); + } + }) + ); + const container = createContainer(fs); + const program = createBaseProgram(); + registerRuntimeCommand(program, container); + + await program.parseAsync([ + "node", + "cli", + "runtime", + "jobs", + "stop", + "job-stop", + "--sync", + "--force-sync" + ]); + + expect(signals).toEqual(["SIGTERM"]); + await expect(fs.readFile(path.join(jobsDir, "job-stop.json"), "utf8")).resolves.toContain( + '"status": "killed"' + ); + await expect(fs.readFile(path.join(jobsDir, "job-stop.json"), "utf8")).resolves.toContain( + '"exit_code": 130' + ); + expect(runtimeEvents.downloads).toEqual([ + { envId: "env-stop", conflictPolicy: "overwrite" } + ]); + }); + it("builds docker runtime templates through the exposed helper", async () => { const fs = createMemFs({ [projectConfigPath]: `${JSON.stringify({ runtime: { type: "docker" } }, null, 2)}\n`, diff --git a/src/cli/commands/runtime/index.ts b/src/cli/commands/runtime/index.ts index 5d4d5c5f57..a4ac7ba7b8 100644 --- a/src/cli/commands/runtime/index.ts +++ b/src/cli/commands/runtime/index.ts @@ -2,6 +2,7 @@ import type { Command } from "commander"; import type { CliContainer } from "../../container.js"; import { registerRuntimeBuildCommand } from "./build.js"; import { registerRuntimeInitCommand } from "./init.js"; +import { registerRuntimeJobsCommand } from "./jobs/index.js"; import { registerRuntimeTemplatesCommand } from "./templates/index.js"; export function registerRuntimeCommand(program: Command, container: CliContainer): void { @@ -12,4 +13,5 @@ export function registerRuntimeCommand(program: Command, container: CliContainer registerRuntimeInitCommand(runtime, program, container); registerRuntimeBuildCommand(runtime, program, container); registerRuntimeTemplatesCommand(runtime, program, container); + registerRuntimeJobsCommand(runtime, program, container); } diff --git a/src/cli/commands/runtime/jobs/attach.ts b/src/cli/commands/runtime/jobs/attach.ts new file mode 100644 index 0000000000..669c86d987 --- /dev/null +++ b/src/cli/commands/runtime/jobs/attach.ts @@ -0,0 +1,61 @@ +import type { Command } from "commander"; +import type { CliContainer } from "../../../container.js"; +import { createExecutionResources, resolveCommandFlags } from "../../shared.js"; +import { + attachJob, + createRuntimeState, + parseSince, + resolveJob, + streamJobLog, + syncJob +} from "./shared.js"; + +export function registerRuntimeJobsAttachCommand( + jobs: Command, + root: Command, + container: CliContainer +): void { + jobs + .command("attach") + .description("Attach to a detached runtime job log stream.") + .argument("[jobId]", "Detached job id") + .option("--since ", "Only include logs from recently modified log files") + .option("--sync-on-exit", "Download the workspace after the job exits") + .option("--force-sync", "Overwrite local files when syncing") + .action( + async ( + jobId: string | undefined, + options: { since?: string; syncOnExit?: boolean; forceSync?: boolean } + ) => { + await executeRuntimeJobsAttach(root, container, jobId, options); + } + ); +} + +async function executeRuntimeJobsAttach( + root: Command, + container: CliContainer, + jobId: string | undefined, + options: { since?: string; syncOnExit?: boolean; forceSync?: boolean } +): Promise { + const flags = resolveCommandFlags(root); + const resources = createExecutionResources(container, flags, "runtime:jobs:attach"); + const state = createRuntimeState(container); + const entry = await resolveJob(state, jobId, "running"); + const { handle } = await attachJob(entry); + + await streamJobLog(handle, { + since: parseSince(options.since), + follow: true, + write(chunk) { + resources.logger.info(chunk.trimEnd()); + }, + onDetach() { + resources.logger.info("detaching (job continues running)"); + } + }); + + if (options.syncOnExit === true && (await handle.status()) !== "running") { + await syncJob(entry, { forceSync: options.forceSync === true, close: false }); + } +} diff --git a/src/cli/commands/runtime/jobs/index.ts b/src/cli/commands/runtime/jobs/index.ts new file mode 100644 index 0000000000..24d478c903 --- /dev/null +++ b/src/cli/commands/runtime/jobs/index.ts @@ -0,0 +1,23 @@ +import type { Command } from "commander"; +import type { CliContainer } from "../../../container.js"; +import { registerRuntimeJobsAttachCommand } from "./attach.js"; +import { registerRuntimeJobsLogsCommand } from "./logs.js"; +import { registerRuntimeJobsLsCommand } from "./ls.js"; +import { registerRuntimeJobsSandboxCommand } from "./sandbox.js"; +import { registerRuntimeJobsStopCommand } from "./stop.js"; +import { registerRuntimeJobsSyncCommand } from "./sync.js"; + +export function registerRuntimeJobsCommand( + runtime: Command, + root: Command, + container: CliContainer +): void { + const jobs = runtime.command("jobs").description("Manage detached runtime jobs."); + + registerRuntimeJobsLsCommand(jobs, root, container); + registerRuntimeJobsAttachCommand(jobs, root, container); + registerRuntimeJobsLogsCommand(jobs, root, container); + registerRuntimeJobsStopCommand(jobs, root, container); + registerRuntimeJobsSyncCommand(jobs, root, container); + registerRuntimeJobsSandboxCommand(jobs, root, container); +} diff --git a/src/cli/commands/runtime/jobs/logs.ts b/src/cli/commands/runtime/jobs/logs.ts new file mode 100644 index 0000000000..a75861d6a2 --- /dev/null +++ b/src/cli/commands/runtime/jobs/logs.ts @@ -0,0 +1,40 @@ +import type { Command } from "commander"; +import type { CliContainer } from "../../../container.js"; +import { createExecutionResources, resolveCommandFlags } from "../../shared.js"; +import { attachJob, createRuntimeState, parseSince, resolveJob, streamJobLog } from "./shared.js"; + +export function registerRuntimeJobsLogsCommand( + jobs: Command, + root: Command, + container: CliContainer +): void { + jobs + .command("logs") + .description("Dump a detached runtime job log.") + .argument("[jobId]", "Detached job id") + .option("--since ", "Only include logs from recently modified log files") + .action(async (jobId: string | undefined, options: { since?: string }) => { + await executeRuntimeJobsLogs(root, container, jobId, options); + }); +} + +async function executeRuntimeJobsLogs( + root: Command, + container: CliContainer, + jobId: string | undefined, + options: { since?: string } +): Promise { + const flags = resolveCommandFlags(root); + const resources = createExecutionResources(container, flags, "runtime:jobs:logs"); + const state = createRuntimeState(container); + const entry = await resolveJob(state, jobId, "pullable"); + const { handle } = await attachJob(entry); + + await streamJobLog(handle, { + since: parseSince(options.since), + follow: false, + write(chunk) { + resources.logger.info(chunk.trimEnd()); + } + }); +} diff --git a/src/cli/commands/runtime/jobs/ls.ts b/src/cli/commands/runtime/jobs/ls.ts new file mode 100644 index 0000000000..6ddc8cb79d --- /dev/null +++ b/src/cli/commands/runtime/jobs/ls.ts @@ -0,0 +1,72 @@ +import { getTheme, renderTable, text, type TableColumn } from "@poe-code/design-system"; +import type { Command } from "commander"; +import type { JobEntry } from "@poe-code/poe-code-config"; +import type { CliContainer } from "../../../container.js"; +import { createExecutionResources, resolveCommandFlags } from "../../shared.js"; +import { attachJob, createRuntimeState } from "./shared.js"; + +export function registerRuntimeJobsLsCommand(jobs: Command, root: Command, container: CliContainer): void { + jobs + .command("ls") + .description("List detached runtime jobs.") + .action(async () => { + await executeRuntimeJobsLs(root, container); + }); +} + +async function executeRuntimeJobsLs(root: Command, container: CliContainer): Promise { + const flags = resolveCommandFlags(root); + const resources = createExecutionResources(container, flags, "runtime:jobs:ls"); + const state = createRuntimeState(container); + const entries = await reconcileRunningJobs(await state.jobs.list(), state); + const theme = getTheme(); + + resources.logger.intro("runtime jobs ls"); + resources.logger.info( + renderTable({ + theme, + columns, + rows: entries.map((entry) => ({ + Job: entry.id, + Tool: entry.tool, + Runtime: entry.env_kind, + Status: entry.status, + Started: entry.started_at || text.muted("-"), + Sandbox: entry.env_id || text.muted("-") + })) + }) + ); +} + +async function reconcileRunningJobs( + entries: JobEntry[], + state: ReturnType +): Promise { + const reconciled: JobEntry[] = []; + for (const entry of entries) { + if (entry.status !== "running") { + reconciled.push(entry); + continue; + } + + try { + const { handle } = await attachJob(entry); + const status = await handle.status(); + const updated = status === entry.status ? entry : await state.jobs.update(entry.id, { status }); + reconciled.push(updated ?? { ...entry, status }); + } catch { + const updated = await state.jobs.update(entry.id, { status: "lost" }); + reconciled.push(updated ?? { ...entry, status: "lost" }); + } + } + return reconciled; +} + +const columns: TableColumn[] = [ + { name: "Job", title: "JOB", alignment: "left", maxLen: 28 }, + { name: "Tool", title: "TOOL", alignment: "left", maxLen: 16 }, + { name: "Runtime", title: "RUNTIME", alignment: "left", maxLen: 10 }, + { name: "Status", title: "STATUS", alignment: "left", maxLen: 10 }, + { name: "Started", title: "STARTED", alignment: "left", maxLen: 24 }, + { name: "Sandbox", title: "SANDBOX", alignment: "left", maxLen: 28 } +]; diff --git a/src/cli/commands/runtime/jobs/sandbox.ts b/src/cli/commands/runtime/jobs/sandbox.ts new file mode 100644 index 0000000000..e65ff6a09b --- /dev/null +++ b/src/cli/commands/runtime/jobs/sandbox.ts @@ -0,0 +1,21 @@ +import type { Command } from "commander"; +import { selectExecutionEnvFactory, type ExecutionEnvType } from "@poe-code/agent-harness-tools"; +import type { CliContainer } from "../../../container.js"; + +export function registerRuntimeJobsSandboxCommand( + jobs: Command, + _root: Command, + _container: CliContainer +): void { + jobs + .command("sandbox") + .description("Open a shell in a runtime sandbox.") + .argument("", "Runtime sandbox id") + .option("--runtime ", "Runtime backend for the sandbox", "docker") + .action(async (envId: string, options: { runtime: string }) => { + const factory = selectExecutionEnvFactory(options.runtime as ExecutionEnvType); + const env = await factory.attach(envId); + const handle = env.shell(); + process.exitCode = (await handle.result).exitCode; + }); +} diff --git a/src/cli/commands/runtime/jobs/shared.ts b/src/cli/commands/runtime/jobs/shared.ts new file mode 100644 index 0000000000..13fde3d4e5 --- /dev/null +++ b/src/cli/commands/runtime/jobs/shared.ts @@ -0,0 +1,177 @@ +import parseDuration from "parse-duration"; +import { + createStateManager, + type JobEntry, + type JobStatus, + type StateManager +} from "@poe-code/poe-code-config"; +import { + selectExecutionEnvFactory, + type ExecutionEnvType, + type JobHandle, + type OpenedEnv +} from "@poe-code/agent-harness-tools"; +import type { CliContainer } from "../../../container.js"; + +export type JobIntent = "running" | "pullable"; + +export function createRuntimeState(container: CliContainer): StateManager { + return createStateManager( + container.env.homeDir, + container.fs as unknown as Parameters[1] + ); +} + +export async function resolveJob( + state: StateManager, + jobId: string | undefined, + intent: JobIntent +): Promise { + if (jobId !== undefined) { + const entry = await state.jobs.get(jobId); + if (entry === null) { + throw new Error(`No runtime job found for "${jobId}".`); + } + return entry; + } + + const allowedStatuses = intent === "running" ? new Set(["running"]) : new Set(["running", "exited"]); + const candidates = (await state.jobs.list()) + .filter((entry) => allowedStatuses.has(entry.status)) + .sort(compareLatestFirst); + + if (candidates.length === 1) { + return candidates[0]; + } + + if (candidates.length === 0) { + throw new Error("No detached runtime jobs match this command."); + } + + throw new Error( + [ + "More than one detached runtime job matches this command. Pass a job id.", + ...candidates.map((entry) => `- ${entry.id} ${entry.tool} ${entry.status} ${entry.started_at}`) + ].join("\n") + ); +} + +export async function attachJob(entry: JobEntry): Promise<{ env: OpenedEnv; handle: JobHandle }> { + const factory = selectExecutionEnvFactory(entry.env_kind as ExecutionEnvType); + const env = await factory.attach(entry.env_id, { + jobId: entry.id, + tool: entry.tool, + argv: entry.argv, + cwd: entry.cwd + }); + const handle = env.job; + if (handle === null) { + throw new Error(`Runtime "${entry.env_kind}" did not provide a handle for job "${entry.id}".`); + } + return { env, handle }; +} + +export function parseSince(value: string | undefined): Date | undefined { + if (value === undefined) { + return undefined; + } + + const milliseconds = parseDuration(value); + if (milliseconds === null || !Number.isFinite(milliseconds) || milliseconds < 0) { + throw new Error(`Invalid duration "${value}".`); + } + return new Date(Date.now() - milliseconds); +} + +export async function syncJob( + entry: JobEntry, + opts: { forceSync: boolean; close: boolean } +): Promise { + const { env } = await attachJob(entry); + try { + await env.downloadWorkspace({ + conflictPolicy: opts.forceSync ? "overwrite" : "refuse" + }); + } finally { + if (opts.close) { + await env.close(); + } + } +} + +export async function streamJobLog( + handle: JobHandle, + opts: { + since?: Date; + follow: boolean; + write(chunk: string): void; + onDetach?: () => void; + } +): Promise { + let detaching = false; + const iterator = handle.stream({ sinceByte: 0, ...(opts.since ? { since: opts.since } : {}) })[ + Symbol.asyncIterator + ](); + const onSigint = opts.onDetach + ? () => { + detaching = true; + opts.onDetach?.(); + void iterator.return?.(); + } + : undefined; + + if (onSigint) { + process.once("SIGINT", onSigint); + } + + try { + while (!detaching) { + const result = await Promise.race([ + iterator.next(), + sleep(250).then(() => ({ timedOut: true as const })) + ]); + + if ("timedOut" in result) { + if (!opts.follow) { + break; + } + if ((await handle.status()) !== "running") { + break; + } + continue; + } + + if (result.done === true) { + break; + } + opts.write(result.value.data); + } + } finally { + if (onSigint) { + process.off("SIGINT", onSigint); + } + await iterator.return?.(); + } +} + +export async function waitForGracefulStop( + handle: JobHandle, + graceMs = 30_000 +): Promise { + await handle.kill("SIGTERM"); + const result = await Promise.race([handle.wait().then(() => "exited" as const), sleep(graceMs)]); + if (result !== "exited") { + await handle.kill("SIGKILL"); + await handle.wait().catch(() => undefined); + } +} + +function compareLatestFirst(left: JobEntry, right: JobEntry): number { + return Date.parse(right.started_at) - Date.parse(left.started_at); +} + +function sleep(ms: number): Promise<"timeout"> { + return new Promise((resolve) => { + setTimeout(() => resolve("timeout"), ms); + }); +} diff --git a/src/cli/commands/runtime/jobs/stop.ts b/src/cli/commands/runtime/jobs/stop.ts new file mode 100644 index 0000000000..0e19599323 --- /dev/null +++ b/src/cli/commands/runtime/jobs/stop.ts @@ -0,0 +1,57 @@ +import type { Command } from "commander"; +import type { CliContainer } from "../../../container.js"; +import { createExecutionResources, resolveCommandFlags } from "../../shared.js"; +import { + attachJob, + createRuntimeState, + resolveJob, + syncJob, + waitForGracefulStop +} from "./shared.js"; + +export function registerRuntimeJobsStopCommand( + jobs: Command, + root: Command, + container: CliContainer +): void { + jobs + .command("stop") + .description("Stop a detached runtime job.") + .argument("[jobId]", "Detached job id") + .option("--sync", "Download the workspace after stopping") + .option("--force-sync", "Overwrite local files when syncing") + .action( + async ( + jobId: string | undefined, + options: { sync?: boolean; forceSync?: boolean } + ) => { + await executeRuntimeJobsStop(root, container, jobId, options); + } + ); +} + +async function executeRuntimeJobsStop( + root: Command, + container: CliContainer, + jobId: string | undefined, + options: { sync?: boolean; forceSync?: boolean } +): Promise { + const flags = resolveCommandFlags(root); + const resources = createExecutionResources(container, flags, "runtime:jobs:stop"); + const state = createRuntimeState(container); + const entry = await resolveJob(state, jobId, "pullable"); + const { handle } = await attachJob(entry); + + await waitForGracefulStop(handle); + await state.jobs.update(entry.id, { + status: "killed", + exit_code: 130, + exited_at: new Date().toISOString() + }); + + if (options.sync === true || options.forceSync === true) { + await syncJob(entry, { forceSync: options.forceSync === true, close: false }); + } + + resources.logger.success(`Stopped runtime job ${entry.id}.`); +} diff --git a/src/cli/commands/runtime/jobs/sync.ts b/src/cli/commands/runtime/jobs/sync.ts new file mode 100644 index 0000000000..6e5f091f16 --- /dev/null +++ b/src/cli/commands/runtime/jobs/sync.ts @@ -0,0 +1,43 @@ +import type { Command } from "commander"; +import type { CliContainer } from "../../../container.js"; +import { createExecutionResources, resolveCommandFlags } from "../../shared.js"; +import { createRuntimeState, resolveJob, syncJob } from "./shared.js"; + +export function registerRuntimeJobsSyncCommand( + jobs: Command, + root: Command, + container: CliContainer +): void { + jobs + .command("sync") + .description("Download a detached runtime job workspace.") + .argument("[jobId]", "Detached job id") + .option("--force-sync", "Overwrite local files when syncing") + .option("--close", "Close the sandbox after syncing") + .action( + async ( + jobId: string | undefined, + options: { forceSync?: boolean; close?: boolean } + ) => { + await executeRuntimeJobsSync(root, container, jobId, options); + } + ); +} + +async function executeRuntimeJobsSync( + root: Command, + container: CliContainer, + jobId: string | undefined, + options: { forceSync?: boolean; close?: boolean } +): Promise { + const flags = resolveCommandFlags(root); + const resources = createExecutionResources(container, flags, "runtime:jobs:sync"); + const state = createRuntimeState(container); + const entry = await resolveJob(state, jobId, "pullable"); + + await syncJob(entry, { + forceSync: options.forceSync === true, + close: options.close === true + }); + resources.logger.success(`Synced runtime job ${entry.id}.`); +} diff --git a/src/cli/commands/spawn-command.test.ts b/src/cli/commands/spawn-command.test.ts index 8e3ba4141a..a2f88e6645 100644 --- a/src/cli/commands/spawn-command.test.ts +++ b/src/cli/commands/spawn-command.test.ts @@ -242,6 +242,37 @@ describe("spawn command", () => { expect(logs.length).toBeGreaterThan(0); }); + it("snapshots --detach output", async () => { + vi.mocked(sdkSpawn).mockImplementation(() => ({ + events: emptyAsyncIterable(), + result: Promise.resolve({ + stdout: "", + stderr: "", + exitCode: 0, + detached: { jobId: "job-123", envId: "env-456" } + }) + })); + + const logs: string[] = []; + const { runner } = createCommandRunnerStub(); + const program = createProgram({ + fs, + prompts: vi.fn().mockResolvedValue({}), + env: { cwd, homeDir }, + commandRunner: runner, + logger: (message) => logs.push(message) + }); + + await program.parseAsync(["node", "cli", "spawn", "codex", "--detach", "hello"]); + + expect(stripAnsi(logs.join("\n"))).toMatchInlineSnapshot(` + "spawn codex + job started: job-123 + sandbox: env-456 + detached." + `); + }); + it("prints final stdout when events are empty", async () => { vi.mocked(sdkSpawn).mockImplementation(() => ({ events: emptyAsyncIterable(), diff --git a/src/cli/commands/spawn.ts b/src/cli/commands/spawn.ts index db59247d6f..d34ea96211 100644 --- a/src/cli/commands/spawn.ts +++ b/src/cli/commands/spawn.ts @@ -235,6 +235,7 @@ export function registerSpawnCommand( model }; const resources = createExecutionResources(container, flags, `spawn:${canonicalService}`); + let skipFinalize = false; if (shouldEmitUiOutput) { resources.logger.intro(`spawn ${canonicalService}`); } @@ -300,6 +301,12 @@ export function registerSpawnCommand( }); process.exitCode = final.exitCode; + if (shouldEmitUiOutput && final.detached) { + resources.logger.info(formatDetachedJob(final.detached)); + skipFinalize = true; + return; + } + if (!shouldEmitUiOutput) { renderAcpEvent({ event: "spawn_result", @@ -344,7 +351,7 @@ export function registerSpawnCommand( } } } finally { - if (shouldEmitUiOutput) { + if (shouldEmitUiOutput && !skipFinalize) { resources.context.finalize(); } } @@ -354,6 +361,10 @@ export function registerSpawnCommand( }); } +function formatDetachedJob(detached: { jobId: string; envId: string }): string { + return `job started: ${detached.jobId}\nsandbox: ${detached.envId}\ndetached.`; +} + function listSpawnServiceNames( services: Array<{ name: string; aliases?: string[] }>, extraServices: string[] diff --git a/src/sdk/types.ts b/src/sdk/types.ts index 7ce7de5714..1a1b83bf32 100644 --- a/src/sdk/types.ts +++ b/src/sdk/types.ts @@ -77,6 +77,8 @@ export interface SpawnResult { usage?: SpawnUsage; /** Path to the JSONL spawn log file (if logging was active) */ logFile?: string; + /** Detached runtime job details when detach mode is used */ + detached?: { jobId: string; envId: string }; /** Captured session messages and tool calls (ACP streaming only) */ sessionResult?: SessionResult; } From 1110d4494259e6da03f4801648d1c589665842c3 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 19:58:10 -0500 Subject: [PATCH 020/111] docs: update e2b runtime documentation --- docs/plans/e2b-integration.md | 4 +- docs/plans/e2b-integration.md.lock | 2 +- docs/plans/qa/e2b-integration.md | 39 +++++++++++ packages/agent-harness-tools/README.md | 37 +++++++++++ packages/poe-code-config/README.md | 47 ++++++++++++++ packages/process-runner/README.md | 24 +++++++ packages/runner-e2b/README.md | 90 ++++++++++++++++++++++++-- 7 files changed, 233 insertions(+), 10 deletions(-) create mode 100644 docs/plans/qa/e2b-integration.md diff --git a/docs/plans/e2b-integration.md b/docs/plans/e2b-integration.md index 4338d9ccab..f1fac23655 100644 --- a/docs/plans/e2b-integration.md +++ b/docs/plans/e2b-integration.md @@ -522,7 +522,7 @@ tasks: status: implement: done test: done - commit: open + commit: done - id: qa-and-readmes title: Manual QA doc, README updates, design-doc regeneration @@ -556,7 +556,7 @@ tasks: Do NOT touch the project root README without a separate request (per CLAUDE.md readme rule). status: - implement: open + implement: done commit: open --- diff --git a/docs/plans/e2b-integration.md.lock b/docs/plans/e2b-integration.md.lock index d41d3ae65a..72a9e5f95e 100644 --- a/docs/plans/e2b-integration.md.lock +++ b/docs/plans/e2b-integration.md.lock @@ -1 +1 @@ -{"pid":82216,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T00:53:16.771Z"} \ No newline at end of file +{"pid":82216,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T00:57:03.810Z"} \ No newline at end of file diff --git a/docs/plans/qa/e2b-integration.md b/docs/plans/qa/e2b-integration.md new file mode 100644 index 0000000000..22d4401a40 --- /dev/null +++ b/docs/plans/qa/e2b-integration.md @@ -0,0 +1,39 @@ +# E2B Integration QA + +- [ ] Fresh repo initialization + - Run `poe-code runtime init` in a repository without an existing `.poe-code` directory. + - Assert `.poe-code/Dockerfile` is created. + - Assert `.poe-code/config.json` is created. + +- [ ] E2B template build cache + - Run an E2B-backed command once with the initialized runtime config. + - Assert the first run builds an E2B template. + - Run the same command again without changing the Dockerfile or build context. + - Assert the second run resolves the same template from cache instead of rebuilding. + +- [ ] Detached Ralph run + - Run `poe-code ralph plan.md --runtime e2b --detach`. + - Assert the command returns a `jobId`. + - Assert the sandbox is visible in the E2B dashboard. + +- [ ] Attach and detach log streaming + - Run `poe-code runtime jobs attach ` with the detached job id. + - Assert the command resumes the job log. + - Press Ctrl-C. + - Assert the local attach session detaches without killing the remote job. + +- [ ] Stop and sync back + - Run `poe-code runtime jobs stop `. + - Assert the remote job is killed. + - Assert the workspace sync-back runs before local state is cleaned up. + +- [ ] Sync-back conflict messaging + - Start a detached E2B run that modifies a tracked local file inside the sandbox. + - Modify the same local file while the job is still running. + - Trigger sync-back with the default conflict policy. + - Assert the command refuses the conflicting file and lists it clearly. + +- [ ] Teammate Dockerfile cache identity + - Share the same `.poe-code/Dockerfile` and build context with another checkout. + - Run the same E2B-backed command in both checkouts. + - Assert the same `template_id` resolves for both users. diff --git a/packages/agent-harness-tools/README.md b/packages/agent-harness-tools/README.md index a8b0efd2c4..8a145998c3 100644 --- a/packages/agent-harness-tools/README.md +++ b/packages/agent-harness-tools/README.md @@ -8,6 +8,43 @@ This package is intended to hold shared runtime building blocks for agent-driven Shared helpers are exported from `src/index.ts` as they are added. +## ExecutionEnv Contract + +`ExecutionEnvFactory` is the runtime backend boundary used by Poe Code command runners. + +- `type`: runtime backend id, currently `host`, `docker`, or `e2b`. +- `supportsDetach`: true when the backend can leave an addressable environment running. +- `open(spec)`: creates a fresh `OpenedEnv`. +- `attach(envId, context)`: reconnects to an existing runtime environment. + +`OpenedEnv` owns one command environment lifecycle: + +- `id`: backend environment id, such as a Docker container id or E2B sandbox id. +- `job`: attached job handle when reconnecting to an existing job, otherwise `null`. +- `uploadWorkspace()`: transfers the caller workspace into the environment. +- `downloadWorkspace({ conflictPolicy })`: syncs the environment workspace back to the caller. +- `exec(spec)`: runs a command in the environment and returns a process `RunHandle`. +- `detach()`: leaves the environment running and returns a `JobHandle`. +- `shell()`: opens an interactive shell in the environment. +- `close()`: closes and cleans up the environment. + +Factories are registered with `registerExecutionEnvFactory(...)` and selected by `selectExecutionEnv(runtime)`. + +## `runPoeCommand` + +`runPoeCommand(...)` is the shared entry point for running a Poe Code tool through an `ExecutionEnvFactory`. + +The flow is: + +1. Create a pending job entry in the state manager. +2. Open the selected execution environment. +3. Upload the workspace. +4. Execute the wrapped Poe command. +5. Either detach and return `{ kind: "detached", jobId, envId }`, or wait for exit. +6. In sync mode, download the workspace with `runner.download_conflict` and return `{ kind: "sync", exitCode, download }`. + +Callers pass `OpenSpec.jobLabel` so detached jobs can be listed and reattached with meaningful command metadata. + ## Loop agent selection `resolveLoopAgent` is the shared selector used by loop-style runners to choose a single agent specifier. diff --git a/packages/poe-code-config/README.md b/packages/poe-code-config/README.md index e70e0d5597..8f72b7f23c 100644 --- a/packages/poe-code-config/README.md +++ b/packages/poe-code-config/README.md @@ -22,6 +22,53 @@ This package is responsible for merging global and project config documents. CLI Use `resolveConfigPath(homeDir)` for the global file and `resolveProjectConfigPath(cwd)` for the project file. +## State locations + +Runtime state is global to the local machine and lives under `~/.poe-code/state`. + +- Template cache: `~/.poe-code/state/templates.json` +- Runtime jobs: `~/.poe-code/state/jobs/.json` + +Use `loadStateManager(homeDir)` for node-backed state or `createStateManager(homeDir, fs)` when tests need an injected filesystem. + +## Runtime Scope + +The `runtime` scope describes where commands execute. `parseRuntime(...)` accepts: + +- `type`: `host`, `docker`, or `e2b`. Defaults to `host`. +- `build_args`: build argument object used by image/template builds. Defaults to `{}`. +- `mounts`: additional runtime mounts. Defaults to `[]`. +- `link`: optional informational URL or label for the runtime definition. + +Docker-specific options: + +- `image`: prebuilt Docker image. When present, no Dockerfile build is required. +- `dockerfile`: Dockerfile path. Defaults to `.poe-code/Dockerfile` when a build is needed. +- `build_context`: Docker build context. Defaults to the current project directory. +- `engine`: `docker` or `podman`. +- `network`: Docker network. +- `extra_args`: additional container runtime arguments. + +E2B-specific options: + +- `template_id`: prebuilt E2B template id. When present, no template build is required. +- `dockerfile`: Dockerfile path. Defaults to `.poe-code/Dockerfile` when a template build is needed. +- `build_context`: E2B template build context. Defaults to the current project directory. +- `cpu`: CPU count for template builds. +- `memory_mb`: memory in megabytes for template builds. +- `timeout_minutes`: sandbox timeout in minutes. +- `preserve_after_exit_hours`: hours to keep a detached sandbox alive after job exit. Defaults to `24`; valid range is `0` to `168`. +- `api_key_env`: host environment variable containing the E2B API key. Defaults to `E2B_API_KEY`. + +## Runner Scope + +Runner settings are stored as `runtime.runner` in config and parsed with `parseRunner(...)`. + +- `detach`: run through a detached runtime job when the backend supports it. Defaults to `false`. +- `upload_max_file_mb`: maximum file size uploaded during workspace transfer. Defaults to `100`. +- `download_conflict`: sync-back conflict policy, either `refuse` or `overwrite`. Defaults to `refuse`. +- `workspace.exclude`: upload exclusion list. Defaults to `.git`, `node_modules`, `dist`, `.turbo`, `.next`, and `.poe-code/state.json`. + ## Merge semantics Project config is read as an override on top of global config. diff --git a/packages/process-runner/README.md b/packages/process-runner/README.md index 31cc024bb2..056123200e 100644 --- a/packages/process-runner/README.md +++ b/packages/process-runner/README.md @@ -8,6 +8,30 @@ Low-level process execution abstraction. Single interface for launching processe - Consumed by `@poe-code/agent-spawn` - Consumed by `process-launcher` +## Host Factory + +- `createHostRunner(options)` returns a `Runner` that launches commands with `node:child_process.spawn`. +- `options.detached` starts the child as a detached process and uses process-group kill on Unix. +- `hostExecutionEnvFactory` implements the shared execution environment contract for local host execution. +- Host environments do not upload, download, detach, or reattach because the caller workspace is already local and there is no addressable remote environment. + +## Docker Factories + +- `createDockerRunner(options)` returns a one-shot `Runner` that executes each command in a Docker or Podman container. +- `dockerExecutionEnvFactory` creates an addressable long-lived container environment for Poe Code runtime jobs. +- Docker environments support workspace upload/download, command execution, interactive shell, detach, attach, and cleanup. + +`DockerRunnerOptions`: + +- `image`: container image to run. +- `engine`: `docker` or `podman`; detected when omitted. +- `context`: Docker context name; detected when omitted. +- `mounts`: container mounts. +- `ports`: port mappings. +- `network`: Docker network. +- `extraArgs`: additional runtime arguments. +- `containerName`: optional container name prefix. + ## Environment variables This package exposes no environment variables. diff --git a/packages/runner-e2b/README.md b/packages/runner-e2b/README.md index 3150d3fbec..fc173af05c 100644 --- a/packages/runner-e2b/README.md +++ b/packages/runner-e2b/README.md @@ -1,15 +1,91 @@ # @poe-code/runner-e2b -E2B execution environment runner for poe-code. +E2B execution environment runner for Poe Code. + +This package implements the shared `ExecutionEnvFactory` contract for `runtime.type: "e2b"`. +It is responsible for opening E2B sandboxes, resolving or building templates from the Poe Code +runtime config, uploading/downloading workspaces, and reconnecting to detached sandboxes. ## Environment Variables -- `E2B_API_KEY` - E2B API key used by default when `runtime.api_key_env` is not configured. +- `E2B_API_KEY` - E2B API key used by default. + +The environment variable name can be changed with `runtime.api_key_env`. When `auth.providers.e2b` +is present in the `OpenSpec` passed by the caller, that configured credential is preferred over the +environment variable. ## Runtime Config -- `runtime.api_key_env` - Host environment variable containing the E2B API key. Defaults to `E2B_API_KEY`. -- `runtime.cpu` - CPU count used when building an E2B template. -- `runtime.memory_mb` - Memory in megabytes used when building an E2B template. -- `runtime.timeout_minutes` - Sandbox timeout in minutes. -- `runtime.preserve_after_exit_hours` - Hours to keep a detached sandbox alive after job exit. Defaults to `24`; valid range is `0` to `168`. +Use these options under the `runtime` config scope: + +- `type`: must be `e2b`. +- `template_id`: existing E2B template id. When set, template build is skipped. +- `dockerfile`: Dockerfile path used to build a template when `template_id` is not set. Defaults to `.poe-code/Dockerfile`. +- `build_context`: build context path. Defaults to the project root. +- `build_args`: build argument object included in the template hash. +- `mounts`: runtime mounts passed through the shared runtime config. +- `cpu`: CPU count used when building an E2B template. +- `memory_mb`: memory in megabytes used when building an E2B template. +- `timeout_minutes`: sandbox timeout in minutes. +- `preserve_after_exit_hours`: hours to keep a detached sandbox alive after job exit. Defaults to `24`; valid range is `0` to `168`. +- `api_key_env`: host environment variable containing the E2B API key. Defaults to `E2B_API_KEY`. + +Runner workspace behavior is controlled by `runtime.runner` in `@poe-code/poe-code-config`: + +- `detach`: default detached execution preference when the caller supports it. +- `upload_max_file_mb`: maximum file size uploaded by workspace transfer. +- `download_conflict`: sync-back policy, `refuse` or `overwrite`. +- `workspace.exclude`: upload exclusion list. + +Example project config: + +```json +{ + "runtime": { + "type": "e2b", + "dockerfile": ".poe-code/Dockerfile", + "build_context": ".", + "timeout_minutes": 60, + "preserve_after_exit_hours": 24, + "runner": { + "detach": false, + "download_conflict": "refuse" + } + } +} +``` + +## Template Build Flow + +When `runtime.template_id` is present, `e2bExecutionEnvFactory.open(...)` uses that template id +directly. + +When `runtime.template_id` is absent: + +1. Read the configured Dockerfile, defaulting to `.poe-code/Dockerfile`. +2. Read regular files from the configured build context, defaulting to the project root. +3. Compute a SHA-256 hash from Dockerfile bytes, build context file paths and bytes, and sorted `build_args`. +4. Look up the hash in `state.templates.get("e2b", hash)`. +5. If a cached entry has `template_id`, reuse it. +6. Otherwise build a new E2B template named `poe-code-`. +7. Persist the built template in `~/.poe-code/state/templates.json`. + +The hash is deterministic for the same Dockerfile, build context contents, and build args. That keeps +template identity stable across runs and across teammates using the same inputs. + +## Sandbox Lifecycle + +`e2bExecutionEnvFactory.open(...)` opens a new sandbox from the resolved template and returns an +`OpenedEnv`. + +The opened environment supports: + +- `uploadWorkspace()`: archives the local workspace and uploads it into the sandbox. +- `exec(spec)`: runs a command inside the sandbox. +- `shell()`: opens an interactive shell using the shared `RunHandle` shape. +- `detach()`: leaves the sandbox running and returns a job handle. +- `downloadWorkspace({ conflictPolicy })`: syncs files back, refusing or overwriting local conflicts according to the runner policy. +- `close()`: shuts down the sandbox when the run is not detached. + +`e2bExecutionEnvFactory.attach(envId, context)` reconnects to an existing sandbox id. Detached jobs +are tracked by the caller state manager under `~/.poe-code/state/jobs/.json`. From bdaeafc750b67b837175636d9f99ffa945cc1fe1 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 19:58:54 -0500 Subject: [PATCH 021/111] docs: archive e2b integration plan --- docs/plans/{ => archive}/e2b-integration.md | 2 +- docs/plans/e2b-integration.md.lock | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename docs/plans/{ => archive}/e2b-integration.md (99%) diff --git a/docs/plans/e2b-integration.md b/docs/plans/archive/e2b-integration.md similarity index 99% rename from docs/plans/e2b-integration.md rename to docs/plans/archive/e2b-integration.md index f1fac23655..acd5e0e3bb 100644 --- a/docs/plans/e2b-integration.md +++ b/docs/plans/archive/e2b-integration.md @@ -557,7 +557,7 @@ tasks: (per CLAUDE.md readme rule). status: implement: done - commit: open + commit: done --- # e2b integration diff --git a/docs/plans/e2b-integration.md.lock b/docs/plans/e2b-integration.md.lock index 72a9e5f95e..d58dbbac0d 100644 --- a/docs/plans/e2b-integration.md.lock +++ b/docs/plans/e2b-integration.md.lock @@ -1 +1 @@ -{"pid":82216,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T00:57:03.810Z"} \ No newline at end of file +{"pid":82216,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T00:58:24.965Z"} \ No newline at end of file From bc18a77fdc4ea20411fdc66a20d0795e41ea8313 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 21:12:38 -0500 Subject: [PATCH 022/111] feat(runner-e2b): own the e2b auth config scope Add e2bAuthScope to runner-e2b and resolve the API key from the merged ~/.poe-code/config.json + project config (env var still wins). Drops the dead auth.providers.e2b branch and the unused runtime.api_key_env field. --- packages/poe-code-config/README.md | 3 +- packages/poe-code-config/src/runtime.test.ts | 12 ++--- packages/poe-code-config/src/runtime.ts | 9 +--- packages/runner-e2b/README.md | 23 ++++++--- packages/runner-e2b/src/auth-scope.test.ts | 54 ++++++++++++++++++++ packages/runner-e2b/src/auth-scope.ts | 44 ++++++++++++++++ packages/runner-e2b/src/factory.test.ts | 52 +++++++------------ packages/runner-e2b/src/factory.ts | 50 ++---------------- packages/runner-e2b/src/index.ts | 1 + 9 files changed, 146 insertions(+), 102 deletions(-) create mode 100644 packages/runner-e2b/src/auth-scope.test.ts create mode 100644 packages/runner-e2b/src/auth-scope.ts diff --git a/packages/poe-code-config/README.md b/packages/poe-code-config/README.md index 8f72b7f23c..96670707df 100644 --- a/packages/poe-code-config/README.md +++ b/packages/poe-code-config/README.md @@ -58,7 +58,8 @@ E2B-specific options: - `memory_mb`: memory in megabytes for template builds. - `timeout_minutes`: sandbox timeout in minutes. - `preserve_after_exit_hours`: hours to keep a detached sandbox alive after job exit. Defaults to `24`; valid range is `0` to `168`. -- `api_key_env`: host environment variable containing the E2B API key. Defaults to `E2B_API_KEY`. + +The E2B API key is configured under the separate `e2b` scope, owned by `@poe-code/runner-e2b`. See that package's README. ## Runner Scope diff --git a/packages/poe-code-config/src/runtime.test.ts b/packages/poe-code-config/src/runtime.test.ts index ad2a47d5c0..841262ebbc 100644 --- a/packages/poe-code-config/src/runtime.test.ts +++ b/packages/poe-code-config/src/runtime.test.ts @@ -150,8 +150,7 @@ describe("runtime config", () => { template_id: "tmpl_123", build_args: {}, mounts: [], - preserve_after_exit_hours: 24, - api_key_env: "E2B_API_KEY" + preserve_after_exit_hours: 24 }); expect( @@ -161,16 +160,14 @@ describe("runtime config", () => { cpu: 4, memory_mb: 8192, timeout_minutes: 60, - preserve_after_exit_hours: 168, - api_key_env: "CUSTOM_E2B_API_KEY" + preserve_after_exit_hours: 168 }) ).toMatchObject({ type: "e2b", cpu: 4, memory_mb: 8192, timeout_minutes: 60, - preserve_after_exit_hours: 168, - api_key_env: "CUSTOM_E2B_API_KEY" + preserve_after_exit_hours: 168 }); expect(() => @@ -289,8 +286,7 @@ describe("runtime config", () => { template_id: "tmpl_123", build_args: {}, mounts: [], - preserve_after_exit_hours: 0, - api_key_env: "E2B_API_KEY" + preserve_after_exit_hours: 0 }); }); diff --git a/packages/poe-code-config/src/runtime.ts b/packages/poe-code-config/src/runtime.ts index 4971ae40e9..9a4d37d488 100644 --- a/packages/poe-code-config/src/runtime.ts +++ b/packages/poe-code-config/src/runtime.ts @@ -46,7 +46,6 @@ export interface E2bRuntime extends SharedRuntimeFields { memory_mb?: number; timeout_minutes?: number; preserve_after_exit_hours?: number; - api_key_env?: string; } export type RuntimeConfig = HostRuntime | DockerRuntime | E2bRuntime; @@ -160,11 +159,6 @@ export const runtimeConfigScope = { default: undefined as number | undefined, parse: parseOptionalNumber, doc: "Hours to keep an E2B sandbox alive after job exit" - }, - api_key_env: { - type: "string", - default: "", - doc: "Environment variable name containing the E2B API key" } } } satisfies ScopeDefinition>; @@ -235,8 +229,7 @@ export function parseRuntime(raw: unknown): RuntimeConfig { cpu: parseOptionalNumber(record.cpu), memory_mb: parseOptionalNumber(record.memory_mb), timeout_minutes: parseOptionalNumber(record.timeout_minutes), - preserve_after_exit_hours: preserveAfterExitHours, - api_key_env: parseOptionalString(record.api_key_env) ?? "E2B_API_KEY" + preserve_after_exit_hours: preserveAfterExitHours }); } diff --git a/packages/runner-e2b/README.md b/packages/runner-e2b/README.md index fc173af05c..4d932cb199 100644 --- a/packages/runner-e2b/README.md +++ b/packages/runner-e2b/README.md @@ -6,13 +6,25 @@ This package implements the shared `ExecutionEnvFactory` contract for `runtime.t It is responsible for opening E2B sandboxes, resolving or building templates from the Poe Code runtime config, uploading/downloading workspaces, and reconnecting to detached sandboxes. -## Environment Variables +## API key -- `E2B_API_KEY` - E2B API key used by default. +The E2B API key is read from the `e2b` config scope. Resolution order: -The environment variable name can be changed with `runtime.api_key_env`. When `auth.providers.e2b` -is present in the `OpenSpec` passed by the caller, that configured credential is preferred over the -environment variable. +1. `E2B_API_KEY` environment variable. +2. `e2b.api_key` in the project config (`/.poe-code/config.json`). +3. `e2b.api_key` in the global config (`~/.poe-code/config.json`). + +Example global config: + +```json +{ + "e2b": { + "api_key": "e2b_..." + } +} +``` + +Missing key on `open()` or `attach()` raises an error pointing to both locations. ## Runtime Config @@ -28,7 +40,6 @@ Use these options under the `runtime` config scope: - `memory_mb`: memory in megabytes used when building an E2B template. - `timeout_minutes`: sandbox timeout in minutes. - `preserve_after_exit_hours`: hours to keep a detached sandbox alive after job exit. Defaults to `24`; valid range is `0` to `168`. -- `api_key_env`: host environment variable containing the E2B API key. Defaults to `E2B_API_KEY`. Runner workspace behavior is controlled by `runtime.runner` in `@poe-code/poe-code-config`: diff --git a/packages/runner-e2b/src/auth-scope.test.ts b/packages/runner-e2b/src/auth-scope.test.ts new file mode 100644 index 0000000000..4a1c941cec --- /dev/null +++ b/packages/runner-e2b/src/auth-scope.test.ts @@ -0,0 +1,54 @@ +import { describe, expect, it } from "vitest"; +import { Volume, createFsFromVolume } from "memfs"; +import type { FileSystem } from "@poe-code/config-mutations"; +import { resolveE2bApiKey } from "./auth-scope.js"; + +const cwd = "/repo"; +const homeDir = "/home/test"; + +function memFs(files: Record): FileSystem { + const volume = Volume.fromJSON(files, "/"); + volume.mkdirSync(cwd, { recursive: true }); + volume.mkdirSync(homeDir, { recursive: true }); + return createFsFromVolume(volume).promises as unknown as FileSystem; +} + +describe("resolveE2bApiKey", () => { + it("reads api_key from global ~/.poe-code/config.json", async () => { + const fs = memFs({ + "/home/test/.poe-code/config.json": JSON.stringify({ e2b: { api_key: "g_key" } }) + }); + expect(await resolveE2bApiKey({ cwd, homeDir, fs, env: {} })).toBe("g_key"); + }); + + it("project .poe-code/config.json overrides global", async () => { + const fs = memFs({ + "/home/test/.poe-code/config.json": JSON.stringify({ e2b: { api_key: "g_key" } }), + "/repo/.poe-code/config.json": JSON.stringify({ e2b: { api_key: "p_key" } }) + }); + expect(await resolveE2bApiKey({ cwd, homeDir, fs, env: {} })).toBe("p_key"); + }); + + it("E2B_API_KEY env var wins over config files", async () => { + const fs = memFs({ + "/home/test/.poe-code/config.json": JSON.stringify({ e2b: { api_key: "g_key" } }) + }); + expect( + await resolveE2bApiKey({ cwd, homeDir, fs, env: { E2B_API_KEY: "env_key" } }) + ).toBe("env_key"); + }); + + it("falls back to E2B_API_KEY env var when no config files exist", async () => { + const fs = memFs({}); + expect( + await resolveE2bApiKey({ cwd, homeDir, fs, env: { E2B_API_KEY: "env_key" } }) + ).toBe("env_key"); + }); + + it("throws when no key is found anywhere", async () => { + const fs = memFs({}); + await expect(resolveE2bApiKey({ cwd, homeDir, fs, env: {} })).rejects.toThrow( + /No E2B API key/ + ); + }); +}); diff --git a/packages/runner-e2b/src/auth-scope.ts b/packages/runner-e2b/src/auth-scope.ts new file mode 100644 index 0000000000..cbf944d52e --- /dev/null +++ b/packages/runner-e2b/src/auth-scope.ts @@ -0,0 +1,44 @@ +import os from "node:os"; +import { promises as nodeFs } from "node:fs"; +import { + defineScope, + readMergedDocument, + resolveConfigPath, + resolveProjectConfigPath, + resolveScope +} from "@poe-code/poe-code-config"; +import type { FileSystem } from "@poe-code/config-mutations"; + +export const e2bAuthScope = defineScope("e2b", { + api_key: { + type: "string", + default: "", + doc: "E2B API key", + env: "E2B_API_KEY" + } +}); + +export interface ResolveE2bApiKeyInput { + cwd: string; + homeDir?: string; + fs?: FileSystem; + env?: Record; +} + +export async function resolveE2bApiKey(input: ResolveE2bApiKeyInput): Promise { + const homeDir = input.homeDir ?? os.homedir(); + const fs = input.fs ?? (nodeFs as unknown as FileSystem); + const env = input.env ?? process.env; + const document = await readMergedDocument( + fs, + resolveConfigPath(homeDir), + resolveProjectConfigPath(input.cwd) + ); + const resolved = resolveScope(e2bAuthScope.schema, document.e2b, env); + if (resolved.api_key.length === 0) { + throw new Error( + "No E2B API key. Set E2B_API_KEY or e2b.api_key in ~/.poe-code/config.json." + ); + } + return resolved.api_key; +} diff --git a/packages/runner-e2b/src/factory.test.ts b/packages/runner-e2b/src/factory.test.ts index c8d28a803d..97bc56cc1e 100644 --- a/packages/runner-e2b/src/factory.test.ts +++ b/packages/runner-e2b/src/factory.test.ts @@ -1,6 +1,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; import { buildOrResolveTemplate } from "./template-build.js"; import { createSandbox, connectSandbox } from "./sdk.js"; +import { resolveE2bApiKey } from "./auth-scope.js"; vi.mock("./template-build.js", () => ({ buildOrResolveTemplate: vi.fn() @@ -11,21 +12,23 @@ vi.mock("./sdk.js", () => ({ connectSandbox: vi.fn() })); +vi.mock("./auth-scope.js", () => ({ + resolveE2bApiKey: vi.fn() +})); + describe("e2bExecutionEnvFactory", () => { beforeEach(() => { vi.clearAllMocks(); - delete process.env.E2B_API_KEY; - delete process.env.CUSTOM_E2B_API_KEY; vi.mocked(buildOrResolveTemplate).mockResolvedValue({ templateId: "tmpl_built", cached: false }); vi.mocked(createSandbox).mockResolvedValue(createSandboxMock("sb_open")); vi.mocked(connectSandbox).mockResolvedValue(createSandboxMock("sb_attached")); + vi.mocked(resolveE2bApiKey).mockResolvedValue("resolved_key"); }); - it("opens a sandbox from a direct template id and runtime api key env", async () => { - process.env.CUSTOM_E2B_API_KEY = "key_from_env"; + it("opens a sandbox from a direct template id and resolved api key", async () => { const { e2bExecutionEnvFactory } = await import("./factory.js"); const env = await e2bExecutionEnvFactory.open({ @@ -35,7 +38,6 @@ describe("e2bExecutionEnvFactory", () => { template_id: "tmpl_configured", build_args: {}, mounts: [], - api_key_env: "CUSTOM_E2B_API_KEY", timeout_minutes: 30 }, env: { NODE_ENV: "test" }, @@ -44,40 +46,17 @@ describe("e2bExecutionEnvFactory", () => { }); expect(env.id).toBe("sb_open"); + expect(resolveE2bApiKey).toHaveBeenCalledWith({ cwd: "/repo" }); expect(buildOrResolveTemplate).not.toHaveBeenCalled(); expect(createSandbox).toHaveBeenCalledWith({ - apiKey: "key_from_env", + apiKey: "resolved_key", templateId: "tmpl_configured", env: { NODE_ENV: "test" }, timeoutMinutes: 30 }); }); - it("prefers auth.providers.e2b over runtime api key env", async () => { - process.env.E2B_API_KEY = "key_from_env"; - const { e2bExecutionEnvFactory } = await import("./factory.js"); - - await e2bExecutionEnvFactory.open({ - cwd: "/repo", - runtime: { - type: "e2b", - template_id: "tmpl_configured", - build_args: {}, - mounts: [] - }, - auth: { providers: { e2b: { api_key: "key_from_auth" } } }, - env: {}, - uploadIgnoreFiles: [], - jobLabel: { tool: "node", argv: ["node"] } - } as Parameters[0]); - - expect(createSandbox).toHaveBeenCalledWith( - expect.objectContaining({ apiKey: "key_from_auth" }) - ); - }); - it("builds a template when template_id is absent", async () => { - process.env.E2B_API_KEY = "key_from_env"; const state = { templates: { get: vi.fn(), put: vi.fn() }, jobs: {} }; const { e2bExecutionEnvFactory } = await import("./factory.js"); @@ -101,7 +80,7 @@ describe("e2bExecutionEnvFactory", () => { dockerfilePath: "/repo/Dockerfile", buildContext: "/repo/sandbox", state, - apiKey: "key_from_env" + apiKey: "resolved_key" }); expect(createSandbox).toHaveBeenCalledWith( expect.objectContaining({ templateId: "tmpl_built" }) @@ -109,13 +88,18 @@ describe("e2bExecutionEnvFactory", () => { }); it("attaches to an existing sandbox id", async () => { - process.env.E2B_API_KEY = "key_from_env"; const { e2bExecutionEnvFactory } = await import("./factory.js"); - const env = await e2bExecutionEnvFactory.attach("sb_existing"); + const env = await e2bExecutionEnvFactory.attach("sb_existing", { + cwd: "/repo", + jobId: "job_1", + tool: "node", + argv: ["node"] + }); expect(env.id).toBe("sb_attached"); - expect(connectSandbox).toHaveBeenCalledWith("sb_existing", "key_from_env"); + expect(resolveE2bApiKey).toHaveBeenCalledWith({ cwd: "/repo" }); + expect(connectSandbox).toHaveBeenCalledWith("sb_existing", "resolved_key"); }); }); diff --git a/packages/runner-e2b/src/factory.ts b/packages/runner-e2b/src/factory.ts index 175cc10f3f..f33f26188a 100644 --- a/packages/runner-e2b/src/factory.ts +++ b/packages/runner-e2b/src/factory.ts @@ -4,13 +4,14 @@ import type { ExecutionEnvFactory, OpenSpec, OpenedEnv } from "@poe-code/agent-h import { createSandbox, connectSandbox } from "./sdk.js"; import { buildOrResolveTemplate } from "./template-build.js"; import { createOpenedE2bEnv } from "./opened-env.js"; +import { resolveE2bApiKey } from "./auth-scope.js"; export const e2bExecutionEnvFactory: ExecutionEnvFactory = { type: "e2b", supportsDetach: true, async open(spec): Promise { const runtime = parseE2bRuntime(spec.runtime); - const apiKey = resolveApiKey(spec, runtime); + const apiKey = await resolveE2bApiKey({ cwd: spec.cwd }); const templateId = runtime.template_id ?? ( @@ -35,8 +36,9 @@ export const e2bExecutionEnvFactory: ExecutionEnvFactory = { return createOpenedE2bEnv({ sandbox, spec, runtime }); }, async attach(envId, context): Promise { - const apiKey = process.env.E2B_API_KEY?.trim(); - const sandbox = await connectSandbox(envId, apiKey && apiKey.length > 0 ? apiKey : undefined); + const cwd = context?.cwd ?? process.cwd(); + const apiKey = await resolveE2bApiKey({ cwd }); + const sandbox = await connectSandbox(envId, apiKey); return createOpenedE2bEnv({ sandbox, spec: { @@ -45,7 +47,6 @@ export const e2bExecutionEnvFactory: ExecutionEnvFactory = { type: "e2b", build_args: {}, mounts: [], - api_key_env: "E2B_API_KEY", preserve_after_exit_hours: 24 }, env: {}, @@ -57,7 +58,6 @@ export const e2bExecutionEnvFactory: ExecutionEnvFactory = { type: "e2b", build_args: {}, mounts: [], - api_key_env: "E2B_API_KEY", preserve_after_exit_hours: 24 } }); @@ -74,43 +74,3 @@ function parseE2bRuntime(runtime: unknown): E2bRuntime { } return record as unknown as E2bRuntime; } - -function resolveApiKey(spec: OpenSpec, runtime: E2bRuntime): string { - const authKey = readAuthProviderKey(spec); - if (authKey !== null) { - return authKey; - } - - const envName = runtime.api_key_env ?? "E2B_API_KEY"; - const apiKey = process.env[envName]?.trim(); - if (apiKey && apiKey.length > 0) { - return apiKey; - } - - throw new Error(`No E2B API key found. Set ${envName} or configure auth.providers.e2b.`); -} - -function readAuthProviderKey(spec: OpenSpec): string | null { - const auth = (spec as OpenSpec & { auth?: unknown }).auth; - if (!auth || typeof auth !== "object" || Array.isArray(auth)) { - return null; - } - const providers = (auth as { providers?: unknown }).providers; - if (!providers || typeof providers !== "object" || Array.isArray(providers)) { - return null; - } - const e2b = (providers as { e2b?: unknown }).e2b; - if (typeof e2b === "string") { - const trimmed = e2b.trim(); - return trimmed.length > 0 ? trimmed : null; - } - if (!e2b || typeof e2b !== "object" || Array.isArray(e2b)) { - return null; - } - const apiKey = (e2b as { api_key?: unknown }).api_key; - if (typeof apiKey !== "string") { - return null; - } - const trimmed = apiKey.trim(); - return trimmed.length > 0 ? trimmed : null; -} diff --git a/packages/runner-e2b/src/index.ts b/packages/runner-e2b/src/index.ts index c16ad1245c..41fb1eb14d 100644 --- a/packages/runner-e2b/src/index.ts +++ b/packages/runner-e2b/src/index.ts @@ -2,3 +2,4 @@ import type { ExecutionEnvFactory } from "@poe-code/agent-harness-tools"; import { e2bExecutionEnvFactory as factory } from "./factory.js"; export const e2bExecutionEnvFactory: ExecutionEnvFactory = factory; +export { e2bAuthScope, resolveE2bApiKey } from "./auth-scope.js"; From 6c05badb389646d15655cf3051549b0cb9b98d39 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 21:21:00 -0500 Subject: [PATCH 023/111] fix(runner-e2b): export buildE2bRuntimeTemplate for the runtime build CLI The CLI's runtime build command dynamically imports buildE2bRuntimeTemplate from @poe-code/runner-e2b but the package only exposed the older buildOrResolveTemplate, so e2b builds failed with "package does not export buildE2bRuntimeTemplate". Renames buildOrResolveTemplate to buildE2bRuntimeTemplate, mirrors the docker variant's return shape (backend/hash/templateId/cached), adds force, and exports it. The CLI now also pulls resolveE2bApiKey from the same package so it does not need to know about auth. --- packages/runner-e2b/src/factory.test.ts | 12 +++-- packages/runner-e2b/src/factory.ts | 4 +- packages/runner-e2b/src/index.ts | 5 ++ .../runner-e2b/src/template-build.test.ts | 54 +++++++++++++++---- packages/runner-e2b/src/template-build.ts | 22 +++++--- src/cli/commands/runtime/build.ts | 39 ++++++++------ 6 files changed, 95 insertions(+), 41 deletions(-) diff --git a/packages/runner-e2b/src/factory.test.ts b/packages/runner-e2b/src/factory.test.ts index 97bc56cc1e..721bf53869 100644 --- a/packages/runner-e2b/src/factory.test.ts +++ b/packages/runner-e2b/src/factory.test.ts @@ -1,10 +1,10 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; -import { buildOrResolveTemplate } from "./template-build.js"; +import { buildE2bRuntimeTemplate } from "./template-build.js"; import { createSandbox, connectSandbox } from "./sdk.js"; import { resolveE2bApiKey } from "./auth-scope.js"; vi.mock("./template-build.js", () => ({ - buildOrResolveTemplate: vi.fn() + buildE2bRuntimeTemplate: vi.fn() })); vi.mock("./sdk.js", () => ({ @@ -19,7 +19,9 @@ vi.mock("./auth-scope.js", () => ({ describe("e2bExecutionEnvFactory", () => { beforeEach(() => { vi.clearAllMocks(); - vi.mocked(buildOrResolveTemplate).mockResolvedValue({ + vi.mocked(buildE2bRuntimeTemplate).mockResolvedValue({ + backend: "e2b", + hash: "h", templateId: "tmpl_built", cached: false }); @@ -47,7 +49,7 @@ describe("e2bExecutionEnvFactory", () => { expect(env.id).toBe("sb_open"); expect(resolveE2bApiKey).toHaveBeenCalledWith({ cwd: "/repo" }); - expect(buildOrResolveTemplate).not.toHaveBeenCalled(); + expect(buildE2bRuntimeTemplate).not.toHaveBeenCalled(); expect(createSandbox).toHaveBeenCalledWith({ apiKey: "resolved_key", templateId: "tmpl_configured", @@ -75,7 +77,7 @@ describe("e2bExecutionEnvFactory", () => { jobLabel: { tool: "node", argv: ["node"] } }); - expect(buildOrResolveTemplate).toHaveBeenCalledWith({ + expect(buildE2bRuntimeTemplate).toHaveBeenCalledWith({ runtime: expect.objectContaining({ type: "e2b" }), dockerfilePath: "/repo/Dockerfile", buildContext: "/repo/sandbox", diff --git a/packages/runner-e2b/src/factory.ts b/packages/runner-e2b/src/factory.ts index f33f26188a..a793014d1e 100644 --- a/packages/runner-e2b/src/factory.ts +++ b/packages/runner-e2b/src/factory.ts @@ -2,7 +2,7 @@ import path from "node:path"; import type { E2bRuntime } from "@poe-code/poe-code-config"; import type { ExecutionEnvFactory, OpenSpec, OpenedEnv } from "@poe-code/agent-harness-tools"; import { createSandbox, connectSandbox } from "./sdk.js"; -import { buildOrResolveTemplate } from "./template-build.js"; +import { buildE2bRuntimeTemplate } from "./template-build.js"; import { createOpenedE2bEnv } from "./opened-env.js"; import { resolveE2bApiKey } from "./auth-scope.js"; @@ -15,7 +15,7 @@ export const e2bExecutionEnvFactory: ExecutionEnvFactory = { const templateId = runtime.template_id ?? ( - await buildOrResolveTemplate({ + await buildE2bRuntimeTemplate({ runtime, dockerfilePath: path.resolve( spec.cwd, diff --git a/packages/runner-e2b/src/index.ts b/packages/runner-e2b/src/index.ts index 41fb1eb14d..1cff129168 100644 --- a/packages/runner-e2b/src/index.ts +++ b/packages/runner-e2b/src/index.ts @@ -3,3 +3,8 @@ import { e2bExecutionEnvFactory as factory } from "./factory.js"; export const e2bExecutionEnvFactory: ExecutionEnvFactory = factory; export { e2bAuthScope, resolveE2bApiKey } from "./auth-scope.js"; +export { + buildE2bRuntimeTemplate, + type BuildE2bRuntimeTemplateInput, + type BuildE2bRuntimeTemplateResult +} from "./template-build.js"; diff --git a/packages/runner-e2b/src/template-build.test.ts b/packages/runner-e2b/src/template-build.test.ts index 4e2e78c1dc..964882e91b 100644 --- a/packages/runner-e2b/src/template-build.test.ts +++ b/packages/runner-e2b/src/template-build.test.ts @@ -11,7 +11,7 @@ vi.mock("./sdk.js", () => ({ buildTemplate: vi.fn() })); -describe("buildOrResolveTemplate", () => { +describe("buildE2bRuntimeTemplate", () => { const files = new Map(); beforeEach(() => { @@ -47,9 +47,9 @@ describe("buildOrResolveTemplate", () => { dockerfile_path: "/repo/Dockerfile", built_at: "2026-05-03T00:00:00.000Z" }); - const { buildOrResolveTemplate } = await import("./template-build.js"); + const { buildE2bRuntimeTemplate } = await import("./template-build.js"); - const result = await buildOrResolveTemplate({ + const result = await buildE2bRuntimeTemplate({ apiKey: "e2b_key", runtime: { type: "e2b", @@ -61,16 +61,21 @@ describe("buildOrResolveTemplate", () => { state }); - expect(result).toEqual({ templateId: "tmpl_cached", cached: true }); + expect(result).toEqual({ + backend: "e2b", + hash: expect.any(String), + templateId: "tmpl_cached", + cached: true + }); expect(state.getCalls).toEqual([{ backend: "e2b", hash: expect.any(String) }]); expect(buildTemplate).not.toHaveBeenCalled(); }); it("builds and caches an E2B template on cache miss", async () => { const state = createState(null); - const { buildOrResolveTemplate } = await import("./template-build.js"); + const { buildE2bRuntimeTemplate } = await import("./template-build.js"); - const result = await buildOrResolveTemplate({ + const result = await buildE2bRuntimeTemplate({ apiKey: "e2b_key", runtime: { type: "e2b", @@ -84,7 +89,12 @@ describe("buildOrResolveTemplate", () => { state }); - expect(result).toEqual({ templateId: "tmpl_built", cached: false }); + expect(result).toEqual({ + backend: "e2b", + hash: expect.any(String), + templateId: "tmpl_built", + cached: false + }); expect(buildTemplate).toHaveBeenCalledWith({ apiKey: "e2b_key", name: expect.stringMatching(/^poe-code-[a-f0-9]{32}$/), @@ -104,11 +114,35 @@ describe("buildOrResolveTemplate", () => { }); }); + it("rebuilds when force is true even when a cached template exists", async () => { + const state = createState({ + hash: "unused", + template_id: "tmpl_cached", + runtime_type: "e2b", + dockerfile_path: "/repo/Dockerfile", + built_at: "2026-05-03T00:00:00.000Z" + }); + const { buildE2bRuntimeTemplate } = await import("./template-build.js"); + + const result = await buildE2bRuntimeTemplate({ + apiKey: "e2b_key", + runtime: { type: "e2b", build_args: {}, mounts: [] }, + dockerfilePath: "/repo/Dockerfile", + buildContext: "/repo", + state, + force: true + }); + + expect(result.cached).toBe(false); + expect(result.templateId).toBe("tmpl_built"); + expect(buildTemplate).toHaveBeenCalledTimes(1); + }); + it("changes the template cache hash when build context file contents change", async () => { const state = createState(null); - const { buildOrResolveTemplate } = await import("./template-build.js"); + const { buildE2bRuntimeTemplate } = await import("./template-build.js"); - await buildOrResolveTemplate({ + await buildE2bRuntimeTemplate({ apiKey: "e2b_key", runtime: { type: "e2b", @@ -120,7 +154,7 @@ describe("buildOrResolveTemplate", () => { state }); files.set("/repo/src/index.js", "console.log('two')\n"); - await buildOrResolveTemplate({ + await buildE2bRuntimeTemplate({ apiKey: "e2b_key", runtime: { type: "e2b", diff --git a/packages/runner-e2b/src/template-build.ts b/packages/runner-e2b/src/template-build.ts index 867b2e8af7..6be664afc0 100644 --- a/packages/runner-e2b/src/template-build.ts +++ b/packages/runner-e2b/src/template-build.ts @@ -4,24 +4,32 @@ import path from "node:path"; import type { E2bRuntime, StateManager } from "@poe-code/poe-code-config"; import { buildTemplate } from "./sdk.js"; -export interface BuildOrResolveTemplateInput { +export interface BuildE2bRuntimeTemplateInput { runtime: E2bRuntime; dockerfilePath: string; buildContext: string; state?: Pick; apiKey: string; + force?: boolean; } -export async function buildOrResolveTemplate( - input: BuildOrResolveTemplateInput -): Promise<{ templateId: string; cached: boolean }> { +export interface BuildE2bRuntimeTemplateResult { + backend: "e2b"; + hash: string; + templateId: string; + cached: boolean; +} + +export async function buildE2bRuntimeTemplate( + input: BuildE2bRuntimeTemplateInput +): Promise { const dockerfileBytes = await readFile(input.dockerfilePath); const buildContextFiles = await readBuildContextFiles(input.buildContext); const hash = hashTemplate(dockerfileBytes, buildContextFiles, input.runtime.build_args); - const cached = await input.state?.templates.get("e2b", hash); + const cached = input.force === true ? null : await input.state?.templates.get("e2b", hash); if (cached?.template_id !== undefined) { - return { templateId: cached.template_id, cached: true }; + return { backend: "e2b", hash, templateId: cached.template_id, cached: true }; } const built = await buildTemplate({ @@ -41,7 +49,7 @@ export async function buildOrResolveTemplate( built_at: new Date().toISOString() }); - return { templateId: built.templateId, cached: false }; + return { backend: "e2b", hash, templateId: built.templateId, cached: false }; } function hashTemplate( diff --git a/src/cli/commands/runtime/build.ts b/src/cli/commands/runtime/build.ts index 8699548b37..b1d552da4a 100644 --- a/src/cli/commands/runtime/build.ts +++ b/src/cli/commands/runtime/build.ts @@ -10,7 +10,7 @@ import { } from "@poe-code/poe-code-config"; import { pathExists } from "@poe-code/config-mutations"; import { buildDockerRuntimeTemplate } from "@poe-code/process-runner"; -import type { ExecutionState, Runner } from "@poe-code/process-runner"; +import type { ExecutionState } from "@poe-code/process-runner"; import type { CliContainer } from "../../container.js"; import { createExecutionResources, resolveCommandFlags } from "../shared.js"; @@ -25,15 +25,17 @@ interface BuildE2bRuntimeTemplateResult { cached: boolean; } -type BuildE2bRuntimeTemplate = (input: { - cwd: string; - runtime: E2bRuntime; - dockerfilePath: string; - buildContext: string; - state?: ExecutionState; - runner?: Runner; - force?: boolean; -}) => Promise; +interface E2bRunnerModule { + buildE2bRuntimeTemplate: (input: { + runtime: E2bRuntime; + dockerfilePath: string; + buildContext: string; + state?: ExecutionState; + apiKey: string; + force?: boolean; + }) => Promise; + resolveE2bApiKey: (input: { cwd: string }) => Promise; +} export function registerRuntimeBuildCommand( runtime: Command, @@ -112,13 +114,14 @@ async function executeRuntimeBuild( return; } const paths = await requireRuntimeBuildPaths(container, runtimeConfig, "E2B"); - const buildE2bRuntimeTemplate = await loadE2bRuntimeTemplateBuilder(); - const result = await buildE2bRuntimeTemplate({ - cwd: container.env.cwd, + const e2bModule = await loadE2bRunnerModule(); + const apiKey = await e2bModule.resolveE2bApiKey({ cwd: container.env.cwd }); + const result = await e2bModule.buildE2bRuntimeTemplate({ runtime: runtimeConfig, dockerfilePath: paths.dockerfilePath, buildContext: paths.buildContext, state, + apiKey, force: options.force === true }); resources.logger.success( @@ -146,7 +149,7 @@ async function requireRuntimeBuildPaths( }; } -async function loadE2bRuntimeTemplateBuilder(): Promise { +async function loadE2bRunnerModule(): Promise { const dynamicImport = new Function("specifier", "return import(specifier)") as ( specifier: string ) => Promise; @@ -157,9 +160,11 @@ async function loadE2bRuntimeTemplateBuilder(): Promise module && typeof module === "object" && "buildE2bRuntimeTemplate" in module && - typeof module.buildE2bRuntimeTemplate === "function" + typeof module.buildE2bRuntimeTemplate === "function" && + "resolveE2bApiKey" in module && + typeof module.resolveE2bApiKey === "function" ) { - return module.buildE2bRuntimeTemplate as BuildE2bRuntimeTemplate; + return module as unknown as E2bRunnerModule; } } catch (error) { if (isModuleNotFound(error)) { @@ -171,7 +176,7 @@ async function loadE2bRuntimeTemplateBuilder(): Promise } throw new Error( - "E2B runtime builds require @poe-code/runner-e2b to export buildE2bRuntimeTemplate." + "E2B runtime builds require @poe-code/runner-e2b to export buildE2bRuntimeTemplate and resolveE2bApiKey." ); } From f6beafcb1213130ce9d17ee85910794816dfe5e8 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 21:24:19 -0500 Subject: [PATCH 024/111] fix(cli): default Dockerfile installs poe-code, not @poe-code/cli The CLI is published as the unscoped poe-code on npm; the runtime init Dockerfile referenced @poe-code/cli, which 404s and broke e2b template builds at the npm install step. --- src/cli/commands/runtime.test.ts | 2 +- src/cli/commands/runtime/shared.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cli/commands/runtime.test.ts b/src/cli/commands/runtime.test.ts index a65ee3ca2f..a087784651 100644 --- a/src/cli/commands/runtime.test.ts +++ b/src/cli/commands/runtime.test.ts @@ -212,7 +212,7 @@ describe("runtime command", () => { await expect(fs.readFile(projectConfigPath, "utf8")).resolves.toContain('"type": "docker"'); await expect(fs.readFile(dockerfilePath, "utf8")).resolves.toContain( - "npm i -g @poe-code/cli @anthropic-ai/claude-code" + "npm i -g poe-code @anthropic-ai/claude-code" ); }); diff --git a/src/cli/commands/runtime/shared.ts b/src/cli/commands/runtime/shared.ts index 70dff450cd..70afcd6dcc 100644 --- a/src/cli/commands/runtime/shared.ts +++ b/src/cli/commands/runtime/shared.ts @@ -16,7 +16,7 @@ export const defaultDockerfile = [ " && apt-get install -y --no-install-recommends git ca-certificates \\", " && rm -rf /var/lib/apt/lists/*", "", - "RUN npm i -g @poe-code/cli @anthropic-ai/claude-code", + "RUN npm i -g poe-code @anthropic-ai/claude-code", "" ].join("\n"); From 82b50f3cc47066142df8b804e703487b98d84f6b Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 21:24:34 -0500 Subject: [PATCH 025/111] chore: scaffold e2b runtime for the poe-code project runtime init wrote .poe-code/Dockerfile and runtime.type=e2b in .poe-code/config.json. build_context is narrowed to .poe-code so the template hash does not walk the whole monorepo. --- .poe-code/Dockerfile | 7 +++++++ .poe-code/config.json | 4 ++++ 2 files changed, 11 insertions(+) create mode 100644 .poe-code/Dockerfile diff --git a/.poe-code/Dockerfile b/.poe-code/Dockerfile new file mode 100644 index 0000000000..3d3f4f8344 --- /dev/null +++ b/.poe-code/Dockerfile @@ -0,0 +1,7 @@ +FROM node:22-bookworm-slim + +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates \ + && rm -rf /var/lib/apt/lists/* + +RUN npm i -g poe-code @anthropic-ai/claude-code diff --git a/.poe-code/config.json b/.poe-code/config.json index 9e872f1f1e..2f4b29fcd9 100644 --- a/.poe-code/config.json +++ b/.poe-code/config.json @@ -1,5 +1,9 @@ { "ralph": { "plan_directory": "docs/plans" + }, + "runtime": { + "type": "e2b", + "build_context": ".poe-code" } } From d79fdaf46c988b9b58cc609ffd3a72b664c8b581 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 21:29:38 -0500 Subject: [PATCH 026/111] fix(cli): default runtime Dockerfile installs only poe-code Runtime init scaffolds a starter image. Bundling claude-code by default ties new projects to one specific agent; users who want it can add the install line. The default keeps poe-code plus git + ca-certificates so the sandbox can fetch repos. --- src/cli/commands/runtime.test.ts | 2 +- src/cli/commands/runtime/shared.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cli/commands/runtime.test.ts b/src/cli/commands/runtime.test.ts index a087784651..039c5b4fba 100644 --- a/src/cli/commands/runtime.test.ts +++ b/src/cli/commands/runtime.test.ts @@ -212,7 +212,7 @@ describe("runtime command", () => { await expect(fs.readFile(projectConfigPath, "utf8")).resolves.toContain('"type": "docker"'); await expect(fs.readFile(dockerfilePath, "utf8")).resolves.toContain( - "npm i -g poe-code @anthropic-ai/claude-code" + "npm i -g poe-code" ); }); diff --git a/src/cli/commands/runtime/shared.ts b/src/cli/commands/runtime/shared.ts index 70afcd6dcc..da211962a5 100644 --- a/src/cli/commands/runtime/shared.ts +++ b/src/cli/commands/runtime/shared.ts @@ -16,7 +16,7 @@ export const defaultDockerfile = [ " && apt-get install -y --no-install-recommends git ca-certificates \\", " && rm -rf /var/lib/apt/lists/*", "", - "RUN npm i -g poe-code @anthropic-ai/claude-code", + "RUN npm i -g poe-code", "" ].join("\n"); From 0093857a6b8a9b7caa4c6c951d6b2b4dc25bd383 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 21:29:53 -0500 Subject: [PATCH 027/111] chore: install all coding agents in the project sandbox image The poe-code project's e2b sandbox is the place where every agent needs to be exercisable end-to-end. Adds claude-code, codex, opencode (npm), kimi-cli (uv), and goose (curl installer) on top of poe-code itself. Skips claude-desktop (GUI) and poe-agent (bundled in poe-code). --- .poe-code/Dockerfile | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/.poe-code/Dockerfile b/.poe-code/Dockerfile index 3d3f4f8344..3dbf329f8d 100644 --- a/.poe-code/Dockerfile +++ b/.poe-code/Dockerfile @@ -1,7 +1,20 @@ FROM node:22-bookworm-slim RUN apt-get update \ - && apt-get install -y --no-install-recommends git ca-certificates \ + && apt-get install -y --no-install-recommends git ca-certificates curl python3 python3-venv \ && rm -rf /var/lib/apt/lists/* -RUN npm i -g poe-code @anthropic-ai/claude-code +ENV UV_INSTALL_DIR=/usr/local/bin +RUN curl -LsSf https://astral.sh/uv/install.sh | sh + +RUN npm i -g \ + poe-code \ + @anthropic-ai/claude-code \ + @openai/codex \ + opencode-ai + +RUN uv tool install --python 3.13 kimi-cli +ENV PATH="/root/.local/bin:${PATH}" + +RUN curl -fsSL https://github.com/block/goose/releases/download/stable/download_cli.sh \ + | CONFIGURE=false bash From 63581b45e0661342cf6f24fb428534820d17b8d6 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 21:31:36 -0500 Subject: [PATCH 028/111] chore: install agents via poe-code install instead of inlining commands Each provider already declares its install steps; calling poe-code install keeps the Dockerfile aligned with the provider definition rather than duplicating npm / curl / uv invocations that would drift when a provider's install changes. --- .poe-code/Dockerfile | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/.poe-code/Dockerfile b/.poe-code/Dockerfile index 3dbf329f8d..a4ceb68ebf 100644 --- a/.poe-code/Dockerfile +++ b/.poe-code/Dockerfile @@ -7,14 +7,11 @@ RUN apt-get update \ ENV UV_INSTALL_DIR=/usr/local/bin RUN curl -LsSf https://astral.sh/uv/install.sh | sh -RUN npm i -g \ - poe-code \ - @anthropic-ai/claude-code \ - @openai/codex \ - opencode-ai +RUN npm i -g poe-code -RUN uv tool install --python 3.13 kimi-cli ENV PATH="/root/.local/bin:${PATH}" - -RUN curl -fsSL https://github.com/block/goose/releases/download/stable/download_cli.sh \ - | CONFIGURE=false bash +RUN poe-code install claude-code \ + && poe-code install codex \ + && poe-code install opencode \ + && poe-code install kimi \ + && poe-code install goose From 20fcd6a024dfcce90856092bd9ac889f6b021cba Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 21:35:25 -0500 Subject: [PATCH 029/111] feat(sdk): export the resolved Poe API key into process.env before spawn Spawn already pre-flighted credentials by calling getPoeApiKey but discarded the value. Anyone who logged in with poe-code login (key stored in the encrypted auth-store, not in env) had nothing to propagate to a sandboxed runtime, since agent-spawn forwards process.env into the e2b sandbox env. Now the resolved key is written back into process.env when it is not already exported, so login-only users get the same automatic sandbox auth that env-var users already had. Existing exports are untouched. --- src/sdk/spawn.test.ts | 48 +++++++++++++++++++++++++++++++++++++++++++ src/sdk/spawn.ts | 5 ++++- 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/src/sdk/spawn.test.ts b/src/sdk/spawn.test.ts index 43c684b473..dd759b4bdc 100644 --- a/src/sdk/spawn.test.ts +++ b/src/sdk/spawn.test.ts @@ -49,6 +49,12 @@ vi.mock("@poe-code/workspace-resolver", async (importOriginal) => { }; }); +const getPoeApiKeyMock = vi.hoisted(() => vi.fn()); + +vi.mock("./credentials.js", () => ({ + getPoeApiKey: getPoeApiKeyMock +})); + import { spawn } from "./spawn.js"; import { getAcpSpawnConfig, @@ -87,6 +93,8 @@ function createMemFs(): FileSystem { beforeEach(() => { process.env = { ...originalEnv, POE_API_KEY: "test-key" }; + getPoeApiKeyMock.mockReset(); + getPoeApiKeyMock.mockResolvedValue("test-key"); vi.mocked(spawnStreaming).mockReset(); vi.mocked(spawnInteractive).mockReset(); vi.mocked(agentSpawn).mockReset(); @@ -1224,4 +1232,44 @@ describe("spawn.autonomous()", () => { }) ); }); + + it("propagates a stored Poe API key into process.env so the runtime sandbox sees it", async () => { + delete process.env.POE_API_KEY; + getPoeApiKeyMock.mockResolvedValue("stored-key"); + + vi.mocked(getSpawnConfig).mockReturnValue({ + kind: "cli", + agentId: "codex", + adapter: "codex" + } as any); + vi.mocked(spawnStreaming).mockImplementation(() => ({ + events: (async function* () {})(), + done: Promise.resolve({ stdout: "", stderr: "", exitCode: 0 }) + })); + + const { result } = spawn("codex", "test prompt"); + await result; + + expect(process.env.POE_API_KEY).toBe("stored-key"); + }); + + it("does not overwrite POE_API_KEY when it is already exported", async () => { + process.env.POE_API_KEY = "exported-key"; + getPoeApiKeyMock.mockResolvedValue("exported-key"); + + vi.mocked(getSpawnConfig).mockReturnValue({ + kind: "cli", + agentId: "codex", + adapter: "codex" + } as any); + vi.mocked(spawnStreaming).mockImplementation(() => ({ + events: (async function* () {})(), + done: Promise.resolve({ stdout: "", stderr: "", exitCode: 0 }) + })); + + const { result } = spawn("codex", "test prompt"); + await result; + + expect(process.env.POE_API_KEY).toBe("exported-key"); + }); }); diff --git a/src/sdk/spawn.ts b/src/sdk/spawn.ts index 4ef7f6d034..dcf6362837 100644 --- a/src/sdk/spawn.ts +++ b/src/sdk/spawn.ts @@ -119,7 +119,10 @@ export function spawn( }); const cwd = workspace.cwd; - await getPoeApiKey(); + const resolvedApiKey = await getPoeApiKey(); + if (!process.env.POE_API_KEY || process.env.POE_API_KEY.trim().length === 0) { + process.env.POE_API_KEY = resolvedApiKey; + } let container: ReturnType | undefined; const getContainer = () => { From 0a0dcc568cf4d48b25a1b1652493424aed3e7112 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 21:38:28 -0500 Subject: [PATCH 030/111] chore: stop pinning runtime type in project config The repo defaults back to the host runtime; e2b is selected explicitly with --runtime e2b on the spawn / runtime commands. --- .poe-code/config.json | 4 ---- 1 file changed, 4 deletions(-) diff --git a/.poe-code/config.json b/.poe-code/config.json index 2f4b29fcd9..9e872f1f1e 100644 --- a/.poe-code/config.json +++ b/.poe-code/config.json @@ -1,9 +1,5 @@ { "ralph": { "plan_directory": "docs/plans" - }, - "runtime": { - "type": "e2b", - "build_context": ".poe-code" } } From 3350dbe790e44a5f9747f5dd8fec4cfbe8ce1a3c Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 21:45:40 -0500 Subject: [PATCH 031/111] feat(runtime): surface build log tail on e2b failures and add a spinner Two improvements to runtime build: - buildE2bRuntimeTemplate now wires e2b's onBuildLogs through the SDK and keeps a sliding tail of the last 30 entries. When the underlying build throws, the tail is appended to the error message so the actual failing line (e.g. "npm ERR! 404 Not Found" or "Killed signal 9") shows up in the CLI output instead of just "exit status 1". - The runtime build CLI wraps the e2b call in withSpinner and forwards warn/error log entries while the build runs, so the three-minute silent wait is gone. Also: runtime build now accepts --runtime / --runtime-image / --runtime-template overrides via addRuntimeOptions, matching what spawn already supports. This is the only way to build an e2b template when the project config doesn't pin runtime.type. --- packages/runner-e2b/src/sdk.ts | 10 ++- .../runner-e2b/src/template-build.test.ts | 48 +++++++++++++- packages/runner-e2b/src/template-build.ts | 47 +++++++++++--- src/cli/commands/runtime/build.ts | 63 +++++++++++++------ 4 files changed, 138 insertions(+), 30 deletions(-) diff --git a/packages/runner-e2b/src/sdk.ts b/packages/runner-e2b/src/sdk.ts index 3c3ae7d22e..5af2f440bb 100644 --- a/packages/runner-e2b/src/sdk.ts +++ b/packages/runner-e2b/src/sdk.ts @@ -93,6 +93,13 @@ export interface BuildTemplateOptions { buildContext: string; cpu?: number; memoryMb?: number; + onLog?: (entry: BuildLogEntry) => void; +} + +export interface BuildLogEntry { + level: "debug" | "info" | "warn" | "error"; + message: string; + timestamp: Date; } export interface BuildTemplateResult { @@ -122,7 +129,8 @@ export async function buildTemplate(opts: BuildTemplateOptions): Promise { dockerfilePath: "/repo/Dockerfile", buildContext: "/repo", cpu: 4, - memoryMb: 4096 + memoryMb: 4096, + onLog: expect.any(Function) }); expect(state.putCalls[0]).toMatchObject({ backend: "e2b", @@ -168,6 +169,51 @@ describe("buildE2bRuntimeTemplate", () => { expect(state.getCalls[0]?.hash).not.toBe(state.getCalls[1]?.hash); }); + + it("appends the captured build log tail when buildTemplate throws", async () => { + vi.mocked(buildTemplate).mockImplementation(async (opts) => { + opts.onLog?.({ level: "info", message: "Step 1/3 : FROM node:22", timestamp: new Date() }); + opts.onLog?.({ level: "info", message: "Step 2/3 : RUN npm i -g poe-code", timestamp: new Date() }); + opts.onLog?.({ level: "error", message: "npm ERR! 404 Not Found", timestamp: new Date() }); + throw new Error("failed to run command 'npm i -g poe-code': exit status 1"); + }); + const state = createState(null); + const { buildE2bRuntimeTemplate } = await import("./template-build.js"); + + await expect( + buildE2bRuntimeTemplate({ + apiKey: "e2b_key", + runtime: { type: "e2b", build_args: {}, mounts: [] }, + dockerfilePath: "/repo/Dockerfile", + buildContext: "/repo", + state + }) + ).rejects.toThrow(/Last build output:[\s\S]*npm ERR! 404 Not Found/); + }); + + it("forwards onLog entries to the caller", async () => { + const seen: string[] = []; + vi.mocked(buildTemplate).mockImplementation(async (opts) => { + opts.onLog?.({ level: "info", message: "step a", timestamp: new Date() }); + opts.onLog?.({ level: "info", message: "step b", timestamp: new Date() }); + return { templateId: "tmpl_built" }; + }); + const state = createState(null); + const { buildE2bRuntimeTemplate } = await import("./template-build.js"); + + await buildE2bRuntimeTemplate({ + apiKey: "e2b_key", + runtime: { type: "e2b", build_args: {}, mounts: [] }, + dockerfilePath: "/repo/Dockerfile", + buildContext: "/repo", + state, + onLog: (entry) => { + seen.push(entry.message); + } + }); + + expect(seen).toEqual(["step a", "step b"]); + }); }); function dirent(name: string, type: "dir" | "file") { diff --git a/packages/runner-e2b/src/template-build.ts b/packages/runner-e2b/src/template-build.ts index 6be664afc0..22e79007d8 100644 --- a/packages/runner-e2b/src/template-build.ts +++ b/packages/runner-e2b/src/template-build.ts @@ -2,7 +2,7 @@ import { createHash } from "node:crypto"; import { readdir, readFile } from "node:fs/promises"; import path from "node:path"; import type { E2bRuntime, StateManager } from "@poe-code/poe-code-config"; -import { buildTemplate } from "./sdk.js"; +import { buildTemplate, type BuildLogEntry } from "./sdk.js"; export interface BuildE2bRuntimeTemplateInput { runtime: E2bRuntime; @@ -11,6 +11,7 @@ export interface BuildE2bRuntimeTemplateInput { state?: Pick; apiKey: string; force?: boolean; + onLog?: (entry: BuildLogEntry) => void; } export interface BuildE2bRuntimeTemplateResult { @@ -20,6 +21,8 @@ export interface BuildE2bRuntimeTemplateResult { cached: boolean; } +const BUILD_LOG_TAIL_SIZE = 30; + export async function buildE2bRuntimeTemplate( input: BuildE2bRuntimeTemplateInput ): Promise { @@ -32,14 +35,29 @@ export async function buildE2bRuntimeTemplate( return { backend: "e2b", hash, templateId: cached.template_id, cached: true }; } - const built = await buildTemplate({ - apiKey: input.apiKey, - name: `poe-code-${hash.slice(0, 32)}`, - dockerfilePath: input.dockerfilePath, - buildContext: input.buildContext, - cpu: input.runtime.cpu, - memoryMb: input.runtime.memory_mb - }); + const tail: string[] = []; + const onLog = (entry: BuildLogEntry): void => { + tail.push(entry.message); + if (tail.length > BUILD_LOG_TAIL_SIZE) { + tail.shift(); + } + input.onLog?.(entry); + }; + + let built; + try { + built = await buildTemplate({ + apiKey: input.apiKey, + name: `poe-code-${hash.slice(0, 32)}`, + dockerfilePath: input.dockerfilePath, + buildContext: input.buildContext, + cpu: input.runtime.cpu, + memoryMb: input.runtime.memory_mb, + onLog + }); + } catch (error) { + throw decorateBuildError(error, tail); + } await input.state?.templates.put("e2b", { hash, @@ -52,6 +70,17 @@ export async function buildE2bRuntimeTemplate( return { backend: "e2b", hash, templateId: built.templateId, cached: false }; } +function decorateBuildError(error: unknown, tail: string[]): Error { + const original = error instanceof Error ? error : new Error(String(error)); + if (tail.length === 0) { + return original; + } + const decorated = new Error(`${original.message}\n\nLast build output:\n${tail.join("\n")}`); + decorated.stack = original.stack; + (decorated as Error & { cause?: unknown }).cause = original; + return decorated; +} + function hashTemplate( dockerfileBytes: Buffer, buildContextFiles: BuildContextFile[], diff --git a/src/cli/commands/runtime/build.ts b/src/cli/commands/runtime/build.ts index b1d552da4a..59ea995756 100644 --- a/src/cli/commands/runtime/build.ts +++ b/src/cli/commands/runtime/build.ts @@ -11,10 +11,18 @@ import { import { pathExists } from "@poe-code/config-mutations"; import { buildDockerRuntimeTemplate } from "@poe-code/process-runner"; import type { ExecutionState } from "@poe-code/process-runner"; +import { withSpinner } from "@poe-code/design-system"; import type { CliContainer } from "../../container.js"; import { createExecutionResources, resolveCommandFlags } from "../shared.js"; +import { addRuntimeOptions, pickRuntimeOptions, type RuntimeCliOptions } from "../runtime-options.js"; -export interface RuntimeBuildOptions { +interface BuildLogEntry { + level: "debug" | "info" | "warn" | "error"; + message: string; + timestamp: Date; +} + +export interface RuntimeBuildOptions extends RuntimeCliOptions { force?: boolean; } @@ -33,6 +41,7 @@ interface E2bRunnerModule { state?: ExecutionState; apiKey: string; force?: boolean; + onLog?: (entry: BuildLogEntry) => void; }) => Promise; resolveE2bApiKey: (input: { cwd: string }) => Promise; } @@ -42,13 +51,13 @@ export function registerRuntimeBuildCommand( root: Command, container: CliContainer ): void { - runtime + const cmd = runtime .command("build") .description("Build the configured runtime template.") - .option("--force", "Ignore the local template cache and rebuild.") - .action(async (options: RuntimeBuildOptions) => { - await executeRuntimeBuild(root, container, options); - }); + .option("--force", "Ignore the local template cache and rebuild."); + addRuntimeOptions(cmd).action(async (options: RuntimeBuildOptions) => { + await executeRuntimeBuild(root, container, options); + }); } async function executeRuntimeBuild( @@ -72,7 +81,15 @@ async function executeRuntimeBuild( document.runtime, container.env.variables ); - const runtimeConfig = parseRuntime(runtimeScope); + const runtimeOverrides = pickRuntimeOptions(options); + const runtimeConfig = parseRuntime({ + ...runtimeScope, + ...(runtimeOverrides.runtime !== undefined ? { type: runtimeOverrides.runtime } : {}), + ...(runtimeOverrides.runtimeImage !== undefined ? { image: runtimeOverrides.runtimeImage } : {}), + ...(runtimeOverrides.runtimeTemplate !== undefined + ? { template_id: runtimeOverrides.runtimeTemplate } + : {}) + }); resources.logger.intro("runtime build"); @@ -116,19 +133,27 @@ async function executeRuntimeBuild( const paths = await requireRuntimeBuildPaths(container, runtimeConfig, "E2B"); const e2bModule = await loadE2bRunnerModule(); const apiKey = await e2bModule.resolveE2bApiKey({ cwd: container.env.cwd }); - const result = await e2bModule.buildE2bRuntimeTemplate({ - runtime: runtimeConfig, - dockerfilePath: paths.dockerfilePath, - buildContext: paths.buildContext, - state, - apiKey, - force: options.force === true + await withSpinner({ + message: "Building E2B template", + fn: () => + e2bModule.buildE2bRuntimeTemplate({ + runtime: runtimeConfig, + dockerfilePath: paths.dockerfilePath, + buildContext: paths.buildContext, + state, + apiKey, + force: options.force === true, + onLog: (entry) => { + if (entry.level === "warn" || entry.level === "error") { + resources.logger.info(`[${entry.level}] ${entry.message}`); + } + } + }), + stopMessage: (r) => + r.cached + ? `Using cached E2B template ${r.templateId}` + : `Built E2B template ${r.templateId}` }); - resources.logger.success( - result.cached - ? `Using cached E2B template ${result.templateId}` - : `Built E2B template ${result.templateId}` - ); } async function requireRuntimeBuildPaths( From 362b4936f8dbdd2bbd1bb14a0e988f5053f55c34 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 21:47:07 -0500 Subject: [PATCH 032/111] fix(runtime): host runtime in build is a user error, not a no-op runtime build silently logged "Host runtime does not require a template build" and returned successfully when no e2b/docker runtime was selected. That hides the real situation: the user asked to build something and the CLI did nothing. Now it throws a ValidationError pointing at the two ways to fix it (--runtime flag or runtime.type in config), matching how the rest of the CLI handles user errors. --- src/cli/commands/runtime/build.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/cli/commands/runtime/build.ts b/src/cli/commands/runtime/build.ts index 59ea995756..fd543fc687 100644 --- a/src/cli/commands/runtime/build.ts +++ b/src/cli/commands/runtime/build.ts @@ -15,6 +15,7 @@ import { withSpinner } from "@poe-code/design-system"; import type { CliContainer } from "../../container.js"; import { createExecutionResources, resolveCommandFlags } from "../shared.js"; import { addRuntimeOptions, pickRuntimeOptions, type RuntimeCliOptions } from "../runtime-options.js"; +import { ValidationError } from "../../errors.js"; interface BuildLogEntry { level: "debug" | "info" | "warn" | "error"; @@ -94,8 +95,11 @@ async function executeRuntimeBuild( resources.logger.intro("runtime build"); if (runtimeConfig.type === "host") { - resources.logger.info("Host runtime does not require a template build."); - return; + throw new ValidationError( + "Host runtime has no template to build. " + + "Pass --runtime e2b or --runtime docker, " + + 'or set "runtime": { "type": "..." } in .poe-code/config.json.' + ); } if (runtimeConfig.type === "docker") { From 76ca4c9b8a91f63f5c179d8ee3c5261971895d5e Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 21:48:35 -0500 Subject: [PATCH 033/111] chore: bump e2b sandbox memory to 4096 MB for the poe-code project Building the project sandbox image installs claude-code via Anthropic's curl installer, which exceeds the 1024 MB e2b default and dies with SIGKILL. 4096 MB gives the installers headroom and also fits running multiple agents concurrently in the eventual sandbox. Only memory_mb is configured; runtime.type stays unset so the sandbox is opt-in via --runtime e2b on each command. --- .poe-code/config.json | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.poe-code/config.json b/.poe-code/config.json index 9e872f1f1e..89523e8f5e 100644 --- a/.poe-code/config.json +++ b/.poe-code/config.json @@ -1,5 +1,8 @@ { "ralph": { "plan_directory": "docs/plans" + }, + "runtime": { + "memory_mb": 4096 } } From 34f1b655c34cad0d50eb04ef7411d219251f3fd3 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 21:52:28 -0500 Subject: [PATCH 034/111] chore: raise e2b sandbox to 8 GB / 4 vCPU for the poe-code project 4 GB still SIGKILL'd the claude installer's post-download "claude install" step. 8 GB and 4 vCPU clear it (claude / codex / opencode / kimi all install cleanly), and they sit inside e2b's standard plan ceiling so this is not a tier-special config. Goose is the next failure (exit 1 from its download_cli.sh, not OOM); investigating separately. --- .poe-code/config.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.poe-code/config.json b/.poe-code/config.json index 89523e8f5e..c859cf514a 100644 --- a/.poe-code/config.json +++ b/.poe-code/config.json @@ -3,6 +3,7 @@ "plan_directory": "docs/plans" }, "runtime": { - "memory_mb": 4096 + "memory_mb": 8192, + "cpu": 4 } } From 4d97b021ceb7268e9909fc196ebd02b5c1f25491 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 21:55:18 -0500 Subject: [PATCH 035/111] fix: install bzip2 in the project sandbox image goose's download_cli.sh ships its Linux release as a .tar.bz2 and calls 'tar -xjf', which requires bzip2. node:22-bookworm-slim does not include it, so the install step exited with code 1 right after the binary downloaded. Adding bzip2 to the apt-get line fixes the install. The full build now completes with claude-code, codex, opencode, kimi, and goose all installed. --- .poe-code/Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.poe-code/Dockerfile b/.poe-code/Dockerfile index a4ceb68ebf..70b68dc9a1 100644 --- a/.poe-code/Dockerfile +++ b/.poe-code/Dockerfile @@ -1,7 +1,7 @@ FROM node:22-bookworm-slim RUN apt-get update \ - && apt-get install -y --no-install-recommends git ca-certificates curl python3 python3-venv \ + && apt-get install -y --no-install-recommends git ca-certificates curl bzip2 python3 python3-venv \ && rm -rf /var/lib/apt/lists/* ENV UV_INSTALL_DIR=/usr/local/bin From 4b4d51378ce202bb4a22b2e3e47e47d26cf4bf77 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 22:00:54 -0500 Subject: [PATCH 036/111] chore: slim the project sandbox image and revert to default e2b sizing Switches the project's e2b image to install claude-code via npm instead of Anthropic's curl installer (which OOM'd at 1 GB and only cleared at 8 GB), and drops goose entirely - its install script was failing on bzip2 anyway and we'll bring it back once it's worth the bytes. With those out of the way, the build fits comfortably in e2b's default 1024 MB / 2 vCPU sandbox, so memory_mb/cpu come out of the project config too. Every spawn from this template now runs at default cost instead of 8x. --- .poe-code/Dockerfile | 10 ++++------ .poe-code/config.json | 4 ---- 2 files changed, 4 insertions(+), 10 deletions(-) diff --git a/.poe-code/Dockerfile b/.poe-code/Dockerfile index 70b68dc9a1..2ceca32ae8 100644 --- a/.poe-code/Dockerfile +++ b/.poe-code/Dockerfile @@ -1,17 +1,15 @@ FROM node:22-bookworm-slim RUN apt-get update \ - && apt-get install -y --no-install-recommends git ca-certificates curl bzip2 python3 python3-venv \ + && apt-get install -y --no-install-recommends git ca-certificates curl python3 python3-venv \ && rm -rf /var/lib/apt/lists/* ENV UV_INSTALL_DIR=/usr/local/bin RUN curl -LsSf https://astral.sh/uv/install.sh | sh -RUN npm i -g poe-code +RUN npm i -g poe-code @anthropic-ai/claude-code ENV PATH="/root/.local/bin:${PATH}" -RUN poe-code install claude-code \ - && poe-code install codex \ +RUN poe-code install codex \ && poe-code install opencode \ - && poe-code install kimi \ - && poe-code install goose + && poe-code install kimi diff --git a/.poe-code/config.json b/.poe-code/config.json index c859cf514a..9e872f1f1e 100644 --- a/.poe-code/config.json +++ b/.poe-code/config.json @@ -1,9 +1,5 @@ { "ralph": { "plan_directory": "docs/plans" - }, - "runtime": { - "memory_mb": 8192, - "cpu": 4 } } From da4753393879066dea25c134dc1462a81cec0910 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 22:13:07 -0500 Subject: [PATCH 037/111] feat(runtime): support extending an e2b base template via from_template E2B's Dockerfile FROM line resolves as a Docker image, so a Dockerfile that says FROM e2b/claude-code 404s. The SDK does expose Template().fromTemplate(alias) for extending an existing e2b template, but it can't be combined with fromDockerfile through the public API surface. Adds runtime.from_template to E2bRuntime config. When set, the runner parses the project's Dockerfile as before (so RUN/ENV instructions are preserved) and then casts the builder to TemplateBase to chain fromTemplate, which voids baseImage and swaps in the alias as the actual base. The Dockerfile's FROM line becomes a documentation hint - any value still parses, but the alias from config wins. --- packages/poe-code-config/src/runtime.ts | 7 +++++++ packages/runner-e2b/src/sdk.ts | 6 +++++- packages/runner-e2b/src/template-build.ts | 1 + 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/packages/poe-code-config/src/runtime.ts b/packages/poe-code-config/src/runtime.ts index 9a4d37d488..6ec3ab9c57 100644 --- a/packages/poe-code-config/src/runtime.ts +++ b/packages/poe-code-config/src/runtime.ts @@ -40,6 +40,7 @@ export interface DockerRuntime extends SharedRuntimeFields { export interface E2bRuntime extends SharedRuntimeFields { type: "e2b"; template_id?: string; + from_template?: string; dockerfile?: string; build_context?: string; cpu?: number; @@ -136,6 +137,11 @@ export const runtimeConfigScope = { default: "", doc: "Prebuilt E2B template id" }, + from_template: { + type: "string", + default: "", + doc: "Existing E2B template alias to extend instead of using the Dockerfile FROM image" + }, cpu: { type: "json", default: undefined as number | undefined, @@ -224,6 +230,7 @@ export function parseRuntime(raw: unknown): RuntimeConfig { ...shared, type, template_id: parseOptionalString(record.template_id), + from_template: parseOptionalString(record.from_template), dockerfile: parseOptionalString(record.dockerfile), build_context: parseOptionalString(record.build_context), cpu: parseOptionalNumber(record.cpu), diff --git a/packages/runner-e2b/src/sdk.ts b/packages/runner-e2b/src/sdk.ts index 5af2f440bb..28aab2d90b 100644 --- a/packages/runner-e2b/src/sdk.ts +++ b/packages/runner-e2b/src/sdk.ts @@ -1,4 +1,4 @@ -import { Template, Sandbox } from "e2b"; +import { Template, Sandbox, TemplateBase } from "e2b"; import type { Readable } from "node:stream"; export interface E2bSandbox { @@ -93,6 +93,7 @@ export interface BuildTemplateOptions { buildContext: string; cpu?: number; memoryMb?: number; + fromTemplate?: string; onLog?: (entry: BuildLogEntry) => void; } @@ -126,6 +127,9 @@ export async function buildTemplate(opts: BuildTemplateOptions): Promise 0) { + (template as TemplateBase).fromTemplate(opts.fromTemplate); + } const result = await Template.build(template, opts.name, { apiKey: opts.apiKey, ...(opts.cpu === undefined ? {} : { cpuCount: opts.cpu }), diff --git a/packages/runner-e2b/src/template-build.ts b/packages/runner-e2b/src/template-build.ts index 22e79007d8..1bb04118f8 100644 --- a/packages/runner-e2b/src/template-build.ts +++ b/packages/runner-e2b/src/template-build.ts @@ -53,6 +53,7 @@ export async function buildE2bRuntimeTemplate( buildContext: input.buildContext, cpu: input.runtime.cpu, memoryMb: input.runtime.memory_mb, + fromTemplate: input.runtime.from_template, onLog }); } catch (error) { From 1362a9ec320ee970692dc8d650ab5842a99fb999 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 22:13:15 -0500 Subject: [PATCH 038/111] chore: switch project sandbox to extend e2b/claude-code Layers poe-code, codex, and opencode on top of e2b's claude-code base instead of building claude from scratch on a slim node image. Drops kimi/python/uv since we are not using kimi for now, and drops the in-build configure step - configure needs an authenticated provider, which is not available at build time. Configure runs at sandbox spawn time instead. --- .poe-code/Dockerfile | 13 ++++--------- .poe-code/config.json | 3 +++ 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/.poe-code/Dockerfile b/.poe-code/Dockerfile index 2ceca32ae8..36147d66ab 100644 --- a/.poe-code/Dockerfile +++ b/.poe-code/Dockerfile @@ -1,15 +1,10 @@ -FROM node:22-bookworm-slim +FROM e2b/claude-code RUN apt-get update \ - && apt-get install -y --no-install-recommends git ca-certificates curl python3 python3-venv \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ && rm -rf /var/lib/apt/lists/* -ENV UV_INSTALL_DIR=/usr/local/bin -RUN curl -LsSf https://astral.sh/uv/install.sh | sh +RUN npm i -g poe-code -RUN npm i -g poe-code @anthropic-ai/claude-code - -ENV PATH="/root/.local/bin:${PATH}" RUN poe-code install codex \ - && poe-code install opencode \ - && poe-code install kimi + && poe-code install opencode diff --git a/.poe-code/config.json b/.poe-code/config.json index 9e872f1f1e..3322083c0e 100644 --- a/.poe-code/config.json +++ b/.poe-code/config.json @@ -1,5 +1,8 @@ { "ralph": { "plan_directory": "docs/plans" + }, + "runtime": { + "from_template": "e2b/claude-code" } } From 3e495aeed7ccb61eb9de1fde4fa35525a6ea6f2f Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 22:38:07 -0500 Subject: [PATCH 039/111] docs(agents): add 700ms spinner guideline --- AGENTS.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 4f37a7af24..136c58d0de 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -131,6 +131,8 @@ However, it is imperative that all configuration can be done also via cli args Defaults are only accepted when --yes +Any action that theoretically takes longer than 700ms, shold use spinner, use your judgement, this is a soft guideline. + ### Example `$ poe-code configure` From bc7d04abffecea7f552744d31ef5d5fc1ba47fa3 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 22:38:19 -0500 Subject: [PATCH 040/111] docs(agent-script): document supported globals --- packages/agent-script/README.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/packages/agent-script/README.md b/packages/agent-script/README.md index 084338baee..4b7563a82b 100644 --- a/packages/agent-script/README.md +++ b/packages/agent-script/README.md @@ -81,6 +81,26 @@ Embed agent-script in your own product when you want to let users (or models) wr | **Budgets** | `maxSteps`, `deadline`, `maxCallDepth`, `stringLength`, `arrayLength` | | **Cancellation** | `AbortSignal`, observed at every host call and yield point | +## Supported globals + +These are pre-bound in every script — you don't need to import them. + +- **`Promise.all(values)`** — wait for every promise; rejects on the first rejection +- **`Promise.race(values)`** — settle with the first promise to settle, fulfilled or rejected +- **`Promise.allSettled(values)`** — never rejects; resolves to `{ status, value | reason }` entries +- **`Promise.any(values)`** — resolves with the first fulfillment; rejects with `AggregateError` only if all reject +- **`Math`** — `abs`, `ceil`, `exp`, `floor`, `log`, `max`, `min`, `pow`, `round`, `sign`, `sqrt`, `trunc`, plus `E`, `PI`, and `random` (only when `randomSeed` is set) +- **`Object`** — `keys`, `values`, `entries`, `fromEntries`, `assign`, `freeze` +- **`Array`** — `isArray`, `from`, `of` +- **`JSON`** — `parse`, `stringify` (replacer must be `null`/`undefined`; indent must be number/string/undefined) +- **`console`** — `log`, `error` (routed to the `sink` you pass to `run()`) +- **`Error`, `TypeError`** — callable factories, e.g. `throw Error("…")`. `new` is forbidden; the factory call is the supported form. +- **`String`, `Number`, `Boolean`** — value coercion factories, e.g. `String(value)` + +What is **not** available as a global: `Promise` constructor, `Date`, `RegExp`, `Map`, `Set`, `WeakMap`, `WeakSet`, `Symbol`, `BigInt`, `Reflect`, `Proxy`, `globalThis`, `setTimeout`, `setInterval`, `fetch`, `URL`, and the other `*Error` constructors (`RangeError`, `SyntaxError`, `ReferenceError`). Expose a host module if you need any of them. + +Method coverage on plain values follows ECMAScript with a few removals: `String#split` / `replace` / `replaceAll` reject regex separators and function replacers, and `Array#sort` only accepts an arrow comparator returning a number. See `src/interp/methods/` for the full list. + ## Built-in host modules Registered by the caller via the factory functions exported from the package. None of them are auto-installed — you choose which to wire up per run. From 6a7663ae07369aa9df406e2e37ec6797be4a12a3 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 22:38:34 -0500 Subject: [PATCH 041/111] fix(harness-tools): preserve raw runtime scope for override re-parse When --runtime overrides change the runtime type, re-parse from the raw merged scope instead of the already-typed config so type-specific fields survive the type switch. Adds the e2b dep and a plan for the remaining runner-e2b spawn fixes; removes a stale plan lock left from a dead pid. --- docs/plans/e2b-integration.md.lock | 1 - docs/plans/e2b-runtime-spawn-fixes.md | 233 ++++++++++++++++++ package-lock.json | 1 + package.json | 11 +- .../src/poe-command-execution.ts | 22 +- 5 files changed, 257 insertions(+), 11 deletions(-) delete mode 100644 docs/plans/e2b-integration.md.lock create mode 100644 docs/plans/e2b-runtime-spawn-fixes.md diff --git a/docs/plans/e2b-integration.md.lock b/docs/plans/e2b-integration.md.lock deleted file mode 100644 index d58dbbac0d..0000000000 --- a/docs/plans/e2b-integration.md.lock +++ /dev/null @@ -1 +0,0 @@ -{"pid":82216,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T00:58:24.965Z"} \ No newline at end of file diff --git a/docs/plans/e2b-runtime-spawn-fixes.md b/docs/plans/e2b-runtime-spawn-fixes.md new file mode 100644 index 0000000000..60b004cc7a --- /dev/null +++ b/docs/plans/e2b-runtime-spawn-fixes.md @@ -0,0 +1,233 @@ +--- +$schema: https://poe-platform.github.io/poe-code/schemas/plans/pipeline.schema.json +kind: pipeline +version: 1 + +tasks: + - id: sandbox-local-workspace-path + title: Upload workspace to a sandbox-local path, not the host cwd + prompt: | + In packages/runner-e2b/src/opened-env.ts, the workspace upload uses + input.spec.cwd (the host's cwd, e.g. /Users/kjopek/Workspace/poe-code) + as the destination directory inside the sandbox. For bases that + run as a non-root user (like e2b/claude-code) this fails with a + permission error on `mkdir -p /Users/...`, and even where it + succeeds it bakes the host's path layout into every sandbox. + + Introduce a sandbox-local destination - default to /workspace - + and translate paths so: + - uploadWorkspace tars from input.spec.cwd on the host but + extracts to the sandbox path inside the sandbox. + - downloadWorkspace mirrors the same translation in reverse. + - exec(spec) runs with `cwd` mapped to the sandbox path when + spec.cwd matches the host workspace root, and uses spec.cwd + unchanged for other paths (so callers can still target + absolute sandbox paths directly). + + Make the sandbox path configurable via runtime.workspace_dir on + E2bRuntime (default "/workspace"). Project config / Dockerfile + resolution must keep using the host cwd - only the runtime side + of the boundary changes. + + The integration test in packages/runner-e2b/src/e2b-execution-env.integration.ts + currently hides this bug by using mkdtemp; add an integration + assertion that the sandbox path differs from the host cwd and + uploads still round-trip. + status: + implement: open + test: open + commit: open + + - id: runRemoteOrThrow-error-tail + title: Surface failing command and stderr from runRemoteOrThrow + prompt: | + In packages/runner-e2b/src/opened-env.ts the runRemoteOrThrow + helper does `await sandbox.commands.run(command)` and then + `if ("exitCode" in result && result.exitCode !== 0) throw ...`. + The e2b SDK's CommandHandle.wait throws a CommandExitError for + any non-zero exit before the helper sees a result, so the + `exitCode !== 0` branch is unreachable and users get the bare + "exit status 1" with no command and no stderr. + + Wrap the call so we always capture stdout and stderr (via the + onStdout/onStderr callbacks the e2b SDK exposes), catch the + CommandExitError thrown by .wait(), and rethrow a new Error + whose message includes the failing command and a trailing tail + of stderr (matching the pattern used by + packages/runner-e2b/src/template-build.ts's decorateBuildError). + Cap the tail at ~30 lines so we don't dump megabytes. + + Add a unit test that mocks sandbox.commands.run to throw a + CommandExitError and asserts the rethrown message contains the + command and stderr tail. + status: + implement: open + test: open + commit: open + + - id: configure-on-spawn + title: Run poe-code configure inside the sandbox before each spawn + prompt: | + Sandbox images install agents (claude-code, codex, opencode) but + their config files don't route through Poe yet, so spawned agents + hit anthropic.com / openai.com directly. POE_API_KEY is already + propagated to the sandbox env via src/sdk/spawn.ts, so configure + can authenticate non-interactively through hasProviderEnvCredential. + + Add a configure-on-spawn step in packages/runner-e2b (or whichever + runner-side hook fires after sandbox.create and before the agent + exec, e.g. inside opened-env.uploadWorkspace's caller in + packages/agent-harness-tools/src/run-poe-command.ts) that runs: + - First, the provider's binary-exists check from + src/providers/.ts inside the sandbox. This is the + createBinaryExistsCheck call already in each provider file. + - If the binary is present, run `poe-code configure --yes + --provider poe ` inside the sandbox. + - If the binary is missing, skip silently. Do not fail the + spawn just because the image lacks an unrelated agent. + + Configure must be idempotent end-to-end: a second spawn of the + same agent in a paused/restarted sandbox should be a no-op (no + mutations reported by configure-payload). If today's configure + always rewrites the file, add a `--skip-if-configured` shortcut + that compares the current config payload to what configure + would emit and exits zero before any write. + + Test with a real sandbox spawning claude-code through e2b and + asserting the agent talks to api.poe.com (e.g. via + `claude --version` followed by a one-shot prompt that succeeds). + status: + implement: open + test: open + commit: open + + - id: e2b-spawn-end-to-end + title: Make `spawn --runtime e2b` work end-to-end on a tmp workspace + prompt: | + With tasks 1-3 landed, wire and verify the spawn-through-e2b + path against a real e2b sandbox. The previous three tasks are + the structural fixes; this task is the integration glue and + the verification. + + Test workspace must be a fresh tmpdir, not the poe-code repo + itself - downloadWorkspace syncs sandbox files back, and + polluting the monorepo on every spawn run is unacceptable. + Create the workspace with `mkdtemp` and seed it with exactly + two files: README.md (one paragraph) and hello.txt (one line). + The agent's prompt should ask it to read hello.txt and reply + with one short sentence - small enough that any post-run sync + back into the tmpdir is trivial to inspect, and the tmpdir is + removed in a finally block regardless of success or failure. + + Acceptance commands, all green from a clean state: + npm run dev -- runtime build --runtime e2b + npm run dev -- --yes spawn claude-code "read hello.txt and \ + summarize in one sentence" --runtime e2b --cwd + + The spawn must: + - Reach the sandbox without permission errors on the upload. + - Auto-configure claude-code inside the sandbox via task 3. + - Hit api.poe.com (verifiable via the request log or a + throwaway POE_API_KEY tied to a fresh account). + - Return non-empty stdout with exit code 0. + - Write nothing back to the poe-code repo. + + Add a vitest integration test that drives the same flow but + against a captured-sandbox fake when E2B_API_KEY is unset, so + CI exercises the wiring even without real e2b access. + status: + implement: open + test: open + commit: open + + - id: e2b-ralph-end-to-end + title: Make `ralph run --runtime e2b` work end-to-end on a fake plan + prompt: | + Once basic spawn through e2b works (previous task), verify the + ralph iteration loop on top of it. + + Use the same tmpdir discipline as the spawn task: mkdtemp, two + files, finally-cleanup. The plan is a one-task ralph markdown + doc whose prompt is intentionally trivial - e.g. "Append the + current iteration number to ITERATIONS.txt and stop after 2 + iterations". This keeps the test cheap (one model call per + iteration) and the diff inspectable. + + Acceptance commands, all green from a clean state: + npm run dev -- ralph init /plan.md \ + --agent claude-code --iterations 2 + npm run dev -- --yes ralph run /plan.md \ + --runtime e2b --cwd + + The run must: + - Open one e2b sandbox, reuse it across both iterations. + - Sync the workspace back between iterations so ralph sees + ITERATIONS.txt grow. + - Stop after 2 iterations as configured. + - Leave the poe-code repo untouched (writes only to tmpdir). + + Document the tmpdir-or-bust rule in + packages/ralph/README.md so future contributors don't aim + ralph at the parent repo. + status: + implement: open + test: open + commit: open + + - id: runner-sync-flag + title: Add a --runner-sync flag to control workspace upload/download + prompt: | + Today every non-host runtime spawn implicitly does an upload on + open and a download on close, with conflict resolution governed + by runtime.runner.download_conflict in config. There is no way + to opt out of either side without editing config, which means + casual experiments either pollute the host workspace via + sync-back or force users to mkdtemp every test. + + Add a CLI option to packages/agent-spawn (and the runtime + command group) with the working name --runner-sync, exposing + one of these modes: + - both (default; current behavior, upload + download) + - upload (upload host workspace into the sandbox, skip the + sync-back so sandbox writes never touch the host) + - none (skip upload and download; the sandbox runs against + whatever the image already contains) + + Wire it as an override over runtime.runner in + packages/poe-code-config/src/runtime.ts (add a new + runner.sync field with the same enum), thread it through + addRuntimeOptions / pickRuntimeOptions in + src/cli/commands/runtime-options.ts, and have + packages/runner-e2b/src/opened-env.ts honor it in + uploadWorkspace / downloadWorkspace (early-return when the + mode says skip). + + Tasks 4 and 5 (spawn / ralph end-to-end) get noticeably + simpler with --runner-sync none: no mkdtemp, no finally + cleanup, just run against an ephemeral sandbox. Update those + tasks' acceptance commands to use --runner-sync none for the + smoke-test variants, while keeping a separate "with sync" + assertion that verifies download still works when requested. + status: + implement: open + test: open + commit: open +--- + +# Context + +Tested e2b spawn end-to-end against the new `e2b/claude-code`-based template (`mxyf0ooulpfwdzo14x64`) and uncovered four blockers. Items 1 and 2 from the original list collapse into a single task because they share a root cause (host `cwd` leaking into the sandbox path). Items 3 and 4 are independent and surfaced once 1+2 were diagnosed. + +## Why now + +`spawn --runtime e2b` looks like the headline feature, but it has never worked outside the integration test, which dodges issue 1 by using `mkdtemp`. Until these are fixed, the only paths exercised in real use are `runtime build`, `runtime templates ls`, and host-runtime spawns. + +## Out of scope + +- Per-sandbox memory/cpu overrides (tied to e2b's template-level memoryMB; separate redesign). +- Workspace exclusion glob extensions for the build context walker (existing default exclusions are sufficient for the spawn-time upload). +- Reintroducing goose / kimi to the sandbox image. + +## Acceptance + +`POE_API_KEY=… npm run dev -- spawn claude-code "say hi" --runtime e2b` returns a Poe-routed response with no error log entries, on a fresh checkout where the e2b template was built but no spawn has run before. diff --git a/package-lock.json b/package-lock.json index e34785c69d..3e97f21b0e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -16,6 +16,7 @@ "commander": "^14.0.3", "console-table-printer": "^2.15.0", "diff": ">=8.0.3", + "e2b": "^2.19.4", "fast-glob": "^3.3.3", "gray-matter": "^4.0.3", "jose": "^6.1.3", diff --git a/package.json b/package.json index 5223e36710..1af5fb3d9a 100644 --- a/package.json +++ b/package.json @@ -107,6 +107,7 @@ "commander": "^14.0.3", "console-table-printer": "^2.15.0", "diff": ">=8.0.3", + "e2b": "^2.19.4", "fast-glob": "^3.3.3", "gray-matter": "^4.0.3", "jose": "^6.1.3", @@ -160,30 +161,30 @@ "@types/node": "^25.2.2", "@types/semver": "^7.7.1", "@vitest/coverage-v8": "^4.1.4", - "toolcraft": "*", - "toolcraft-openapi": "*", - "toolcraft-schema": "*", "auth-store": "*", "bats": "^1.13.0", "eslint": "^9.0.0", "eslint-config-prettier": "^10.1.8", "globals": "^17.3.0", "husky": "^9.1.7", - "memfs": "^4.56.10", "mcp-oauth": "*", + "memfs": "^4.56.10", "opencode-poe-auth": "*", "poe-oauth": "*", "prettier": "^3.8.1", "terminal-pilot": "*", "terminal-pilot-mcp": "*", "terminal-png": "*", - "tiny-http-mcp-server": "*", "tiny-http-mcp-oauth-test-server": "*", + "tiny-http-mcp-server": "*", "tiny-mcp-client": "*", "tiny-oauth-test-server": "*", "tiny-stdio-mcp-server": "*", "tiny-stdio-mcp-test-server": "*", "tokenfill": "*", + "toolcraft": "*", + "toolcraft-openapi": "*", + "toolcraft-schema": "*", "ts-morph": "^27.0.2", "tsx": ">=4.21.0", "turbo": "^2.8.3", diff --git a/packages/agent-harness-tools/src/poe-command-execution.ts b/packages/agent-harness-tools/src/poe-command-execution.ts index e457c20059..4c7aee8884 100644 --- a/packages/agent-harness-tools/src/poe-command-execution.ts +++ b/packages/agent-harness-tools/src/poe-command-execution.ts @@ -43,7 +43,8 @@ export function resolvePoeCommandExecution(input: { state: StateManager; } { const homeDir = input.context?.homeDir ?? os.homedir(); - const config = applyRuntimeOverrides(loadRuntimeConfig(input.cwd, homeDir), input.runtime, input.cwd); + const loaded = loadRuntimeConfig(input.cwd, homeDir); + const config = applyRuntimeOverrides(loaded, input.runtime, input.cwd); const resolved = resolveRuntime({ cwd: input.cwd, config }); const factory = selectExecutionEnv(resolved.runtime); const state = input.context?.state ?? loadState(homeDir); @@ -68,17 +69,27 @@ export function resolvePoeCommandExecution(input: { }; } +export interface LoadedRuntimeConfig extends ResolvedConfig { + /** Raw merged runtime scope preserved for re-parsing when overrides change the type. */ + rawScope: Record; +} + export function applyRuntimeOverrides( - config: ResolvedConfig, + config: ResolvedConfig | LoadedRuntimeConfig, overrides: RuntimeOverrideOptions | undefined, cwd = process.cwd() ): ResolvedConfig { if (!overrides) { - return config; + return { runtime: config.runtime, runner: config.runner }; } + const base: Record = + "rawScope" in config && config.rawScope + ? { ...config.rawScope } + : { ...(config.runtime as unknown as Record) }; + const runtime = parseRuntime({ - ...config.runtime, + ...base, ...(overrides.runtime !== undefined ? { type: overrides.runtime } : {}), ...(overrides.runtimeImage !== undefined ? { image: overrides.runtimeImage } : {}), ...(overrides.runtimeTemplate !== undefined @@ -106,7 +117,7 @@ function createPoeCodeMount(cwd: string): { source: string; target: string; read }; } -function loadRuntimeConfig(cwd: string, homeDir: string): ResolvedConfig { +function loadRuntimeConfig(cwd: string, homeDir: string): LoadedRuntimeConfig { const document = deepMergeDocuments( readConfigDocument(resolveConfigPath(homeDir)), readConfigDocument(resolveProjectConfigPath(cwd)) @@ -114,6 +125,7 @@ function loadRuntimeConfig(cwd: string, homeDir: string): ResolvedConfig { const runtimeScope = resolveScope(runtimeConfigScope.schema, document.runtime, process.env); return { + rawScope: { ...(runtimeScope as unknown as Record) }, runtime: parseRuntime(runtimeScope), runner: runtimeScope.runner }; From 017fb8f05836ed27ad83403013f24f3c526284df Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 22:38:48 -0500 Subject: [PATCH 042/111] docs(plans): add harness/approval/toolcraft planning docs - harness-plans-via-task-list: unify per-harness plan discovery on a single @poe-code/task-list markdown-dir - human-in-loop-approval-windows: time-bounded approval grants (once, 1h, today) with a CLI for listing/revoking - toolcraft-help-and-result-rendering: width-aware column formatter and shared toolcraft help/result rendering --- docs/plans/harness-plans-via-task-list.md | 136 ++++ docs/plans/human-in-loop-approval-windows.md | 586 ++++++++++++++ .../toolcraft-help-and-result-rendering.md | 725 ++++++++++++++++++ 3 files changed, 1447 insertions(+) create mode 100644 docs/plans/harness-plans-via-task-list.md create mode 100644 docs/plans/human-in-loop-approval-windows.md create mode 100644 docs/plans/toolcraft-help-and-result-rendering.md diff --git a/docs/plans/harness-plans-via-task-list.md b/docs/plans/harness-plans-via-task-list.md new file mode 100644 index 0000000000..3d241f2f5e --- /dev/null +++ b/docs/plans/harness-plans-via-task-list.md @@ -0,0 +1,136 @@ +--- +$schema: https://poe-platform.github.io/poe-code/schemas/plans/plan.schema.json +kind: plan +version: 1 +--- + +# Harness plans via task-list + +Replace the per-harness plan discovery + archive code with a single `@poe-code/task-list` `markdown-dir` task list, shared by experiment, ralph, pipeline, and superintendent. + +## 1. What we're building + +Switch every harness — experiment-loop, ralph, pipeline, superintendent — off its bespoke plan discovery and archive logic, onto one shared `@poe-code/task-list` `markdown-dir` task list. Plan files in the configured plan directory (e.g. `docs/plans/`, `.poe-code/ralph/plans/`) are tasks. The harness opens the task list and asks it for the active set, the plan to run, and the archive operation. Archive is the `archive` event on the task lifecycle: the abstraction moves the file under `archive/`, drops its order prefix, and re-packs the prefixes of the remaining active plans so there are no gaps. No harness owns archive logic anymore. + +Non-goals: + +- Changing plan markdown content or per-harness frontmatter (`kind: pipeline | ralph | superintendent | experiment`). +- Replacing the harness-specific plan parsers (`parsePlan` in pipeline, `parseSuperintendentDoc`, etc.) — those still operate on the file body. +- Changing the storage location for plans (each harness keeps its current default plan directory). +- Adding the `gh-issues` backend or yaml-file backend to harness plan discovery — `markdown-dir` only. +- Migrating the `task-list-ordering-and-gh-issues.md` work; that pipeline runs independently. + +## 2. User-facing shape + +### Shared discovery API in `@poe-code/agent-harness-tools` + +A single new export that every harness consumes. It opens a `task-list` `markdown-dir` over the plan directory, lists active tasks, and (optionally) filters by `kind`. + +```ts +import { discoverPlans, archivePlan, openPlanList } from "@poe-code/agent-harness-tools"; + +// Discovery — replaces three near-identical discovery files. +const plans = await discoverPlans({ + cwd, + homeDir, + planDirectory: "docs/plans", // optional; default per harness + kinds: ["pipeline"], // optional; filters Task.metadata.kind +}); + +// plans: Array<{ id: string; absolutePath: string; displayPath: string; kind: string }> + +// Archive after a successful run — replaces per-harness archivePlan() helpers. +await archivePlan({ cwd, homeDir, planDirectory: "docs/plans", id: "agent-harness" }); +// → moves NN-agent-harness.md to archive/agent-harness.md +// → renumbers every remaining NN-*.md so prefixes are gap-free + +// Lower-level handle if a harness needs more (rare). +const list = await openPlanList({ cwd, homeDir, planDirectory: "docs/plans" }); +``` + +`kinds` is matched against `Task.metadata.kind`, which the backend reads from each plan's existing YAML frontmatter (`kind: pipeline | ralph | superintendent | experiment | plan`). No frontmatter changes; the backend already round-trips unknown frontmatter into `metadata`. + +### Harness call sites — before / after + +Pipeline today (`packages/pipeline/src/run/pipeline.ts`): + +```ts +// before +async function archivePlan(fs: PipelineFileSystem, absolutePlanPath: string): Promise { + const dir = path.dirname(absolutePlanPath); + const archiveDir = path.join(dir, "archive"); + const archivePath = path.join(archiveDir, path.basename(absolutePlanPath)); + await fs.mkdir(archiveDir, { recursive: true }); + await fs.rename(absolutePlanPath, archivePath); +} +// after +import { archivePlan } from "@poe-code/agent-harness-tools"; +await archivePlan({ cwd, homeDir, planDirectory, id: planId }); +``` + +Ralph + experiment-loop drop their entire `discovery/discovery.ts` and replace internal calls to their local `archivePlan` with the same shared call. + +Superintendent uses `discoverPlans({ kinds: ["superintendent"] })` in place of its own scan; archive is unchanged for now (superintendent does not currently archive on completion — it stays out of scope until that flow exists). + +### Plan filenames + +Existing plans get a one-time renumber on this branch: + +```text +docs/plans/ + 01-agent-harness.md + 02-agent-human-in-loop.md + 03-braintrust-integration.md + ... + archive/ + cmdkit-openapi.md + ... +``` + +Order is alphabetical-by-id at migration time; subsequent reorders go through `Tasks.move`/`reorder`. The id is the filename stem with the `NN-` stripped — same as the backend already enforces. + +### Archive behavior change + +`fire(id, "archive")` (and the `task-list-driven archivePlan` wrapper) now repacks the remaining active tasks' prefixes after moving the archived file: + +```text +before: after fire("02-bar", "archive"): + 01-foo.md 01-foo.md + 02-bar.md 02-baz.md ← was 03 + 03-baz.md archive/bar.md +``` + +Default-on for every consumer of `markdown-dir`. The current behavior left dangling prefixes; that's a bug rather than a feature. + +### `markdown-dir` flat-root mode + +Plans live directly in the directory (`docs/plans/foo.md`), not under a list subdir (`docs/plans//foo.md`). The backend gains a single new option: + +```ts +openTaskList({ + type: "markdown-dir", + path: "docs/plans", + singleList: "plans" // ← new; root IS the list +}); +``` + +Behavior with `singleList`: + +- `lists()` returns `[singleList]`. +- `list(name)` requires `name === singleList` (any other throws). +- Active tasks live at `/*.md` / `/NN-*.md`. +- Archived tasks live at `/archive/*.md`. +- `moveBetweenLists` throws — single list. + +Without `singleList` the backend behaves exactly as today. + +### Plan-directory defaults + +Each harness keeps its own default plan directory: + +| Harness | Default `planDirectory` | `kinds` filter | +| --- | --- | --- | +| pipeline | `docs/plans` | `["pipeline"]` | +| ralph | `.poe-code/ralph/plans` | `["ralph"]` | +| experiment-loop | `.poe-code/experiments` | `["experiment"]` | +| superintendent | `docs/plans` | `["superintendent"]` | diff --git a/docs/plans/human-in-loop-approval-windows.md b/docs/plans/human-in-loop-approval-windows.md new file mode 100644 index 0000000000..71d73f53a5 --- /dev/null +++ b/docs/plans/human-in-loop-approval-windows.md @@ -0,0 +1,586 @@ +--- +$schema: https://poe-platform.github.io/poe-code/schemas/plans/plan.schema.json +kind: plan +version: 1 +--- + +# Human-in-loop approval windows + +Let a human grant an approval that persists for a time window ("allow for 1h", "allow for today"), so subsequent matching requests auto-approve until the window expires. + +## 1. What we're building + +Today, every gated call to `requestApproval` pops a dialog and asks again — even if the human just approved the identical thing 30 seconds ago. For overnight detached runs and long agentic loops this is the wrong shape: the human wants to grant a window of trust ("yes, this kind of action is fine for the next hour / for the rest of today") and walk away. + +Add time-bounded approvals to the human-in-loop stack: + +- The osascript dialog grows beyond Approve/Decline. On approval, the user picks a window: **Once**, **1 hour**, or **Today** (until local-midnight). +- A persistent grant store lives between calls. When a `requestApproval` arrives, the runtime checks the store first; on a live grant for the same key, the call resolves `{ outcome: "approved" }` without prompting. +- Async-mode (`toolcraft` queued approvals) honors live grants too — enqueue + spawn is skipped when the grant is already there, the call returns immediately as approved. +- The CLI gains `approvals grants list` / `approvals grants revoke ` so the human can see and tear down active windows. + +Non-goals: + +- Per-parameter approval rules ("approve `rm` only on `/tmp`"). Grants key on the call site (command path + a caller-chosen scope), not on parameter shape. +- Pluggable window menus per provider. The window set is fixed in v1: `once`, `1h`, `today`. New windows are a follow-up, not a config surface. +- Persistence across machines / shared stores. Grants are local to one machine, one user. +- Decline windows ("decline-for-today"). Decline stays one-shot. +- Provider branching (`if (provider.id === "osascript")`). Window selection is part of the `ApprovalResult` contract, providers without a UI for it return `window: "once"`. + +## 2. User-facing shape + +### API: `requestApproval` gains `grantKey` + `window` + +The primitive grows two contract changes. Everything else is unchanged. + +```ts +import { requestApproval, osascriptProvider } from "@poe-code/agent-human-in-loop"; + +const provider = osascriptProvider({ title: "poe-code" }); + +const result = await requestApproval({ + message: "Run `rm -rf /tmp/foo`?", + grantKey: "tools.fs.delete", // command path; omit for one-off prompts + provider, +}); + +// result.outcome === "approved" → result.window: "once" | "1h" | "today" +// result.outcome === "approved" → result.grantHit: true when served from store +// result.outcome === "declined" → unchanged ({ outcome, reason? }) +``` + +`grantKey` is the only thing keying the cache. It is opaque to the package — the caller (toolcraft) passes a command path. Identical `grantKey` strings share a window; different strings do not. + +When `grantKey` is omitted, the call is a one-off: no store lookup, no store write, dialog every time. Existing callers that don't pass `grantKey` keep their current behavior bit-for-bit. + +### Dialog + +One `choose from list` dialog, single click for any path. + +```text +┌─ Approval needed ────────────────────────────────────┐ +│ Run `rm -rf /tmp/foo`? │ +│ │ +│ ◉ Approve once │ +│ ○ Allow for 1 hour │ +│ ○ Allow for today │ +│ │ +│ [ Decline ] [ Confirm ] │ +└──────────────────────────────────────────────────────┘ +``` + +- Default selection is **Approve once**. +- **Confirm** → approval, with the chosen window. +- **Decline** → declined, no reason. The decline-with-reason two-stage flow (existing) still applies when `declineInputPrompt` is set: cancel-button click triggers the second dialog before resolving. +- **Esc** / window close → declined (osascript returns -128, mapped to `{ outcome: "declined" }`). + +### Window semantics + +| Window | Meaning | +| ------- | --------------------------------------------------------------- | +| `once` | No grant written. Next call re-prompts. | +| `1h` | Grant valid for 60 minutes from approval timestamp. | +| `today` | Grant valid until next local midnight (user's system timezone). | + +### Toolcraft integration + +Command authors do not change anything. The existing `humanInLoop` config keeps the same fields: + +```ts +defineCommand({ + name: "delete", + humanInLoop: { + mode: "sync", + message: ({ params }) => `Delete ${params.path}?`, + }, + // ... +}); +``` + +Toolcraft computes `grantKey` from the command path internally (`"tools.fs.delete"`) and threads it through `provider.requestApproval`. Grant lookup happens inside `agent-human-in-loop`; toolcraft does not see the store. + +### Async mode (queued approvals) + +Async-mode gating short-circuits when a grant is live for the command path: + +- **Grant live** → no task is enqueued; the handler runs immediately and returns its real result, not `HumanInLoopPending`. +- **Grant absent** → existing behavior: task enqueued, runner spawned, caller receives `{ status: "pending-approval", approvalId, ... }`. +- When the runner resolves an enqueued approval through the dialog and the user picks `1h` or `today`, the grant is written before the handler fires. Subsequent async-mode calls within the window also short-circuit. + +### CLI: `approvals grants` + +Two new subcommands under the existing `approvals` built-in group. + +```text +$ poe-code approvals grants list + +ID COMMAND PATH WINDOW GRANTED EXPIRES +g_3a9f2c tools.fs.delete 1h 2026-05-03 14:02:11 2026-05-03 15:02:11 +g_88ad10 tools.shell.run today 2026-05-03 09:18:44 2026-05-04 00:00:00 +``` + +```text +$ poe-code approvals grants revoke g_3a9f2c + +Revoked grant g_3a9f2c (tools.fs.delete). +``` + +```text +$ poe-code approvals grants list --json +[ + { "id": "g_3a9f2c", "commandPath": "tools.fs.delete", "window": "1h", + "grantedAt": "2026-05-03T14:02:11Z", "expiresAt": "2026-05-03T15:02:11Z" } +] +``` + +`list` filters out expired entries on read and writes the cleaned file back. `revoke` errors with `UserError("no grant with id ")` if the id is unknown or already expired. + +### Grant store location + +`$XDG_DATA_HOME/poe-code/grants.json` if `XDG_DATA_HOME` is set, otherwise `~/.poe-code/grants.json`. File created lazily on first write. File format is internal — not a contract — but illustratively: + +```json +{ + "schemaVersion": 1, + "grants": [ + { "id": "g_3a9f2c", "commandPath": "tools.fs.delete", "window": "1h", + "grantedAt": "2026-05-03T14:02:11Z", "expiresAt": "2026-05-03T15:02:11Z" } + ] +} +``` + +Concurrent writers serialize through `@poe-code/file-lock`. + +### Errors the user sees + +- Grants file unreadable / malformed → `UserError("grants file at is malformed; remove it to reset")`. We do not silently rewrite a corrupt file. +- `revoke ` on an unknown / expired id → `UserError("no grant with id ")`. +- Existing osascript errors are unchanged. +- Mock provider unchanged: still returns the scripted `ApprovalResult`. To exercise the window field in tests, set `outcome: "approved", window: "1h"`. + +## 3. Implementation details and technical decisions + +### Architecture + +Two packages change. No new packages. + +```text +packages/agent-human-in-loop/src/ +├── types.ts # ApprovalRequest, ApprovalResult, Grant, Window +├── request-approval.ts # adds grant-check wrapper around provider call +├── grants.ts # NEW — file-backed grant store + helpers +├── providers/ +│ ├── osascript.ts # dialog rebuilt as `choose from list` form +│ ├── osascript-script.ts # buildScript handles 3-window dialog +│ └── mock.ts # unchanged + +packages/toolcraft/src/human-in-loop/ +├── gate.ts # async path checks live grant before enqueue +├── runner.ts # passes grantKey to requestApproval inside the runner +├── approvals-commands.ts # adds `grants` subgroup (list, revoke) +└── types.ts # HumanInLoopRuntimeOptions gains `grants?: boolean` +``` + +### `agent-human-in-loop`: grant-aware `requestApproval` + +The wrapper is the only place that knows about grants. Providers stay UI-only. + +```text +requestApproval({ message, declineInputPrompt, grantKey, provider }) + if grantKey: + grant = findLiveGrant(grantKey) # reads grants.json under file-lock + if grant: return { outcome: "approved", window: grant.window, grantHit: true } + result = provider.requestApproval({ message, declineInputPrompt }) + if grantKey and result.outcome == "approved" and result.window != "once": + saveGrant({ commandPath: grantKey, window: result.window }) # writes grants.json + return result +``` + +`provider.requestApproval` does **not** receive `grantKey`. The grant layer wraps it. Providers that don't render the window picker return `window: "once"`; the wrapper writes nothing in that case, so non-osascript providers keep their existing behavior automatically. + +### Grant store (`grants.ts`) + +Single internal module exposing four functions used by the wrapper, plus two used by the toolcraft CLI commands: + +- `findLiveGrant(grantKey)` — read, sweep expired, return first live grant matching the key. +- `saveGrant({ commandPath, window })` — read, sweep, append, write under file-lock. +- `listGrants()` — read, sweep, write back, return all live grants. +- `revokeGrant(id)` — read, drop the entry, write; throws `UserError` on miss. + +All four go through `@poe-code/file-lock` around `grants.json`. Read-only callers still take the lock to avoid reading a half-written file. + +Grant id: `g_` + 6 hex chars from `randomBytes`. Collisions are checked against the in-memory list before write. + +Expiry on `today`: `new Date()` then increment day, set `00:00:00.000` in local time. Computed at write time and stored as ISO-8601. Local-midnight semantics survive sleep/wake; DST transitions are absorbed because the absolute timestamp is already pinned. + +Sweep-on-read deletes any entry where `expiresAt <= now()`. The cleaned list is written back even on read paths so the file does not grow unbounded. + +### File location resolver + +```text +if process.env.XDG_DATA_HOME: /poe-code/grants.json +else: /.poe-code/grants.json +``` + +A module-level `setGrantsFilePathForTesting(path: string | undefined)` overrides the resolver. Production never calls it. + +### Toolcraft sync path + +Unchanged at the call site. `gate.ts` `invokeWithHumanInLoop` already calls `provider.requestApproval(...)`; it now passes `grantKey: commandPath` through the new `requestApproval` top-level helper instead of calling the provider directly. The grant short-circuit happens inside the helper. + +### Toolcraft async path + +Async-mode gating gets one new step before `enqueueApproval`: + +```text +if humanInLoop.mode == "async": + if runtimeOptions.grants != false: + grant = findLiveGrant(commandPath) + if grant: return node.handler(ctx) # short-circuits to real result + // existing path: enqueue, spawn runner, return pending +``` + +The runner itself (`runner.ts`) now calls the top-level `requestApproval({ ..., grantKey: approval.commandPath })` instead of the bare provider, so a `1h` / `today` window picked while the runner has the dialog open is persisted before the handler fires. + +### Toolcraft runtime option + +`HumanInLoopRuntimeOptions` gains one optional field: + +```ts +grants?: boolean; // default true +``` + +When `false`, toolcraft never passes `grantKey` downstream — every call re-prompts. This is the v1 escape hatch for users who don't want any caching. + +### Default-on, opt-out + +The feature is on by default. No env var, no config flag in `humanInLoop` per command. Per-command exceptions ("never grant for `tools.shell.run`") are not in v1; if needed, they go through `runtimeOptions.grants = false` for the whole runtime, or a future per-command field. + +### `approvals grants` subgroup + +A new `defineGroup` named `grants` is appended to the existing `approvalsGroup` in `approvals-commands.ts`. Only mounted when toolcraft's existing approvals built-in is mounted (i.e. when any command uses `humanInLoop`). Two children: + +- `list` — scope `["cli", "mcp", "sdk"]`. Calls `listGrants()`. +- `revoke` — scope `["cli"]`. Param `{ id: string }`. Calls `revokeGrant(id)`. + +Render hooks mirror the existing `approvals list` / `approvals show` style (rich table, markdown table, json passthrough). + +### Edge cases + +- **Clock moves backward** (NTP correction, manual change). Live grants stay live until their absolute `expiresAt` passes; they never re-expire and re-live. Sweep is monotone with respect to the current `Date.now()` only. +- **Machine sleep across `expiresAt`**. On wake, next `findLiveGrant` sees the past timestamp and sweeps. No timer-based expiry, so sleep is not a concern. +- **Two `requestApproval` calls race for the same `grantKey`**. Both miss the grant, both call the provider, two dialogs stack. Whichever user answer arrives first writes the grant; the second answer also writes (sweep happens before append, so we end up with at most two grants for the same key — both live, both honored on next lookup, and `findLiveGrant` returns the first match). Acceptable for v1; deduplication on save is a one-line follow-up if it bites. +- **Two processes write at once** (overnight detached run + interactive shell). `@poe-code/file-lock` serializes; second writer rebases on the first writer's view. +- **`XDG_DATA_HOME` set but pointing at unwritable dir**. First write throws filesystem error wrapped in `UserError("could not write grants file at : ")`. We do not silently fall back to `~/.poe-code` when XDG is set. +- **Corrupt `grants.json`**. Read throws `UserError("grants file at is malformed; remove it to reset")`. We do not auto-repair. +- **Grants file with a future `schemaVersion`**. Same `UserError` — forward-compat is not a v1 promise; the user is asked to delete it. +- **Provider returns `window` we don't recognize** (e.g. `"forever"`). Wrapper treats unknown windows as `"once"` — no grant written. Defensive against future provider drift. +- **`grantKey` is empty string**. Wrapper treats empty same as missing — no lookup, no write. Caller bug, not our problem to enforce; documented behavior. +- **Mock provider returning `window: "1h"` in a unit test**. With `setGrantsFilePathForTesting` not set, the wrapper writes to the real `~/.poe-code/grants.json`. To prevent test pollution, every test that uses `mockProvider` with an approve outcome **must** call `setGrantsFilePathForTesting()` in its setup. Documented in the package README and asserted by a vitest-level setup file. + +### Env vars and config + +- agent-human-in-loop: still no env vars. README updated to spell that out. +- toolcraft: still no env vars. README documents `runtimeOptions.grants`. + +### Compatibility / migration + +- No breaking changes to public API. `requestApproval`'s `grantKey` is optional; `ApprovalResult` `approved` shape gains optional `window` and `grantHit` fields — existing consumers ignore them. +- No migration of the grants file format until we have one to migrate. `schemaVersion: 1` is the floor. + +## 4. Interfaces and test plan + +### Public types — `agent-human-in-loop` + +```ts +// src/types.ts +export type ApprovalWindow = "once" | "1h" | "today"; + +export interface ApprovalRequest { + message: string; + declineInputPrompt?: string; +} + +export type ApprovalResult = + | { outcome: "approved"; window: ApprovalWindow; grantHit?: true } + | { outcome: "declined"; reason?: string }; + +export interface HumanInLoopProvider { + readonly id: string; + requestApproval(request: ApprovalRequest): Promise; +} + +export interface Grant { + id: string; // "g_" + 6 hex + commandPath: string; // grantKey at write time + window: "1h" | "today"; + grantedAt: string; // ISO-8601 + expiresAt: string; // ISO-8601 +} +``` + +### Public functions — `agent-human-in-loop` + +```ts +// src/request-approval.ts +export function requestApproval( + args: ApprovalRequest & { grantKey?: string; provider: HumanInLoopProvider } +): Promise; + +// src/grants.ts +export function findLiveGrant(grantKey: string): Promise; +export function listGrants(): Promise; +export function revokeGrant(id: string): Promise; +export function setGrantsFilePathForTesting(path: string | undefined): void; + +// src/index.ts re-exports the above plus existing osascriptProvider, mockProvider +``` + +`saveGrant` is internal — only `requestApproval` calls it. + +### Public types — `toolcraft/human-in-loop` + +```ts +// src/human-in-loop/types.ts +export interface HumanInLoopRuntimeOptions { + // ...existing fields... + grants?: boolean; // default true +} +``` + +`Grant` and `ApprovalWindow` re-exported through `src/human-in-loop/index.ts`. + +### Test plan + +#### Unit — `agent-human-in-loop` + +`grants.test.ts`: + +- `findLiveGrant` returns `undefined` on no match. +- `findLiveGrant` returns the live entry, ignoring expired. +- `listGrants` returns all live, in insertion order. +- `listGrants` writes back the cleaned file (expired removed) when sweep runs. +- `revokeGrant` removes one entry; subsequent `findLiveGrant` returns `undefined`. +- `revokeGrant` on unknown id throws `UserError("no grant with id ")`. +- File path resolver: `XDG_DATA_HOME` set → `/poe-code/grants.json`. +- File path resolver: unset → `/.poe-code/grants.json`. +- `setGrantsFilePathForTesting` overrides resolver; clearing it (`undefined`) restores resolver. +- Corrupt JSON → `UserError("grants file at is malformed; remove it to reset")`. +- `schemaVersion` other than 1 → same `UserError`. +- `today` expiry: write at `2026-05-03T14:02:11Z` in TZ where local is UTC-5 → `expiresAt` = next local midnight as ISO. (Inject `Date` via parameter or use vi.setSystemTime + a known TZ; vi.setSystemTime is the right call here.) +- `1h` expiry: `expiresAt - grantedAt === 3600000`. +- Concurrent `saveGrant` from same process: serialized via file-lock; both entries present. + +`grants.race.test.ts` (integration): + +- Spawns two child Node processes. Each calls `saveGrant` with a different `commandPath` 50 times in a loop. After both exit, the file is well-formed JSON, contains 100 entries (or fewer due to expiry, but no half-writes), and `findLiveGrant` for either path resolves to a live entry. + +`request-approval.test.ts`: + +- No `grantKey` → no store IO; provider called every time. +- `grantKey` set, no live grant → provider called; if approved with `window: "1h"`, store now has the entry; if approved with `window: "once"`, store unchanged. +- `grantKey` set, live grant present → provider not called; result is `{ outcome: "approved", window: , grantHit: true }`. +- `grantKey` empty string → treated as missing. +- Provider returns `outcome: "declined"` → no store write, regardless of `grantKey`. +- Provider returns unknown `window` (e.g. `"forever"`) → wrapper returns approved + the unknown window passes through, but no store write. +- All cases use `setGrantsFilePathForTesting()` via vitest setup. + +`providers/osascript-script.test.ts`: + +- `buildScript` snapshot for a representative request — single `choose from list` form with `Approve once`, `Allow for 1 hour`, `Allow for today`, OK="Confirm", cancel="Decline", prompt = message, default item = `Approve once`. +- `buildScript` with `declineInputPrompt` set: emits two-stage AppleScript that runs the chooser first, then the decline-reason dialog if Decline is clicked. Snapshot. +- `parseStdout`: + + - `"Approve once\n"` → `{ outcome: "approved", window: "once" }`. + - `"Allow for 1 hour\n"` → `{ outcome: "approved", window: "1h" }`. + - `"Allow for today\n"` → `{ outcome: "approved", window: "today" }`. + - `"DECLINED\n"` → `{ outcome: "declined" }`. + - `"DECLINED:because\n"` → `{ outcome: "declined", reason: "because" }`. + - unknown → throws. + +- `escapeAppleScriptString` round-trip on quotes and backslashes. + +`providers/osascript.test.ts`: + +- Fake binary returning the new stdout shapes round-trips through the provider with the expected `ApprovalResult`. +- ENOENT → `UserError("osascript not found ...")`. +- Exit code with stderr containing `(-128)` → `{ outcome: "declined" }` (Esc / window close). +- Exit code with unrelated stderr → `UserError("osascript failed: ...")`. + +`providers/mock.test.ts`: + +- Existing cases plus: `mockProvider({ outcome: "approved", window: "1h" })` returns the window verbatim. (No store interaction in the mock — the wrapper does that.) + +#### Vitest setup file + +`packages/agent-human-in-loop/test/setup.ts`: + +- `beforeEach`: create a tmp dir, call `setGrantsFilePathForTesting(/grants.json)`. +- `afterEach`: clear the path (`setGrantsFilePathForTesting(undefined)`), `rm -rf` the tmp dir. + +Wired in `packages/agent-human-in-loop/vitest.config.ts` (created if absent) via `setupFiles: ["./test/setup.ts"]`. The race test opts out by passing its own paths to child processes. + +#### Unit — `toolcraft/human-in-loop` + +`gate.test.ts` (additions): + +- Sync mode, `grants: undefined` (default true) → `requestApproval` is called with `grantKey` = command path. +- Sync mode, `grants: false` → `requestApproval` is called without `grantKey`. +- Async mode, no live grant → existing behavior (enqueue, return pending). +- Async mode, live grant present → handler runs, real result returned, no task created. +- Async mode, `grants: false` → live grant ignored, existing behavior. + +`runner.test.ts` (additions): + +- Runner uses top-level `requestApproval` (not bare provider). When `mockProvider` returns `window: "1h"`, the runner's call writes a grant for the approval's `commandPath`. +- Runner with `grants: false` → no grant written even on `1h`. + +`approvals-grants-commands.test.ts`: + +- `list` with two live grants → returns both in insertion order. +- `list` after one grant expires → returns one; file is rewritten without the expired entry. +- `revoke ` → entry gone; second `revoke` of same id throws. +- `revoke ` → throws `UserError("no grant with id ")`. + +`approvals-commands.test.ts`: regression — existing `approvals list / show / run` still mount and work after the new subgroup is appended. + +#### Integration + +`mcp-runtime.integration.test.ts` / `cli-runtime.integration.test.ts` / `sdk-runtime.integration.test.ts` (additions): for each runtime, one assertion that `humanInLoop` sync command + `mockProvider` returning `window: "1h"` writes a grant; second invocation short-circuits and returns the handler result with no provider call. + +#### Manual QA — `packages/agent-human-in-loop/QA.md` additions + +- Approve once flow: dialog → Confirm with `Approve once` selected → no grant in `grants list`. +- Approve 1h flow: dialog → Confirm with `Allow for 1 hour` → grant appears in `approvals grants list` with `window: 1h`; rerun command → no dialog, returns immediately. +- Approve today flow: same as above with `Allow for today`; expiry shown is next local midnight. +- Decline (button): no grant written. +- Decline (Esc / red dot): no grant written. +- Decline-with-reason: still works when `declineInputPrompt` is set. +- Revoke flow: `approvals grants revoke ` removes grant; next call re-prompts. +- Two parallel agent runs both grant `1h` for the same path: both writes serialize, the file ends well-formed. + +#### Spot test commands + +- `npm run dev -- approvals grants list` (with empty store and after a manual approve-1h). +- `npm run dev -- approvals grants revoke `. +- `npm run screenshot-poe-code -- approvals grants list` (CLI table output check). + +#### Snapshot / screenshot scope + +- `buildScript` snapshots only — AppleScript is text, snapshots are stable. +- CLI table for `approvals grants list`: visual screenshot via `npm run screenshot-poe-code -- approvals grants list`. + +### Rollout + +Purely additive on the `agent-human-in-loop` API (new optional field, new shape on approve). Toolcraft consumers who pass nothing get the default-on behavior: existing apps gain windowed approvals automatically. To preserve the old "always re-prompt" behavior, set `runtimeOptions.grants = false`. + +Single bundled commit covers both packages — no version skew window where toolcraft expects a `grantKey` field that agent-human-in-loop doesn't accept. + +### Autonomy checklist + +The implementing agent must verify before pushing: + +- `grep -r "provider.id ===" packages/agent-human-in-loop/src` → empty. +- `grep -r "execFileSync\|spawnSync" packages/agent-human-in-loop/src` → empty (only async forms). +- All grant store reads and writes are wrapped in `@poe-code/file-lock`. +- `setGrantsFilePathForTesting` is imported only from test files. +- Vitest setup file is wired in `vitest.config.ts`; running the full suite without a real `~/.poe-code/grants.json` does not create one. +- README for `agent-human-in-loop` lists exports, grant store path resolution, env vars (still none), and the test seam. +- README for `toolcraft` documents `runtimeOptions.grants`. +- `package.json` of `agent-human-in-loop` adds one runtime dep: `@poe-code/file-lock`. No others. +- `npm run screenshot-poe-code -- approvals grants list` produces a readable table. +- `npm run lint`, `npm run typecheck`, `npm run test` from root all green. + +## 5. Code plan + +### Files to create + +| File | Purpose | +| --- | --- | +| `packages/agent-human-in-loop/src/grants.ts` | File-backed grant store. Exports `findLiveGrant`, `listGrants`, `revokeGrant`, `setGrantsFilePathForTesting`, plus internal `saveGrant`. All IO under `@poe-code/file-lock`. | +| `packages/agent-human-in-loop/src/grants.test.ts` | Unit tests per §4. Uses `vi.setSystemTime`, tmp paths via `setGrantsFilePathForTesting`. | +| `packages/agent-human-in-loop/src/grants.race.test.ts` | Spawns two child Node processes that each call `saveGrant` 50 times. Asserts file integrity. | +| `packages/agent-human-in-loop/test/setup.ts` | Vitest setup file: per-test tmp grants path. | +| `packages/agent-human-in-loop/vitest.config.ts` | Created if absent; wires `setupFiles`. | +| `packages/toolcraft/src/human-in-loop/approvals-grants-commands.ts` | Defines the `grants` subgroup (`list`, `revoke`). Renders rich/markdown/json. | +| `packages/toolcraft/src/human-in-loop/approvals-grants-commands.test.ts` | Unit tests per §4. | + +### Files to change + +| File | Change | +| --- | --- | +| `packages/agent-human-in-loop/src/types.ts` | Add `ApprovalWindow`. Extend `ApprovalResult` approve variant with `window` + optional `grantHit`. Add `Grant`. | +| `packages/agent-human-in-loop/src/request-approval.ts` | Add `grantKey?` to args. Wrap provider call: lookup → call → maybe save. | +| `packages/agent-human-in-loop/src/request-approval.test.ts` | New cases per §4. | +| `packages/agent-human-in-loop/src/providers/osascript-script.ts` | Replace `buildScript` with single `choose from list` form (windows + Decline cancel button). Two-stage variant when `declineInputPrompt` set: `choose from list` → second dialog only when Decline. Update `parseStdout` for `Approve once` / `Allow for 1 hour` / `Allow for today` / `DECLINED` / `DECLINED:`. | +| `packages/agent-human-in-loop/src/providers/osascript-script.test.ts` | Snapshot regenerated. New `parseStdout` cases. | +| `packages/agent-human-in-loop/src/providers/osascript.ts` | No structural change; pick up new `parseStdout` outputs through the existing helper boundary. | +| `packages/agent-human-in-loop/src/providers/osascript.test.ts` | Update fake-binary stdout strings to the new outputs. | +| `packages/agent-human-in-loop/src/providers/mock.ts` | No code change. (Type widening is automatic.) | +| `packages/agent-human-in-loop/src/index.ts` | Re-export `findLiveGrant`, `listGrants`, `revokeGrant`, `setGrantsFilePathForTesting`, `ApprovalWindow`, `Grant`. | +| `packages/agent-human-in-loop/package.json` | Add `@poe-code/file-lock` to `dependencies`. | +| `packages/agent-human-in-loop/README.md` | Document the grant store, file path, `setGrantsFilePathForTesting`, per-package env vars (still none), and the new dialog. | +| `packages/agent-human-in-loop/QA.md` | Add manual flows per §4. | +| `packages/agent-human-in-loop/example.ts` | Show window picker; print result. | +| `packages/toolcraft/src/human-in-loop/types.ts` | Add `grants?: boolean` to `HumanInLoopRuntimeOptions`. | +| `packages/toolcraft/src/human-in-loop/gate.ts` | Sync path: thread `grantKey: commandPath` through new `requestApproval`. Async path: `findLiveGrant(commandPath)` short-circuit before `enqueueApproval`, gated by `runtimeOptions.grants !== false`. | +| `packages/toolcraft/src/human-in-loop/gate.test.ts` | Add cases per §4. | +| `packages/toolcraft/src/human-in-loop/runner.ts` | Replace bare `provider.requestApproval` call with top-level `requestApproval({ ..., grantKey: approval.commandPath })` (when grants enabled). | +| `packages/toolcraft/src/human-in-loop/runner.test.ts` | Add cases per §4. | +| `packages/toolcraft/src/human-in-loop/approvals-commands.ts` | Append `grantsGroup` (from new file) to `approvalsGroup.children`. No other change. | +| `packages/toolcraft/src/human-in-loop/index.ts` | Re-export `Grant`, `ApprovalWindow`. | +| `packages/toolcraft/README.md` | Document `runtimeOptions.grants`. | +| `packages/toolcraft/src/human-in-loop/mcp-runtime.integration.test.ts` | Add the grant-hit assertion per §4. | +| `packages/toolcraft/src/human-in-loop/cli-runtime.integration.test.ts` | Same. | +| `packages/toolcraft/src/human-in-loop/sdk-runtime.integration.test.ts` | Same. | + +### Function signatures + +```ts +// agent-human-in-loop/src/grants.ts +export function findLiveGrant(grantKey: string): Promise; +export function listGrants(): Promise; +export function revokeGrant(id: string): Promise; +export function setGrantsFilePathForTesting(path: string | undefined): void; +// internal +export function saveGrant(input: { commandPath: string; window: "1h" | "today" }): Promise; + +// agent-human-in-loop/src/request-approval.ts +export function requestApproval( + args: ApprovalRequest & { grantKey?: string; provider: HumanInLoopProvider } +): Promise; + +// agent-human-in-loop/src/providers/osascript-script.ts +export function buildScript(request: ApprovalRequest, title: string): string; +export function parseStdout(out: string): ApprovalResult; +export function escapeAppleScriptString(value: string): string; + +// toolcraft/src/human-in-loop/approvals-grants-commands.ts +export const grantsGroup: Group; +``` + +### Build order + +TDD throughout. Each step ends green. + +1. **Types extension** — update `agent-human-in-loop/src/types.ts`. Add `ApprovalWindow`, extend `ApprovalResult`, add `Grant`. Run `npm run build --workspace agent-human-in-loop`. No new tests yet. +2. **Grant store, red → green** — write `grants.test.ts` covering all §4 cases except the race. Implement `grants.ts` (file-lock, sweep-on-read, schemaVersion gate, path resolver). Tests pass. No real disk pollution. +3. **Vitest setup wiring** — create `test/setup.ts` and `vitest.config.ts`; setup applies tmp paths around every test. Verify by running step-2 tests with the setup file in place. +4. **Race test** — write `grants.race.test.ts` spawning two child processes. Implement only if the file-lock integration needs adjustment; expectation is it passes against the `grants.ts` from step 2. +5. **`requestApproval` wrapper, red → green** — extend `request-approval.test.ts` for the new cases. Update `request-approval.ts` to accept `grantKey`, do lookup-call-write. Tests pass. +6. **AppleScript single-form, red → green** — update `osascript-script.test.ts` snapshots and `parseStdout` cases. Update `osascript-script.ts`. Tests pass. +7. **osascript provider stdout** — update `osascript.test.ts` fake-binary stdout. Adjust provider only if `parseStdout`'s contract changed. +8. **Public exports** — update `agent-human-in-loop/src/index.ts`. Update `package.json` (`@poe-code/file-lock` dep). Update `README.md` and `QA.md`. +9. **Build + test agent-human-in-loop** — `npm run build --workspace agent-human-in-loop`, `npm run test --workspace agent-human-in-loop`. Green. +10. **Toolcraft runtime option** — update `toolcraft/src/human-in-loop/types.ts`. Build green. +11. **Toolcraft sync gate, red → green** — extend `gate.test.ts` for sync grantKey threading. Update `gate.ts` sync branch. +12. **Toolcraft async gate, red → green** — extend `gate.test.ts` for async short-circuit + `grants: false`. Update `gate.ts` async branch. +13. **Runner, red → green** — extend `runner.test.ts`; update `runner.ts` to thread `grantKey`. +14. **Approvals grants subgroup, red → green** — write `approvals-grants-commands.test.ts`; implement `approvals-grants-commands.ts`; mount in `approvals-commands.ts`. +15. **Toolcraft re-exports + README** — `toolcraft/src/human-in-loop/index.ts`, `toolcraft/README.md`. +16. **Integration tests** — extend `mcp-runtime.integration.test.ts`, `cli-runtime.integration.test.ts`, `sdk-runtime.integration.test.ts`. +17. **Build + test toolcraft** — `npm run build --workspace toolcraft`, `npm run test --workspace toolcraft`. Green. +18. **Visual screenshot** — `npm run screenshot-poe-code -- approvals grants list` to verify the new table renders correctly. Capture for QA.md. +19. **Spot test** — run a sample command twice through `npm run dev`; first call pops the dialog, second call short-circuits. Confirm `approvals grants revoke` clears it. +20. **Sweep** — `npm run lint`, `npm run typecheck`, `npm run test` from root. All green. +21. **Commit** — single conventional commit `feat(agent-human-in-loop,toolcraft): time-bounded approval grants`. Files committed individually per CLAUDE.md (no `git add -A`). Plan doc included in the commit. After ship, move plan to `docs/plans/archive/`. diff --git a/docs/plans/toolcraft-help-and-result-rendering.md b/docs/plans/toolcraft-help-and-result-rendering.md new file mode 100644 index 0000000000..1ad84447ad --- /dev/null +++ b/docs/plans/toolcraft-help-and-result-rendering.md @@ -0,0 +1,725 @@ +--- +$schema: https://poe-platform.github.io/poe-code/schemas/plans/pipeline.schema.json +kind: pipeline +version: 1 + +tasks: + - id: design-system-format-columns + title: Width-aware formatColumns helper in design-system + prompt: | + Add a width-aware column formatter to + packages/design-system/src/components/help-formatter.ts. + + Public API: + + export interface FormatColumnsOptions { + rows: Array<{ left: string; right: string }>; + totalWidth?: number; // defaults to process.stdout.columns ?? 100 + minLeftWidth?: number; // defaults to 12 + maxLeftWidth?: number; // defaults to 32 + gap?: number; // defaults to 3 + indent?: number; // defaults to 2 + } + + export function formatColumns(opts: FormatColumnsOptions): string; + + Behaviour: + - leftWidth = clamp(max(rows.map(r => visibleWidth(r.left))) + gap, + minLeftWidth, maxLeftWidth) + - rightWidth = max(20, totalWidth - leftWidth - indent) + - For each row: indent + padEnd(left, leftWidth) + word-wrapped + right column. Continuation lines align to (indent + leftWidth). + - visibleWidth strips ANSI escape codes when measuring. Add a + 5-line inline ANSI-strip helper; do not pull a new dep. + - Word-wrap breaks on whitespace; long unbreakable tokens are + emitted as-is and overflow rather than mid-token-broken. + - Empty rows array returns "" (no trailing newline). + + Refactor formatCommandList and formatOptionList in the same file + to be thin wrappers over formatColumns. Their public signatures + stay the same. Internally: + - formatCommandList maps { name, description } to + { left: text.command(name), right: description } + - formatOptionList maps { flags, description } to + { left: text.option(flags), right: description } + + Drop reliance on widths.helpColumn = 24 (it can stay as a token + but the formatter no longer reads it). + + Tests in + packages/design-system/src/components/help-formatter.test.ts: + - formatColumns aligns left to min(maxLen+gap, maxLeftWidth) + - wraps right at totalWidth - leftWidth - indent + - continuation indent is preserved + - ANSI-styled left tokens do not widen the column + - empty rows array returns "" + - formatCommandList / formatOptionList still produce expected + output via the new path (snapshot a small example) + + No filesystem in tests; pure string assertions. + status: + implement: open + test: open + commit: open + + - id: design-system-section-header + title: Add text.sectionHeader to design-system + prompt: | + Add a sectionHeader function to + packages/design-system/src/components/text.ts on the existing + `text` object: + + sectionHeader(content: string): string + + Behaviour: + - terminal mode: typography.bold(content.toUpperCase()), + rendered on its own line, no trailing colon + - markdown mode: `## ${content}` + - JSON mode: passthrough (return content unchanged) + + Reuse the same resolveOutputFormat / typography path that + text.section already uses. Do NOT remove text.section — other + callers depend on it. + + Re-export sectionHeader from packages/design-system/src/index.ts + alongside the existing `text` export. (sectionHeader lives on + `text`; just confirm `text` is exported.) + + Tests in packages/design-system/src/components/text.test.ts (new + or existing): + - terminal mode: returns bold uppercase, no colon + - markdown mode: returns `## Title` + - JSON mode: returns input unchanged + status: + implement: open + test: open + commit: open + + - id: design-system-help-formatter-plain + title: Plain-text fallback module for help-formatter + prompt: | + Create + packages/design-system/src/components/help-formatter-plain.ts. + + Re-export formatColumns, formatCommandList, formatOptionList + with the SAME signatures as + packages/design-system/src/components/help-formatter.ts but + bypass chalk and `text.*` styling — produce ASCII-only output + with no ANSI escape codes. + + Re-export from packages/design-system/src/index.ts as a + sub-namespace, e.g.: + + export * as helpFormatterPlain from + "./components/help-formatter-plain.js"; + + Use cases: + 1. runCLI output when process.stdout.isTTY === false + 2. Source for regenerating + ashby-mcp/todos_mcp_cli/vendor/design-system/index.js (the + vendored stub today reduces formatCommandList / + formatOptionList to `${name}\t${desc}`; that gets replaced + by this module's plain output). + + Tests in + packages/design-system/src/components/help-formatter-plain.test.ts: + - output contains no ANSI escape codes (regex + /\x1b\[[0-9;]*m/ never matches) + - same row alignment / wrapping rules as the chalk version + (reuse a couple of cases from help-formatter.test.ts to + confirm parity) + status: + implement: open + test: open + commit: open + + - id: toolcraft-help-global-options-gate + title: Gate global option rows in toolcraft help + prompt: | + Rewrite formatGlobalOptionRows in + packages/toolcraft/src/cli.ts (current location around line + 1211, function name unchanged). + + New signature: + + function formatGlobalOptionRows(ctx: { + showVersion: boolean; + presetsEnabled: boolean; + }): HelpOptionRow[] + + Rules: + - --preset → only if presetsEnabled + - --yes → always + - --output → always; description text becomes + "Output format: rich, md, json." + (drop the parenthesised form) + - -h, --help → NEVER on a help screen. Do not push + this row from this function. Help is + still wired by commander, just not + advertised in the rendered help table. + - --version → only if showVersion + + Update the call sites in renderGroupHelp and renderLeafHelp to + pass { showVersion: options.version !== undefined, + presetsEnabled: options.presets === true }. + + Rename the section header from "Global options:" to "Options" + (no trailing colon). Use text.sectionHeader from + @poe-code/design-system instead of text.section for that line + (and for "Commands", "Options", "Secrets (environment)"). + + Today the shipped toolcraft@0.0.3 unconditionally pushes + --preset, --yes, --output, -h/--help and the source has a + partial gate; this task makes the gate complete and consistent. + + Tests in packages/toolcraft/src/cli.test.ts (or a new + cli.help.test.ts): three snapshot cases: + 1. presets:false, version:undefined → only --yes and + --output rendered + 2. presets:true, version:"1.2.3" → --preset, --yes, + --output, --version rendered (in that order) + 3. -h, --help never appears in any of the above + status: + implement: open + test: open + commit: open + + - id: toolcraft-help-field-tokens + title: Boolean-aware and pattern-aware help field tokens + prompt: | + Fix value-token rendering in + packages/toolcraft/src/cli.ts. The relevant function is + formatHelpFieldFlags (~line 760) plus its callers. + + Today: every option renders as `${flags} [value]` (for booleans) + or `${flags} ` / `` (for scalars). This leaks + schema kinds into help and confuses booleans with optional-value + flags. + + Required behaviour: + + Booleans: + - default false (or no default) → render `--flag`, no value + token at all + - default true → render `--no-flag` (the negation form), + since enabling is the no-op + + Scalars / arrays: + Token derivation, in priority order: + 1. field.schema.format if present: + "date" → + "date-time" → + "uri" → + "email" → + 2. field.schema.pattern: if it matches a known shape, expand: + /^\d{4}-\d{2}-\d{2}$/ → + /^\d{4}-\d{2}-\d{2}T/ → + Otherwise fall through. + 3. Field-name heuristic on the displayPath / optionFlag: + *Path / *File → + *Url → + *Email → + *Name → + *Id → + 4. Fallback: + + The schema-kind tokens and are NEVER emitted + by help. (commander still uses them internally for parsing — + that is fine; the help renderer just produces its own token.) + + Tests in packages/toolcraft/src/cli.test.ts: + - boolean field default false → row shows "--flag", no value + token; description appended in the right column + - boolean field default true → row shows "--no-flag" + - string field with pattern ^\d{4}-\d{2}-\d{2}$ → "--date + " + - string field with format=email → "" + - string field named "configPath" with no schema metadata → + "" + - string field with no metadata and no name match → "" + - / never appear in any rendered help row + (regex assertion across the rendered output) + status: + implement: open + test: open + commit: open + + - id: toolcraft-help-document-layout + title: Heading line, Usage line, breadcrumb, flat commands list + prompt: | + Rewrite renderHelpDocument, renderGroupHelp, renderLeafHelp, + and formatCommandRows in packages/toolcraft/src/cli.ts. + + Heading and description (renderHelpDocument): + - Drop empty breadcrumb segments before joining: + breadcrumb.filter((s) => s.length > 0).join(" ") + (today the root group has name "" and the current code + prints a leading space and a blank heading line). + - If description is present, render the heading on a single + line: `${title} — ${description}` + When description spans multiple sentences, use the first + sentence (split on first ". ") for the heading line; emit + the remainder as a paragraph after a blank line. + + Usage line (always rendered): + - `Usage: ${rootUsageName} ${subPath} ${suffix}` + - subPath = breadcrumb.filter((s) => s.length > 0).slice(1) + .join(" ") + - suffix is "[command] [options]" for groups, or + "[options]" + positional tokens for leaves (existing logic). + - rootUsageName resolution: use options.rootUsageName when set; + otherwise fall back to inferProgramName(process.argv) (that + helper already exists at the top of cli.ts but is currently + only used when `roots` is an array — extend the fallback to + fire whenever options.rootUsageName is undefined). + + Section headers: + - Use text.sectionHeader(...) from @poe-code/design-system, + not text.section(...). Headers are "Commands", "Options", + "Secrets (environment)" — no trailing colons. + + Flat commands list (formatCommandRows): + - Remove the recursive depth-prefixed rendering (" ".repeat + (depth)). A group's "Commands" section lists ONLY its + direct children. To see grandchildren, the user runs + `--help` on the child group. + + Tests in packages/toolcraft/src/cli.test.ts (snapshots for each + case at process.stdout.columns = 100, isTTY = true unless + noted): + 1. Root group with name "", description "X" → heading is + inferred program name + " — X" (no leading space, no + empty heading line) + 2. Two-level group `parent child --help` → heading is + "parent child — desc" + 3. Usage line always present at all levels; rootUsageName + defaults from argv + 4. Group with subgroups: Commands section lists ONLY direct + children, no indented grandchildren + 5. Leaf with description containing two sentences: heading + uses first sentence; remainder appears as a paragraph + after a blank line + 6. Snapshot at columns=60: descriptions wrap; section + headers still render correctly + 7. Snapshot at isTTY=false: plain-text helpFormatterPlain + path is used; output contains no ANSI escape codes + status: + implement: open + test: open + commit: open + + - id: toolcraft-renderer-mcp-unwrap + title: Auto-unwrap MCP CallToolResult in renderer + prompt: | + In packages/toolcraft/src/renderer.ts add a normaliser that + runs at the start of renderResult. + + Detection (strict to avoid false positives on user data): + + function isMcpCallToolResult(v: unknown): v is { + content?: unknown[]; + structuredContent?: unknown; + isError?: boolean; + _meta?: unknown; + } { + if (!isObject(v)) return false; + const hasContent = Array.isArray((v as any).content); + const hasStructured = (v as any).structuredContent !== undefined; + if (!hasContent && !hasStructured) return false; + return Object.keys(v).every((k) => + k === "content" || k === "structuredContent" || + k === "isError" || k === "_meta"); + } + + Extraction: + + function extractMcpPayload(env): unknown { + const sc = env.structuredContent; + if (isObject(sc) && "result" in sc) return (sc as any).result; + if (sc !== undefined) return sc; + if (Array.isArray(env.content)) { + const text = env.content + .filter((b) => b && b.type === "text" && + typeof b.text === "string") + .map((b) => b.text) + .join("\n"); + return text.length > 0 ? text : undefined; + } + return undefined; + } + + Wiring: + - renderResult calls unwrapMcpEnvelope(result) before + autoRender / custom render hooks. + - When env.isError === true, write the unwrapped payload (or + joined content[*].text fallback) to STDERR via the WriteFn + and signal the caller to set process.exitCode = 1. + - Extend WriteFn to + (chunk: string, stream?: "stdout" | "stderr") => void; + default to process.stdout.write / process.stderr.write + respectively. + - In packages/toolcraft/src/cli.ts, after the command handler + returns, if the renderer signalled an MCP error, set + process.exitCode = 1. Today the run-CLI exit handling + (around line 2985) only sets non-zero on commander throws. + + Tests in packages/toolcraft/src/renderer.test.ts (new): + 1. structuredContent.result = "- Daily Focus", no isError → + stdout is "- Daily Focus\n", exitCode untouched + 2. structuredContent = { foo: 1, bar: 2 }, no .result → the + unwrapped value is the object (downstream rendering tested + by toolcraft-renderer-yaml-fallback) + 3. content = [{type:"text",text:"hello"},{type:"text", + text:"world"}], no structuredContent → stdout is + "hello\nworld\n" + 4. content = [], no structuredContent → stdout is "Done.\n" + (via existing autoRender null/undefined path) + 5. isError:true with text content → stderr receives the + text; stdout is empty; exitCode marker is set + 6. Object with extra keys + ({content,structuredContent,isError,customKey}) is NOT + treated as an envelope and renders as-is + status: + implement: open + test: open + commit: open + + - id: toolcraft-renderer-yaml-fallback + title: String/string[] shortcuts plus YAML fallback in autoRender + prompt: | + In packages/toolcraft/src/renderer.ts simplify autoRender so + that, after the MCP envelope unwrap, results render as + human-readable text by default. + + Add `yaml` as a direct dependency of packages/toolcraft if it + is not already pulled in. Import as + import YAML from "yaml"; + + autoRender rules (after the unwrap step from + toolcraft-renderer-mcp-unwrap): + 1. value === null || value === undefined → "Done." + 2. typeof value === "string" → value (printed as-is, single + trailing newline added by renderResult) + 3. Array.isArray(value) && value.every(v => typeof v === + "string") → value.join("\n") + 4. Otherwise → YAML.stringify(value) + + The previous renderObjectTable / renderArrayTable paths are NO + LONGER reached from autoRender. Keep both functions exported so + Command.render.rich consumers can still use them when they want + a tabular layout — autoRender just does not call them. + + output mode handling stays: + - --output md → existing markdown renderer on the unwrapped + payload (unchanged) + - --output json → existing JSON renderer on the unwrapped + payload (unchanged) + - default --output rich (or unset) → the four-rule layer + above + + Tests in packages/toolcraft/src/renderer.test.ts: + 1. string → as-is + 2. string[] → joined with \n + 3. object {foo:1, bar:[1,2]} → YAML.stringify output + (snapshot match) + 4. array of objects → YAML.stringify output (snapshot match) + 5. Command.render.rich defined → handler is invoked; YAML is + bypassed + 6. --output md → markdown renderer runs; YAML NOT used + 7. --output json → JSON renderer runs; YAML NOT used + + Update any existing renderer tests whose expectations were + based on the old object/array table being the default. Tables + now appear only via Command.render.rich, never automatically. + status: + implement: open + test: open + commit: open + + - id: toolcraft-help-output-qa + title: Markdown QA for help output at multiple terminal widths + prompt: | + Create packages/toolcraft/QA-help-output.md as an ad-hoc + manual QA walkthrough (not a test script — markdown only, per + the project's QA-as-markdown rule). + + Contents: + + 1. A small example consumer the QA can run from the toolcraft + package itself. Either reuse an existing fixture under + packages/toolcraft/src/cli.test.fixture.json or describe + a one-file example with two groups, one leaf with mixed + field shapes (boolean, pattern-constrained string, + positional), one secret. The QA must not depend on + ashby-mcp. + + 2. Steps to run the example at three terminal widths: + - 60 columns + - 100 columns + - 160 columns + For each width, capture root --help, group --help, + leaf --help. + + 3. Acceptance checklist for each captured screen: + [ ] Heading is " — " with no + leading space and no blank heading line + [ ] Usage: line is present + [ ] Section header is "Commands" / "Options" / + "Secrets (environment)" — no trailing colons + [ ] -h, --help is NOT listed under Options + [ ] --preset is listed only when presets:true was passed + [ ] --version is listed only when version is set + [ ] Boolean flags render as --flag, not --flag [value] + [ ] Pattern-constrained scalar renders the human token + (e.g. ), not + [ ] Description column wraps at the right edge; + continuation lines align with the description column + + 4. Steps to verify run output: + - run a command whose handler returns a string + - run a command whose handler returns string[] + - run a command whose handler returns an object + - run a command whose handler is an MCP proxy returning + a CallToolResult + - run a command whose handler returns isError:true + For each, the acceptance checklist: + [ ] string → printed as-is + [ ] string[] → one per line + [ ] object → YAML + [ ] MCP envelope → unwrapped to its payload, then + rendered per the rules above + [ ] isError → payload to stderr, process exit code 1 + + Do NOT write a test runner. The QA is human-executed. + status: + implement: open + commit: open + + - id: toolcraft-release-and-vendor-refresh + title: Release toolcraft 0.0.4 and refresh ashby-mcp vendor stub + prompt: | + Cut a release that ships the help and renderer fixes, and + regenerate the consumer-side vendor stub so ashby-mcp picks + them up. + + Steps: + + 1. Bump packages/design-system version (patch level — output + surface change, no programmatic API removal). + + 2. Bump packages/toolcraft version to 0.0.4. + + 3. Update each package's CHANGELOG / release notes if the + repo has them (search the package for a CHANGELOG.md + before adding one; do not create one if not present). + + 4. Push the branch / open a PR per the repo's standard + release workflow. Releases are done on github via the + trusted-publishing workflow — do not publish from local. + See NPM_PUBLISHING.md at the repo root for the canonical + sequence. + + 5. After publish, in the ashby-mcp consumer + (/Users/kjopek/Workspace/ashby-mcp): + - update todos_mcp_cli/package.json: bump + toolcraft to ^0.0.4 (or pin to the registry tarball + URL if the existing entry uses that form) + - regenerate + todos_mcp_cli/vendor/design-system/index.js from + packages/design-system/dist/components/help-formatter-plain.js + so the vendored copies of formatCommandList / + formatOptionList match the new wrapping/padding + behaviour. The vendor stub is what actually ships + inside ashby-mcp; the npm-installed copy is shadowed + by the file: link in package.json. + - npm install in todos_mcp_cli/ + + 6. Smoke test in ashby-mcp via terminal-pilot (or by hand + in a terminal): + node todos_mcp_cli/bin/todos-mcp-cli.mjs --help + node todos_mcp_cli/bin/todos-mcp-cli.mjs calendar --help + node todos_mcp_cli/bin/todos-mcp-cli.mjs calendar events --help + node todos_mcp_cli/bin/todos-mcp-cli.mjs calendar events list --help + node todos_mcp_cli/bin/todos-mcp-cli.mjs todo lists --yes + Confirm: + - no leading blank lines on root help + - no -h, --help row anywhere in the help output + - no Global options: header + - todo lists prints "- Daily Focus" (or whatever the + actual value is), NOT a key/value table of the + envelope + + Do not run any of the destructive paths flagged in + todos_mcp_cli/bin/todos-mcp-cli.mjs's + destructiveCommandsByGroupPath (asana add_task / delete, + calendar.meeting create / edit). Only --help and known + read-only commands. + status: + implement: open + commit: open +--- + +## Toolcraft help and result rendering overhaul + +Holistic fix for `toolcraft` CLI output: rebuild `--help` from the design system, render results as human-readable text by default, and stop dumping raw MCP `CallToolResult` envelopes when a proxied command runs. + +Driver: `ashby-mcp/todos_mcp_cli` consumes `toolcraft@0.0.3`. Help is unreadable, results render as a 4-row key/value table of the MCP envelope. Both flaws live in `packages/toolcraft` and `packages/design-system`; ashby-mcp is just the witness. + +## North star: human-readable output + +Every screen toolcraft renders is read by a person, in a terminal, scanning for what to do next. Every formatting decision answers to that. + +- **Sentences, not jargon.** No `` schema-kind tokens, no `[value]` placeholders, no envelope keys (`structuredContent`, `content[]`, `isError`) leaking out. +- **One thing per line.** Descriptions wrap to terminal width with continuation aligned under the description column. +- **Skim-first.** Bold section header, indent rows, blank line between sections. +- **No noise.** No `-h, --help` on a `--help` screen. No `--preset` if presets aren't enabled. No repeated `Global options:` header. +- **Results read like prose by default.** String → text. `string[]` → one per line. Anything richer → YAML. Tables only via `Command.render.rich`. +- **Width-aware.** `process.stdout.columns` honoured; layout composes at 60 cols, doesn't sprawl at 160. + +## Observed defects + +Captured via terminal-pilot against ashby-mcp at 120 cols. + +### Root --help (today) + +```text +$ node todos_mcp_cli/bin/todos-mcp-cli.mjs --help + + +CLI proxy for todo workspace tools. + +Commands: +slack Slack messages and channels. +asana Asana project tasks. +todo Apple Reminders todos. +calendar Google Calendar. +approvals Inspect and execute queued approvals. + +Global options: +--preset Load parameter defaults from a JSON file +--yes Accept defaults, skip prompts +--output Output format (rich, md, json) +-h, --help Show help +``` + +Defects: empty heading line; no Usage line; `-h, --help` listed during `--help`; `Global options:` header repeats on every screen; `--preset` advertised even when presets are not enabled; tab-separated columns from the vendored `@poe-code/design-system` stub at `ashby-mcp/todos_mcp_cli/vendor/design-system/index.js` produce inconsistent alignment. + +### Group --help (today) + +```text + calendar events + +Google Calendar events. + +Commands: +list Get Google Calendar events for today, tomorrow, the current week, or a specific date. Returns events with UIDs usable by google_calendar_edit_meeting. TIMEZONE HANDLING: ... +``` + +Heading has a leading space (`breadcrumb = ["", "calendar", "events"]`); description column overflows the terminal width. + +### Leaf --help (today) + +```text +Options: +--tomorrow [value] Get tomorrow's events ... (default: false) +--week [value] Get this week's events ... (default: false) +--details [value] Include Notion and Zoom links in output (default: false) +--date Specific date in YYYY-MM-DD format ... +``` + +Booleans render as `[value]`; `--date ` exposes the schema kind instead of the value shape. + +### Run output (today) + +```text +$ node todos_mcp_cli/bin/todos-mcp-cli.mjs todo lists --yes +key value +content [{"type":"text","text":"- Daily Focus"}] +structuredContent {"result":"- Daily Focus"} +isError false +``` + +The MCP `CallToolResult` envelope is rendered instead of its payload. The actual result `"- Daily Focus"` lives at `structuredContent.result`. + +## Target output + +### Root --help + +```text +todos-mcp-cli — CLI proxy for todo workspace tools. + +Usage: todos-mcp-cli [command] [options] + +Commands + slack Slack messages and channels. + asana Asana project tasks. + todo Apple Reminders todos. + calendar Google Calendar. + approvals Inspect and execute queued approvals. + +Options + --yes Accept defaults, skip prompts. + --output Output format: rich, md, json. +``` + +### Group --help + +```text +calendar — Google Calendar. + +Usage: todos-mcp-cli calendar [command] [options] + +Commands + events Google Calendar events. + meeting Google Calendar meetings. + +Options + --yes Accept defaults, skip prompts. + --output Output format: rich, md, json. +``` + +### Leaf --help + +```text +calendar events list — Get today's, tomorrow's, this week's, or a specific date's events. + +Usage: todos-mcp-cli calendar events list [options] + +Options + --tomorrow Get tomorrow's events. + --week Get this week's events. + --details Include Notion and Zoom links. + --date Specific date (overrides --tomorrow / --week). + --yes Accept defaults, skip prompts. + --output Output format: rich, md, json. + +Secrets (environment) + GOOGLE_CREDENTIALS_FILE Path to Google OAuth credentials JSON. +``` + +### Run output (string result) + +```text +- Daily Focus +``` + +### Run output (object result) + +For `{ lists: [{ id: "1", title: "Daily Focus" }, { id: "2", title: "Errands" }] }`: + +```yaml +lists: + - id: "1" + title: Daily Focus + - id: "2" + title: Errands +``` + +vs. today's `key | value` table with JSON-stuffed cells. + +## Out of scope + +- Replacing commander; the parser stays. +- `NO_COLOR` / `--no-color` handling (already in design-system). +- Changing what MCP-proxied commands return; only the rendering of their result changes. +- Rich tabular output by default; tables remain available via `Command.render.rich`. From db1ef7424f07d0864343b20294cc41cd5a5b966c Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 22:57:33 -0500 Subject: [PATCH 043/111] feat(toolcraft-schema): add runtime validation --- docs/plans/agent-harness.md | 6 +- docs/plans/harness-plans-via-task-list.md | 136 ---- docs/plans/zharness-plans-via-task-list.md | 717 ++++++++++++++++++ packages/toolcraft-schema/package.json | 4 +- packages/toolcraft-schema/src/index.ts | 14 +- .../toolcraft-schema/src/validate.test.ts | 281 +++++++ packages/toolcraft-schema/src/validate.ts | 562 ++++++++++++++ 7 files changed, 1577 insertions(+), 143 deletions(-) delete mode 100644 docs/plans/harness-plans-via-task-list.md create mode 100644 docs/plans/zharness-plans-via-task-list.md create mode 100644 packages/toolcraft-schema/src/validate.test.ts create mode 100644 packages/toolcraft-schema/src/validate.ts diff --git a/docs/plans/agent-harness.md b/docs/plans/agent-harness.md index ca9be6e89d..f28dfeb064 100644 --- a/docs/plans/agent-harness.md +++ b/docs/plans/agent-harness.md @@ -44,9 +44,9 @@ tasks: application, additionalProperties rejection, nested object paths, and the multi-issue accumulation behavior. status: - implement: open - test: open - commit: open + implement: done + test: done + commit: done - id: agent-script-export-parser title: Parse `export const X = expr` and `export default expr` in agent-script diff --git a/docs/plans/harness-plans-via-task-list.md b/docs/plans/harness-plans-via-task-list.md deleted file mode 100644 index 3d241f2f5e..0000000000 --- a/docs/plans/harness-plans-via-task-list.md +++ /dev/null @@ -1,136 +0,0 @@ ---- -$schema: https://poe-platform.github.io/poe-code/schemas/plans/plan.schema.json -kind: plan -version: 1 ---- - -# Harness plans via task-list - -Replace the per-harness plan discovery + archive code with a single `@poe-code/task-list` `markdown-dir` task list, shared by experiment, ralph, pipeline, and superintendent. - -## 1. What we're building - -Switch every harness — experiment-loop, ralph, pipeline, superintendent — off its bespoke plan discovery and archive logic, onto one shared `@poe-code/task-list` `markdown-dir` task list. Plan files in the configured plan directory (e.g. `docs/plans/`, `.poe-code/ralph/plans/`) are tasks. The harness opens the task list and asks it for the active set, the plan to run, and the archive operation. Archive is the `archive` event on the task lifecycle: the abstraction moves the file under `archive/`, drops its order prefix, and re-packs the prefixes of the remaining active plans so there are no gaps. No harness owns archive logic anymore. - -Non-goals: - -- Changing plan markdown content or per-harness frontmatter (`kind: pipeline | ralph | superintendent | experiment`). -- Replacing the harness-specific plan parsers (`parsePlan` in pipeline, `parseSuperintendentDoc`, etc.) — those still operate on the file body. -- Changing the storage location for plans (each harness keeps its current default plan directory). -- Adding the `gh-issues` backend or yaml-file backend to harness plan discovery — `markdown-dir` only. -- Migrating the `task-list-ordering-and-gh-issues.md` work; that pipeline runs independently. - -## 2. User-facing shape - -### Shared discovery API in `@poe-code/agent-harness-tools` - -A single new export that every harness consumes. It opens a `task-list` `markdown-dir` over the plan directory, lists active tasks, and (optionally) filters by `kind`. - -```ts -import { discoverPlans, archivePlan, openPlanList } from "@poe-code/agent-harness-tools"; - -// Discovery — replaces three near-identical discovery files. -const plans = await discoverPlans({ - cwd, - homeDir, - planDirectory: "docs/plans", // optional; default per harness - kinds: ["pipeline"], // optional; filters Task.metadata.kind -}); - -// plans: Array<{ id: string; absolutePath: string; displayPath: string; kind: string }> - -// Archive after a successful run — replaces per-harness archivePlan() helpers. -await archivePlan({ cwd, homeDir, planDirectory: "docs/plans", id: "agent-harness" }); -// → moves NN-agent-harness.md to archive/agent-harness.md -// → renumbers every remaining NN-*.md so prefixes are gap-free - -// Lower-level handle if a harness needs more (rare). -const list = await openPlanList({ cwd, homeDir, planDirectory: "docs/plans" }); -``` - -`kinds` is matched against `Task.metadata.kind`, which the backend reads from each plan's existing YAML frontmatter (`kind: pipeline | ralph | superintendent | experiment | plan`). No frontmatter changes; the backend already round-trips unknown frontmatter into `metadata`. - -### Harness call sites — before / after - -Pipeline today (`packages/pipeline/src/run/pipeline.ts`): - -```ts -// before -async function archivePlan(fs: PipelineFileSystem, absolutePlanPath: string): Promise { - const dir = path.dirname(absolutePlanPath); - const archiveDir = path.join(dir, "archive"); - const archivePath = path.join(archiveDir, path.basename(absolutePlanPath)); - await fs.mkdir(archiveDir, { recursive: true }); - await fs.rename(absolutePlanPath, archivePath); -} -// after -import { archivePlan } from "@poe-code/agent-harness-tools"; -await archivePlan({ cwd, homeDir, planDirectory, id: planId }); -``` - -Ralph + experiment-loop drop their entire `discovery/discovery.ts` and replace internal calls to their local `archivePlan` with the same shared call. - -Superintendent uses `discoverPlans({ kinds: ["superintendent"] })` in place of its own scan; archive is unchanged for now (superintendent does not currently archive on completion — it stays out of scope until that flow exists). - -### Plan filenames - -Existing plans get a one-time renumber on this branch: - -```text -docs/plans/ - 01-agent-harness.md - 02-agent-human-in-loop.md - 03-braintrust-integration.md - ... - archive/ - cmdkit-openapi.md - ... -``` - -Order is alphabetical-by-id at migration time; subsequent reorders go through `Tasks.move`/`reorder`. The id is the filename stem with the `NN-` stripped — same as the backend already enforces. - -### Archive behavior change - -`fire(id, "archive")` (and the `task-list-driven archivePlan` wrapper) now repacks the remaining active tasks' prefixes after moving the archived file: - -```text -before: after fire("02-bar", "archive"): - 01-foo.md 01-foo.md - 02-bar.md 02-baz.md ← was 03 - 03-baz.md archive/bar.md -``` - -Default-on for every consumer of `markdown-dir`. The current behavior left dangling prefixes; that's a bug rather than a feature. - -### `markdown-dir` flat-root mode - -Plans live directly in the directory (`docs/plans/foo.md`), not under a list subdir (`docs/plans//foo.md`). The backend gains a single new option: - -```ts -openTaskList({ - type: "markdown-dir", - path: "docs/plans", - singleList: "plans" // ← new; root IS the list -}); -``` - -Behavior with `singleList`: - -- `lists()` returns `[singleList]`. -- `list(name)` requires `name === singleList` (any other throws). -- Active tasks live at `/*.md` / `/NN-*.md`. -- Archived tasks live at `/archive/*.md`. -- `moveBetweenLists` throws — single list. - -Without `singleList` the backend behaves exactly as today. - -### Plan-directory defaults - -Each harness keeps its own default plan directory: - -| Harness | Default `planDirectory` | `kinds` filter | -| --- | --- | --- | -| pipeline | `docs/plans` | `["pipeline"]` | -| ralph | `.poe-code/ralph/plans` | `["ralph"]` | -| experiment-loop | `.poe-code/experiments` | `["experiment"]` | -| superintendent | `docs/plans` | `["superintendent"]` | diff --git a/docs/plans/zharness-plans-via-task-list.md b/docs/plans/zharness-plans-via-task-list.md new file mode 100644 index 0000000000..f7b8178188 --- /dev/null +++ b/docs/plans/zharness-plans-via-task-list.md @@ -0,0 +1,717 @@ +--- +$schema: https://poe-platform.github.io/poe-code/schemas/plans/pipeline.schema.json +kind: pipeline +version: 1 + +tasks: + - id: task-list-options + title: Add singleList + frontmatterMode options to task-list types and open + prompt: | + Extend `@poe-code/task-list` so the `markdown-dir` backend can be opened in a + single-list, passthrough-frontmatter mode. This task is type plumbing only — + no behavior change yet. + + In `packages/task-list/src/types.ts`: + + 1. Add two optional fields to `OpenTaskListOptions`: + + ```ts + singleList?: string; + frontmatterMode?: "strict" | "passthrough"; + ``` + + 2. Add the same fields to `BackendDeps`. In `BackendDeps`, `frontmatterMode` + is required (no `?`) — the default is filled by `open.ts`. `singleList` + stays optional. + + In `packages/task-list/src/open.ts`: + + - Pass `options.singleList` straight through to `BackendDeps`. + - Pass `options.frontmatterMode ?? "strict"` to `BackendDeps`. + + Tests in `packages/task-list/src/open-task-list.test.ts`: + + - Existing tests must still pass with no changes (defaults preserve behavior). + - Add one new test: opening with `singleList: "plans"` and + `frontmatterMode: "passthrough"` does not throw and returns a `TaskList`. + + Constraints: + - No new files. + - `markdown-dir.ts` itself is not modified yet — it ignores the new fields + in this task. (If TypeScript flags unused fields, suppress via underscore + prefix or a small no-op read; the next task uses them.) + - Do not modify `gh-issues` types or any other backend. + status: + implement: open + test: open + commit: open + + - id: markdown-dir-single-list + title: markdown-dir singleList layout — root is the list + prompt: | + In `packages/task-list/src/backends/markdown-dir.ts`, implement the + `singleList` layout. When `deps.singleList` is set, the backend treats + the root `path` itself as the (only) list — no list subdirectory. + + Add an internal helper: + + ```ts + type ListLayout = { kind: "multi" } | { kind: "single"; name: string }; + function resolveListLayout(deps: BackendDeps): ListLayout { + return deps.singleList + ? { kind: "single", name: deps.singleList } + : { kind: "multi" }; + } + ``` + + Refactor the path helpers to take a layout: + + - `listPath(rootPath, layout, list)`: in single mode returns `rootPath`; in + multi mode returns `path.join(rootPath, list)`. + - `archiveDirectoryPath(rootPath, layout, list)`: in single mode returns + `path.join(rootPath, "archive")`; in multi mode returns + `path.join(rootPath, list, "archive")`. + - `archivedTaskPath(rootPath, layout, list, id)`: same shape as above plus + `${id}.md`. + + Wire the layout into: + + - `lists()`: in single mode returns `[layout.name]`. In multi mode + unchanged. + - `list(name)`: in single mode requires `name === layout.name`, otherwise + throws `Error("Task list \"\" not found.")` matching the existing + error style. In multi mode unchanged. + - `moveBetweenLists(qualifiedId, targetList)`: in single mode always + throws `Error("moveBetweenLists is unsupported in single-list mode.")`. + + Subdirectories of the root other than `archive/` are ignored when scanning + active tasks in single mode (mirror what multi mode does for non-list + directories). + + Tests in `packages/task-list/src/backends/markdown-dir.test.ts` (use memfs): + + - Open with `singleList: "plans"`, write `/foo.md` and + `/01-bar.md`. `lists()` returns `["plans"]`. + `list("plans").all()` returns both tasks. + - `list("other")` throws. + - `moveBetweenLists("plans/foo", "plans")` throws. + - A subdirectory `/poe-agent/` containing markdown is ignored. + - In multi mode (no `singleList`), all existing behavior is unchanged — + the existing test suite confirms this; do not modify those tests. + + Constraints: + - `frontmatterMode` is not yet wired; assume `"strict"` for reading in + this task (existing `assertValidTaskRecord` runs unchanged). + - Do not change `move`/`reorder`/`fire` semantics yet beyond what the + layout helpers require. + status: + implement: open + refactor: open + test: open + commit: open + + - id: markdown-dir-passthrough + title: markdown-dir frontmatterMode passthrough — read and write loose frontmatter + prompt: | + In `packages/task-list/src/backends/markdown-dir.ts`, implement the + `frontmatterMode: "passthrough"` mode so the backend can manage markdown + files whose frontmatter is not task-shaped (e.g. plan files with + `kind: pipeline`). + + Read path: + + - When `deps.frontmatterMode === "passthrough"`, skip + `assertValidTaskRecord`. Instead synthesize defaults: + - `name` defaults to the filename stem with any `NN-` prefix stripped + if `frontmatter.name` is missing or non-string. + - `state` defaults to `stateMachine.initial` if `frontmatter.state` is + missing or not in `validStates`. + - `description` continues to come from the markdown body. + - `metadataFromFrontmatter` uses a smaller reserved set in passthrough + mode: only `name`, `state`, `description`. Other keys (including + `$schema`, `kind`, `version`) flow into `Task.metadata`. + + Write path (used by `create`, `update`, `fire`): + + - In passthrough mode, do NOT inject `$schema: `, + `kind: "task"`, or `version: 1` when serializing. Round-trip every + frontmatter key the file already had, mutating only the recognized + fields (`name`, `state`, `description`) plus any explicit metadata + patches the caller passed. + - In strict mode, current behavior is unchanged. + + Tests in `packages/task-list/src/backends/markdown-dir.test.ts` (memfs): + + - With `singleList: "plans"`, `frontmatterMode: "passthrough"`: write a + file `/foo.md` whose frontmatter is + ```yaml + $schema: https://poe-platform.github.io/poe-code/schemas/plans/pipeline.schema.json + kind: pipeline + version: 1 + ``` + and an empty body. `list("plans").get("foo")` returns a Task whose + `state` equals the state machine's initial state, `name` equals + `"foo"`, and `metadata.kind === "pipeline"`, + `metadata.$schema === "...pipeline.schema.json"`, `metadata.version === 1`. + - `fire("foo", "")` (any non-archive event) writes the file with + the new `state` set on frontmatter, and the original `kind`, + `$schema`, `version` keys are preserved verbatim. Read the file back + and confirm the YAML keys. + - In strict mode (no `frontmatterMode`), an unrecognized + `kind: pipeline` still throws `MalformedTaskError` — confirm this is + the existing test, no regression. + + Constraints: + - Do not change strict mode behavior. + - Do not modify gh-issues or yaml-file backends. + - Filename → id translation (strip `NN-`) is already handled by + `parseActiveFilename`; reuse it for the synthesized name default. + status: + implement: open + refactor: open + test: open + commit: open + + - id: markdown-dir-archive-repack + title: markdown-dir fire(archive) repacks remaining prefixes + prompt: | + In `packages/task-list/src/backends/markdown-dir.ts`, fix the `fire` + flow so archiving a task also re-packs the order prefixes of the + remaining active tasks. Currently the active file is moved into + `archive/` but its prefix slot is left as a gap. + + Locate the `event.to === "archived"` branch in `fire` (around line 703). + Refactor so the archive flow: + + 1. Acquires `withListLock` (the same lock used by `move`/`reorder`). + The current code uses only `withTaskLock`; the archive branch needs + both — task lock for the file being archived, list lock for the + repack. Take list lock outside, task lock inside, to keep the + existing acquisition order consistent across the file. + 2. Performs the existing serialize + mkdir + rename of the active file + into `/.md`. + 3. Reads the remaining active filenames in the list (use the existing + `readActiveTasks`-style scan) and computes their ids in current + prefix order. + 4. Calls `rewriteListPrefixes(remainingIds)` so prefixes are gap-free. + + Apply this in both single-list and multi-list layouts (the helper + `archiveDirectoryPath` from the singleList task already returns the + right path for either). + + Tests in `packages/task-list/src/backends/markdown-dir.test.ts`: + + - Multi-list: list with three tasks `01-foo`, `02-bar`, `03-baz`. + `fire("bar", "archive")`. Assert the active dir now contains + `01-foo.md` and `02-baz.md` (renumbered) and the archive contains + `bar.md`. Snapshot the directory listing. + - Single-list (`singleList: "plans"`, passthrough): same scenario at + the root path. Same assertions adapted to root-level paths. + - Archive the only task: active list becomes empty, archive contains + one file, no `.md` left at root (multi: list dir is empty except + `archive/`). + - Concurrency: two `fire(_, "archive")` calls on different ids run + sequentially under the list lock and produce a consistent gap-free + prefix sequence (use the same memfs lock harness as existing + reorder tests). + + Constraints: + - Default-on for every consumer of `markdown-dir`. No flag. + - Strict-mode tests with the default state machine continue to pass. + - Do not change behavior for non-archive `fire` calls. + status: + implement: open + test: open + commit: open + + - id: agent-harness-tools-plans + title: agent-harness-tools — discoverPlans / archivePlan / openPlanList + prompt: | + Add a shared plan-management API to `@poe-code/agent-harness-tools` + that wraps `@poe-code/task-list` for harness use. + + In `packages/agent-harness-tools/package.json`, add to `dependencies`: + + ```json + "@poe-code/task-list": "workspace:*" + ``` + + Create `packages/agent-harness-tools/src/plans.ts` exporting: + + ```ts + import type { TaskList, TaskListFs } from "@poe-code/task-list"; + + export interface PlanRef { + id: string; + absolutePath: string; + displayPath: string; + kind: string; + name: string; + } + + export interface DiscoverPlansOptions { + cwd: string; + homeDir: string; + planDirectory: string; + kinds?: readonly string[]; + fs?: TaskListFs; + } + + export interface ArchivePlanOptions { + cwd: string; + homeDir: string; + planDirectory: string; + id: string; + fs?: TaskListFs; + } + + export interface OpenPlanListOptions { + cwd: string; + homeDir: string; + planDirectory: string; + fs?: TaskListFs; + } + + export function discoverPlans(options: DiscoverPlansOptions): Promise; + export function archivePlan(options: ArchivePlanOptions): Promise; + export function openPlanList(options: OpenPlanListOptions): Promise; + ``` + + Implementation: + + - Internally resolve the plan directory with `resolveWorkflowPath` from + `./paths.js`. + - All three functions open a markdown-dir task list with: + ```ts + openTaskList({ + type: "markdown-dir", + path: , + singleList: "plans", + frontmatterMode: "passthrough", + fs: options.fs, + }); + ``` + - `discoverPlans` calls `taskList.list("plans").all()`, then maps each + Task to a `PlanRef`: + - `id` = `task.id` + - `name` = `task.name` + - `kind` = `String(task.metadata.kind ?? "plan")` + - `absolutePath` = the resolved file path (compute from + `/[NN-].md` — the backend does not surface this, so + stat the directory once per call to find the actual filename, or + read it from the entry list returned by an internal helper. If the + backend lacks a way to surface the filename, add one — keep it + minimal). + - `displayPath` = path relative to `cwd` if the resolved path is + under `cwd`, else `~/`-prefixed if under `homeDir`, else absolute + (mirror `discoverWorkflowDocs` display logic in `paths.ts`). + - If `options.kinds` is provided, filter `metadata.kind` against it. + - `archivePlan` opens the list and calls + `taskList.list("plans").fire(id, "archive")`. Return void. + The state machine for plans is the default `defaultStateMachine`, + which has an `archive` event from any state to `archived`. Verify + this event exists in the state machine; if not, supply a custom + `stateMachine` to `openTaskList` with one event named `archive` + whose `from: "*"` and `to: "archived"`. + - `openPlanList` returns the underlying `TaskList`. + + If the resolved directory does not exist, `discoverPlans` returns + `[]` (do not throw — match current per-harness discovery behavior). + + Tests in `packages/agent-harness-tools/src/plans.test.ts` (memfs): + + - `discoverPlans` returns plans with kind from frontmatter; sets + `metadata.kind` correctly. + - `discoverPlans({ kinds: ["pipeline"] })` filters out non-pipeline + kinds. + - `discoverPlans` returns `[]` when the directory does not exist. + - `discoverPlans` ignores `archive/` and non-plan subdirectories. + - `archivePlan({ id })` moves the file to `archive/` and the next + `discoverPlans` call shows renumbered prefixes (gap-free). + - `archivePlan({ id })` throws `TaskNotFoundError` for an unknown id. + + Constraints: + - Use `memfs` for filesystem in tests; pass the in-memory fs via + `options.fs`. + - No `@modelcontextprotocol/sdk`, no `child_process`. + - No new env vars or CLI flags. + status: + implement: open + refactor: open + test: open + commit: open + + - id: agent-harness-tools-export + title: Re-export plans API from agent-harness-tools index + prompt: | + In `packages/agent-harness-tools/src/index.ts` add: + + ```ts + export { + discoverPlans, + archivePlan, + openPlanList, + } from "./plans.js"; + export type { + PlanRef, + DiscoverPlansOptions, + ArchivePlanOptions, + OpenPlanListOptions, + } from "./plans.js"; + ``` + + Update `packages/agent-harness-tools/README.md` only if it already + enumerates exports — add the new entries to the existing list. Do not + add new sections or expand documentation beyond what is already there. + + Constraints: + - Re-export only. No logic changes. + - Verify with `npm run build --workspace @poe-code/agent-harness-tools`. + status: + implement: open + commit: open + + - id: pipeline-migrate + title: Migrate pipeline harness to shared plan API + prompt: | + Switch the pipeline harness off its bespoke `archivePlan` helper and + onto the shared `archivePlan` from `@poe-code/agent-harness-tools`. + Keep pipeline-specific discovery (done/total counts, prompt UX) but + build it on top of `discoverPlans`. + + In `packages/pipeline/src/run/pipeline.ts`: + + - Delete the local `archivePlan` function (around line 150). + - At the existing call site (around line 394), replace + `await archivePlan(fs, absolutePlanPath)` with: + ```ts + import { archivePlan as archivePlanShared } from "@poe-code/agent-harness-tools"; + // ... + const id = path.basename(absolutePlanPath, ".md").replace(/^\d+-/, ""); + await archivePlanShared({ + cwd, + homeDir, + planDirectory: configuredPlanDirectory ?? "docs/plans", + id, + fs: , + }); + ``` + Pull `cwd`, `homeDir`, and `configuredPlanDirectory` from whatever + is already in scope at the call site. + + In `packages/pipeline/src/plan/discovery.ts`: + + - Keep the public functions `resolvePlanPath` and `resolvePlanPaths` + and their option shapes — they are consumed by the pipeline CLI. + - Replace the internals: instead of scanning markdown files directly, + call `discoverPlans({ cwd, homeDir, planDirectory, kinds: ["pipeline"], fs })` + from `@poe-code/agent-harness-tools` to get the candidate list. + - Continue to compute `done/total` per candidate by reading and + parsing the plan body via the existing `parsePlan` (this stays + pipeline-specific). + - The `displayPath` returned by `discoverPlans` is the same shape the + prompt UX needs. + + Add `@poe-code/agent-harness-tools` already exists as a dep, so no + package.json change is required. Confirm. + + Tests: + + - Existing pipeline discovery tests must pass after the swap. + Where the test asserted directory state after archive, update the + assertion to expect the renumbered remaining files. + - Where the test asserted on the local `archivePlan`'s exact rename, + switch to checking that the file moved to `archive/.md` and the + active list is gap-free. + - Run `npm test --workspace @poe-code/pipeline`. + + Constraints: + - No CLI surface changes. + - Plan filenames are still flat (no NN- prefix yet) — the rename + happens in a later task. The shared API tolerates files without + prefixes. + status: + implement: open + test: open + commit: open + + - id: ralph-migrate + title: Migrate ralph harness to shared plan API + prompt: | + Switch the ralph harness off its bespoke `archivePlan` helper and + `discovery/discovery.ts` onto the shared API. + + In `packages/ralph/src/run/ralph.ts`: + + - Delete the local `archivePlan` function (around line 496). + - Replace both call sites (around line 201 and line 236): + ```ts + import { archivePlan as archivePlanShared } from "@poe-code/agent-harness-tools"; + // ... + const id = path.basename(absoluteDocPath, ".md").replace(/^\d+-/, ""); + await archivePlanShared({ + cwd, + homeDir, + planDirectory: planDirectory ?? ".poe-code/ralph/plans", + id, + }); + ``` + + In `packages/ralph/src/discovery/discovery.ts`: + + - Replace the body of `discoverDocs` (the public function) with a + thin call into `discoverPlans({ cwd, homeDir, planDirectory, kinds: ["ralph"], fs })` + and adapt the return shape (the existing + `Array<{ path; displayPath }>`) from the resulting `PlanRef[]`. + - Keep the function's signature and exports unchanged so callers do + not need to be touched in this task. + + Confirm `@poe-code/agent-harness-tools` is already in the ralph + package's dependencies (it is — ralph already imports + `discoverWorkflowDocs` from it). No `package.json` change. + + Tests: + + - Run `npm test --workspace @poe-code/ralph`. + - Update tests that asserted on the local `archivePlan` to assert on + the directory state after archive (file moved to `archive/`, + remaining files renumbered gap-free). + - Existing ralph plan discovery tests should pass with no changes + beyond fixture filename adjustments if any test fixture relied on + flat names — keep flat names; rename happens later. + + Constraints: + - No CLI surface changes. + - The state machine the ralph plans see is the shared-API default. + If any existing ralph test asserted on a specific state machine, + confirm the default has the `archive` event (it does). + status: + implement: open + test: open + commit: open + + - id: experiment-loop-migrate + title: Migrate experiment-loop harness to shared plan API + prompt: | + Switch experiment-loop off its bespoke + `discovery/discovery.ts` onto the shared API. + + In `packages/experiment-loop/src/discovery/discovery.ts`: + + - Replace the body of `discoverExperimentDocs` (the public + function) with a thin call into + `discoverPlans({ cwd, homeDir, planDirectory, kinds: ["experiment"], fs })` + from `@poe-code/agent-harness-tools`. Adapt the return shape (the + existing `Array<{ path; displayPath }>`) from `PlanRef[]`. + - Keep the function signature and exports unchanged so callers are + not touched. + + Confirm `@poe-code/agent-harness-tools` is already a dependency (it + is — experiment-loop imports `discoverWorkflowDocs` from it). No + `package.json` change. + + experiment-loop has no `archivePlan` flow today — leave that alone. + + Tests: + + - Run `npm test --workspace @poe-code/experiment-loop`. + - Existing discovery tests should pass with no changes; if any + relied on a non-`experiment` kind in fixtures, fix the fixture + rather than the test. + + Constraints: + - No CLI surface changes. + - No new dependencies. + status: + implement: open + test: open + commit: open + + - id: superintendent-migrate + title: Migrate superintendent harness to shared plan discovery + prompt: | + Switch the superintendent harness off its local + `discoverSuperintendentDocs` helper onto the shared API. + + In `packages/superintendent/src/commands/run.ts`: + + - Locate `discoverSuperintendentDocs` (around line 830) and the + call site (around line 798). + - Replace the call site's invocation with: + ```ts + import { discoverPlans } from "@poe-code/agent-harness-tools"; + // ... + const docs = await discoverPlans({ + cwd, + homeDir, + planDirectory: planDirectory ?? "docs/plans", + kinds: ["superintendent"], + fs, + }); + ``` + Adapt the consumer code to the `PlanRef[]` shape (the consumer + currently expects `Array<{ path; displayPath }>` — map + `{ path: ref.displayPath, displayPath: ref.displayPath }` if + needed for minimal-touch). + - Delete the local `discoverSuperintendentDocs` function (around + line 830) once the call site is migrated. + + Add `@poe-code/agent-harness-tools` to + `packages/superintendent/package.json` `dependencies` if it is not + already present. + + Superintendent has no `archivePlan` flow — leave the runtime alone. + + Tests: + + - Run `npm test --workspace @poe-code/superintendent`. + - Run `npm run dev -- superintendent --help` to confirm CLI still + boots (no behavior change to output). + + Constraints: + - No CLI flag changes. + - No prompt UX regressions. + status: + implement: open + test: open + commit: open + + - id: rename-plan-files + title: Rename existing plan files with NN- prefixes + prompt: | + One-time migration: rename every active plan file in the three + harness plan directories so each starts with a two-digit order + prefix matching `task-list`'s `markdown-dir` convention. + + Directories to migrate (only if they exist on disk): + + - `docs/plans/` — top-level `*.md` only. Skip subdirectories + `archive/`, `poe-agent/`, `qa/`, `research/` and their contents. + Also skip files with names ending in `.lock`. + - `.poe-code/ralph/plans/` — top-level `*.md` only. Skip `archive/`. + - `.poe-code/experiments/` — top-level `*.md` only. Skip `archive/`. + + Algorithm per directory: + + 1. List top-level markdown files. + 2. Sort alphabetically by the existing filename. + 3. Compute width = max(2, length of decimal count). For ≤99 files + this is `2`. + 4. Rename in order: `01-.md`, `02-.md`, ... + Use `git mv` so history is preserved. + 5. Files already starting with `^\d+-` are skipped (do not double- + prefix). Re-derive their numeric order from the current prefix + and re-pack only if there are gaps; otherwise leave them. + + Do this with a Node script (no bash); commit only the renames, not + the script. Run the script from the repo root. + + Verification: + + - `ls docs/plans/*.md` shows every active plan starts with `NN-`. + - `git status` shows only `R` (rename) entries, no content + modifications. + - Run `npm test --workspaces --if-present` to confirm no test + suite breaks on the renames. + + Constraints: + - No content edits inside any plan file. + - Do not touch the `archive/` directories. + - Do not rename files in `qa/`, `research/`, or `poe-agent/`. + status: + implement: open + commit: open + + - id: cleanup-and-verify + title: Final cleanup — delete dead code and run full test suite + prompt: | + With all four harnesses migrated and plan files renamed, audit the + tree for dead code and verify everything is green. + + Delete or simplify: + + - In `packages/pipeline/src/run/pipeline.ts`, confirm the local + `archivePlan` function is gone. No-op if already deleted. + - In `packages/ralph/src/run/ralph.ts`, confirm the local + `archivePlan` function is gone. + - In `packages/superintendent/src/commands/run.ts`, confirm the + local `discoverSuperintendentDocs` function is gone. + - In `packages/ralph/src/discovery/discovery.ts` and + `packages/experiment-loop/src/discovery/discovery.ts`: if the + files now contain only thin wrappers around `discoverPlans` and + no caller would lose coverage by collapsing them, inline the + single call into the consumer and delete the discovery file. + Otherwise leave the wrapper. + + Run a global grep for orphaned helpers: + + ```bash + git grep -nE "function archivePlan|function discoverSuperintendentDocs|function discoverPipelineDocs|function discoverRalphDocs|function discoverExperimentDocs" + ``` + + The only matches should be type-level imports of the shared + `archivePlan` from `@poe-code/agent-harness-tools`. + + Run the full suite: + + - `npm test` + - `npm run lint:workflows` + - `npm run dev -- pipeline run --plan docs/plans/01-.md --dry-run` + to smoke-test the discovery + archive path on real renamed files. + Pick any pipeline plan that exists post-rename. + + Constraints: + - No content changes to plan files. + - No new dependencies. + - No README additions beyond what was added in the export task. + status: + implement: open + test: open + commit: open +--- + +# Context + +Replace the per-harness plan discovery + archive code with a single shared +`@poe-code/task-list` `markdown-dir` task list, used by experiment-loop, ralph, +pipeline, and superintendent. Archive becomes the `archive` event on the task +lifecycle: the abstraction moves the file under `archive/`, drops its order +prefix, and re-packs the prefixes of the remaining active plans so there are +no gaps. + +## Settled design + +**Mapping.** One mixed list per directory; harnesses filter by +`Task.metadata.kind` (read from each plan's existing YAML frontmatter). The +markdown-dir backend gains a `singleList` mode (root IS the list) and a +`frontmatterMode: "passthrough"` mode (no schema validation; non-recognized +keys flow through to `metadata`). + +**Repack.** `fire(id, "archive")` now calls `rewriteListPrefixes(remainingIds)` +under the list lock after the active file is renamed into `archive/`. Default +on for every consumer of `markdown-dir`. + +**Shared API.** `@poe-code/agent-harness-tools` exports `discoverPlans`, +`archivePlan`, and `openPlanList`. Each harness drops its bespoke discovery +file and local `archivePlan`. + +**Plan-directory defaults per harness:** + +| Harness | Default `planDirectory` | `kinds` filter | +| --------------- | ----------------------- | -------------------- | +| pipeline | `docs/plans` | `["pipeline"]` | +| ralph | `.poe-code/ralph/plans` | `["ralph"]` | +| experiment-loop | `.poe-code/experiments` | `["experiment"]` | +| superintendent | `docs/plans` | `["superintendent"]` | + +**Out of scope.** Replacing the harness-specific plan body parsers (pipeline's +`parsePlan`, superintendent's `parseSuperintendentDoc`); changing default plan +locations; adding `gh-issues` or `yaml-file` to harness discovery; superintendent +archive flow (does not exist today). The `task-list-ordering-and-gh-issues.md` +work runs independently. + +## Order of execution + +Tasks above are listed in dependency order. Run them sequentially. The cleanup +task at the end deletes anything that became dead code and runs the full test +suite plus a smoke run. diff --git a/packages/toolcraft-schema/package.json b/packages/toolcraft-schema/package.json index 1f47edbc21..e9655de251 100644 --- a/packages/toolcraft-schema/package.json +++ b/packages/toolcraft-schema/package.json @@ -12,8 +12,8 @@ }, "scripts": { "build": "rm -rf dist && tsc", - "test": "cd ../.. && vitest run packages/toolcraft-schema/src/index.test.ts", - "test:unit": "cd ../.. && vitest run packages/toolcraft-schema/src/index.test.ts", + "test": "cd ../.. && vitest run packages/toolcraft-schema/src/*.test.ts", + "test:unit": "cd ../.. && vitest run packages/toolcraft-schema/src/*.test.ts", "lint": "cd ../.. && eslint packages/toolcraft-schema/src --ext ts && tsc -p packages/toolcraft-schema/tsconfig.json --noEmit" }, "files": [ diff --git a/packages/toolcraft-schema/src/index.ts b/packages/toolcraft-schema/src/index.ts index 3c9dcc5367..7f1d90ff86 100644 --- a/packages/toolcraft-schema/src/index.ts +++ b/packages/toolcraft-schema/src/index.ts @@ -2,10 +2,12 @@ import { Json } from "./json.js"; import { OneOf } from "./oneof.js"; import { Record as RecordBuilder } from "./record.js"; import { Union } from "./union.js"; +import { validate } from "./validate.js"; import type { JsonValue, JsonValueSchema } from "./json.js"; import type { OneOfSchema } from "./oneof.js"; import type { RecordSchema } from "./record.js"; import type { UnionSchema } from "./union.js"; +import type { ValidationIssue, ValidationResult } from "./validate.js"; type JsonSchemaType = "string" | "number" | "integer" | "boolean" | "array" | "object"; type SchemaKind = @@ -446,5 +448,13 @@ export function toJsonSchema(schema: AnySchema): JsonSchema { } } -export { Json, OneOf, RecordBuilder as Record, Union }; -export type { JsonValue, JsonValueSchema, OneOfSchema, RecordSchema, UnionSchema }; +export { Json, OneOf, RecordBuilder as Record, Union, validate }; +export type { + JsonValue, + JsonValueSchema, + OneOfSchema, + RecordSchema, + UnionSchema, + ValidationIssue, + ValidationResult, +}; diff --git a/packages/toolcraft-schema/src/validate.test.ts b/packages/toolcraft-schema/src/validate.test.ts new file mode 100644 index 0000000000..74ab100250 --- /dev/null +++ b/packages/toolcraft-schema/src/validate.test.ts @@ -0,0 +1,281 @@ +import { describe, expect, expectTypeOf, it } from "vitest"; +import { S, validate } from "toolcraft-schema"; +import type { ValidationResult } from "toolcraft-schema"; + +describe("validate", () => { + it("validates every builder and applies defaults for missing optionals", () => { + const schema = S.Object({ + name: S.String({ minLength: 2 }), + count: S.Optional(S.Number({ default: 3, minimum: 1 })), + enabled: S.Boolean(), + role: S.Enum(["admin", "user"] as const), + tags: S.Array(S.String(), { minItems: 1 }), + settings: S.Record(S.Boolean()), + payload: S.Json(), + omitted: S.Optional(S.String()) + }); + + const result = validate(schema, { + name: "Ada", + enabled: true, + role: "admin", + tags: ["core"], + settings: { verbose: false }, + payload: { nested: [1, "two", null] } + }); + + expect(result).toEqual({ + ok: true, + value: { + name: "Ada", + count: 3, + enabled: true, + role: "admin", + tags: ["core"], + settings: { verbose: false }, + payload: { nested: [1, "two", null] } + } + }); + expectTypeOf(result).toMatchTypeOf< + ValidationResult<{ + name: string; + count?: number; + enabled: boolean; + role: "admin" | "user"; + tags: string[]; + settings: Record; + payload: string | number | boolean | null | { [key: string]: unknown } | unknown[]; + omitted?: string; + }> + >(); + }); + + it("validates oneOf and union schemas", () => { + const oneOfSchema = S.OneOf({ + discriminator: "kind", + branches: { + text: S.Object({ value: S.String() }), + count: S.Object({ value: S.Number() }) + } + }); + const unionSchema = S.Union([ + S.Object({ email: S.String() }), + S.Object({ phone: S.String(), extension: S.Optional(S.Number({ default: 100 })) }) + ]); + + expect(validate(oneOfSchema, { kind: "text", value: "hello" })).toEqual({ + ok: true, + value: { kind: "text", value: "hello" } + }); + expect(validate(unionSchema, { phone: "555-0100" })).toEqual({ + ok: true, + value: { phone: "555-0100", extension: 100 } + }); + expect(validate(unionSchema, { email: 12 })).toEqual({ + ok: false, + issues: [ + { + path: ["email"], + expected: "string", + received: "integer", + message: "Expected string at email" + } + ] + }); + }); + + it("omits missing optionals without defaults", () => { + const schema = S.Object({ + required: S.String(), + maybe: S.Optional(S.Boolean()), + fallback: S.Optional(S.String({ default: "defaulted" })) + }); + + expect(validate(schema, { required: "value" })).toEqual({ + ok: true, + value: { + required: "value", + fallback: "defaulted" + } + }); + expect(validate(S.Optional(S.String()), undefined)).toEqual({ + ok: true, + value: undefined + }); + }); + + it("accumulates nested issues and rejects additional object properties", () => { + const schema = S.Object({ + user: S.Object({ + name: S.String({ minLength: 3 }), + retries: S.Number({ minimum: 1 }), + tags: S.Array(S.String(), { minItems: 2 }), + mode: S.Enum(["fast", "safe"] as const) + }) + }); + + const result = validate(schema, { + user: { + name: "Al", + retries: 0, + tags: [], + mode: "slow", + extra: true + }, + rootExtra: 1 + }); + + expect(result).toEqual({ + ok: false, + issues: [ + { + path: ["user", "name"], + expected: "string with length at least 3", + received: "string with length 2", + message: "Expected string with length at least 3 at user.name" + }, + { + path: ["user", "retries"], + expected: "number greater than or equal to 1", + received: "0", + message: "Expected number greater than or equal to 1 at user.retries" + }, + { + path: ["user", "tags"], + expected: "array with at least 2 items", + received: "array with 0 items", + message: "Expected array with at least 2 items at user.tags" + }, + { + path: ["user", "mode"], + expected: "one of fast, safe", + received: "slow", + message: "Expected one of fast, safe at user.mode" + }, + { + path: ["user", "extra"], + expected: "no additional properties", + received: "unknown property", + message: "Unexpected property user.extra" + }, + { + path: ["rootExtra"], + expected: "no additional properties", + received: "unknown property", + message: "Unexpected property rootExtra" + } + ] + }); + }); + + it("returns all item and record value issues", () => { + const schema = S.Object({ + items: S.Array(S.Number({ minimum: 10 })), + flags: S.Record(S.Boolean()) + }); + + expect(validate(schema, { items: [1, "two"], flags: { ok: true, bad: "no" } })).toEqual({ + ok: false, + issues: [ + { + path: ["items", "0"], + expected: "number greater than or equal to 10", + received: "1", + message: "Expected number greater than or equal to 10 at items.0" + }, + { + path: ["items", "1"], + expected: "number", + received: "string", + message: "Expected number at items.1" + }, + { + path: ["flags", "bad"], + expected: "boolean", + received: "string", + message: "Expected boolean at flags.bad" + } + ] + }); + }); + + it("enforces upper bounds and string patterns", () => { + const schema = S.Object({ + code: S.String({ maxLength: 4, pattern: "^[A-Z]+$" }), + score: S.Number({ maximum: 5 }), + values: S.Array(S.Boolean(), { maxItems: 1 }) + }); + + expect(validate(schema, { code: "abcde", score: 6, values: [true, false] })).toEqual({ + ok: false, + issues: [ + { + path: ["code"], + expected: "string with length at most 4", + received: "string with length 5", + message: "Expected string with length at most 4 at code" + }, + { + path: ["code"], + expected: "string matching pattern ^[A-Z]+$", + received: "abcde", + message: "Expected string matching pattern ^[A-Z]+$ at code" + }, + { + path: ["score"], + expected: "number less than or equal to 5", + received: "6", + message: "Expected number less than or equal to 5 at score" + }, + { + path: ["values"], + expected: "array with at most 1 items", + received: "array with 2 items", + message: "Expected array with at most 1 items at values" + } + ] + }); + }); + + it("preserves additional object properties when the object schema allows them", () => { + const schema = S.Object( + { + name: S.String() + }, + { additionalProperties: true } + ); + + expect(validate(schema, { name: "Ada", title: "engineer" })).toEqual({ + ok: true, + value: { + name: "Ada", + title: "engineer" + } + }); + }); + + it("reports missing required values and invalid JSON payloads without throwing", () => { + const schema = S.Object({ + required: S.String(), + payload: S.Json() + }); + + expect(validate(schema, { payload: { bad: undefined } })).toEqual({ + ok: false, + issues: [ + { + path: ["required"], + expected: "string", + received: "missing", + message: "Expected string at required" + }, + { + path: ["payload"], + expected: "JSON value", + received: "object", + message: "Expected JSON value at payload" + } + ] + }); + }); +}); diff --git a/packages/toolcraft-schema/src/validate.ts b/packages/toolcraft-schema/src/validate.ts new file mode 100644 index 0000000000..bd623fba41 --- /dev/null +++ b/packages/toolcraft-schema/src/validate.ts @@ -0,0 +1,562 @@ +import type { AnySchema, ObjectSchema, OptionalSchema, Static } from "./index.js"; + +export type SchemaDescriptor = AnySchema; + +export type ValidationIssue = { + path: readonly string[]; + expected: string; + received: string; + message: string; +}; + +export type ValidationResult = + | { ok: true; value: T } + | { ok: false; issues: readonly ValidationIssue[] }; + +type ValidationState = { + issues: ValidationIssue[]; +}; + +type WalkResult = { present: true; value: unknown } | { present: false }; + +const missingValue = Symbol("missingValue"); + +export function validate( + schema: S, + value: unknown +): ValidationResult> { + const state: ValidationState = { issues: [] }; + const result = walkSchema(schema, value, [], state); + + if (state.issues.length > 0) { + return { ok: false, issues: state.issues }; + } + + return { ok: true, value: (result.present ? result.value : undefined) as Static }; +} + +function walkSchema( + schema: AnySchema, + value: unknown | typeof missingValue, + path: readonly string[], + state: ValidationState +): WalkResult { + if (schema.kind === "optional") { + return walkOptional(schema, value, path, state); + } + + if (value === missingValue) { + addIssue( + state, + path, + expectedFor(schema), + "missing", + `Expected ${expectedFor(schema)} at ${formatPath(path)}` + ); + return { present: false }; + } + + if (value === null && schema.nullable === true) { + return { present: true, value }; + } + + switch (schema.kind) { + case "string": + return walkString(schema, value, path, state); + + case "number": + return walkNumber(schema, value, path, state); + + case "boolean": + return walkBoolean(value, path, state); + + case "enum": + return walkEnum(schema, value, path, state); + + case "array": + return walkArray(schema, value, path, state); + + case "object": + return walkObject(schema, value, path, state); + + case "oneOf": + return walkOneOf(schema, value, path, state); + + case "union": + return walkUnion(schema, value, path, state); + + case "record": + return walkRecord(schema, value, path, state); + + case "json": + return walkJson(value, path, state); + } +} + +function walkOptional( + schema: OptionalSchema, + value: unknown | typeof missingValue, + path: readonly string[], + state: ValidationState +): WalkResult { + if (value === missingValue || value === undefined) { + const defaultValue = getDefault(schema.inner); + + if (defaultValue.present) { + return { present: true, value: defaultValue.value }; + } + + return { present: false }; + } + + return walkSchema(schema.inner, value, path, state); +} + +function walkString( + schema: Extract, + value: unknown, + path: readonly string[], + state: ValidationState +): WalkResult { + if (typeof value !== "string") { + addExpectedIssue(state, path, "string", value); + return { present: true, value }; + } + + if (schema.minLength !== undefined && value.length < schema.minLength) { + const expected = `string with length at least ${schema.minLength}`; + addIssue( + state, + path, + expected, + `string with length ${value.length}`, + `Expected ${expected} at ${formatPath(path)}` + ); + } + + if (schema.maxLength !== undefined && value.length > schema.maxLength) { + const expected = `string with length at most ${schema.maxLength}`; + addIssue( + state, + path, + expected, + `string with length ${value.length}`, + `Expected ${expected} at ${formatPath(path)}` + ); + } + + if (schema.pattern !== undefined) { + const pattern = compilePattern(schema.pattern); + + if (pattern === undefined || !pattern.test(value)) { + const expected = `string matching pattern ${schema.pattern}`; + addIssue(state, path, expected, value, `Expected ${expected} at ${formatPath(path)}`); + } + } + + return { present: true, value }; +} + +function walkNumber( + schema: Extract, + value: unknown, + path: readonly string[], + state: ValidationState +): WalkResult { + if (typeof value !== "number" || Number.isNaN(value)) { + addExpectedIssue(state, path, schema.jsonType === "integer" ? "integer" : "number", value); + return { present: true, value }; + } + + if (schema.jsonType === "integer" && !Number.isInteger(value)) { + addExpectedIssue(state, path, "integer", value); + } + + if (schema.minimum !== undefined && value < schema.minimum) { + const expected = `number greater than or equal to ${schema.minimum}`; + addIssue(state, path, expected, String(value), `Expected ${expected} at ${formatPath(path)}`); + } + + if (schema.maximum !== undefined && value > schema.maximum) { + const expected = `number less than or equal to ${schema.maximum}`; + addIssue(state, path, expected, String(value), `Expected ${expected} at ${formatPath(path)}`); + } + + return { present: true, value }; +} + +function walkBoolean(value: unknown, path: readonly string[], state: ValidationState): WalkResult { + if (typeof value !== "boolean") { + addExpectedIssue(state, path, "boolean", value); + } + + return { present: true, value }; +} + +function walkEnum( + schema: Extract, + value: unknown, + path: readonly string[], + state: ValidationState +): WalkResult { + if (!schema.values.includes(value as never)) { + const expected = `one of ${schema.values.join(", ")}`; + addIssue( + state, + path, + expected, + receivedValue(value), + `Expected ${expected} at ${formatPath(path)}` + ); + } + + return { present: true, value }; +} + +function walkArray( + schema: Extract, + value: unknown, + path: readonly string[], + state: ValidationState +): WalkResult { + if (!Array.isArray(value)) { + addExpectedIssue(state, path, "array", value); + return { present: true, value }; + } + + if (schema.minItems !== undefined && value.length < schema.minItems) { + const expected = `array with at least ${schema.minItems} items`; + addIssue( + state, + path, + expected, + `array with ${value.length} items`, + `Expected ${expected} at ${formatPath(path)}` + ); + } + + if (schema.maxItems !== undefined && value.length > schema.maxItems) { + const expected = `array with at most ${schema.maxItems} items`; + addIssue( + state, + path, + expected, + `array with ${value.length} items`, + `Expected ${expected} at ${formatPath(path)}` + ); + } + + const nextValue = value.map((item, index) => { + const result = walkSchema(schema.item, item, [...path, String(index)], state); + + return result.present ? result.value : item; + }); + + return { present: true, value: nextValue }; +} + +function walkObject( + schema: ObjectSchema, + value: unknown, + path: readonly string[], + state: ValidationState, + injectedProperties: Record = {} +): WalkResult { + if (!isPlainRecord(value)) { + addExpectedIssue(state, path, "object", value); + return { present: true, value }; + } + + const nextValue: Record = {}; + const allowedKeys = new Set([...Object.keys(schema.shape), ...Object.keys(injectedProperties)]); + + for (const [key, propertySchema] of Object.entries(schema.shape) as Array<[string, AnySchema]>) { + const propertyValue = Object.hasOwn(value, key) ? value[key] : missingValue; + const result = walkSchema(propertySchema, propertyValue, [...path, key], state); + + if (result.present) { + nextValue[key] = result.value; + } + } + + for (const [key, injectedValue] of Object.entries(injectedProperties)) { + if (Object.hasOwn(value, key)) { + nextValue[key] = value[key]; + } else { + nextValue[key] = injectedValue; + } + } + + for (const [key, propertyValue] of Object.entries(value)) { + if (allowedKeys.has(key)) { + continue; + } + + if (schema.additionalProperties === true) { + nextValue[key] = propertyValue; + } else { + addUnexpectedPropertyIssue(state, [...path, key]); + } + } + + return { present: true, value: nextValue }; +} + +function walkOneOf( + schema: Extract, + value: unknown, + path: readonly string[], + state: ValidationState +): WalkResult { + if (!isPlainRecord(value)) { + addExpectedIssue(state, path, "object", value); + return { present: true, value }; + } + + const discriminatorValue = value[schema.discriminator]; + + if ( + typeof discriminatorValue !== "string" || + !Object.hasOwn(schema.branches, discriminatorValue) + ) { + const discriminatorPath = [...path, schema.discriminator]; + const expected = `one of ${Object.keys(schema.branches).join(", ")}`; + addIssue( + state, + discriminatorPath, + expected, + receivedValue(discriminatorValue), + `Expected ${expected} at ${formatPath(discriminatorPath)}` + ); + return { present: true, value }; + } + + return walkObject(schema.branches[discriminatorValue], value, path, state, { + [schema.discriminator]: discriminatorValue + }); +} + +function walkUnion( + schema: Extract, + value: unknown, + path: readonly string[], + state: ValidationState +): WalkResult { + if (isPlainRecord(value)) { + const candidateBranches = schema.branches.filter((branch) => hasRequiredKeys(branch, value)); + + if (candidateBranches.length === 1) { + return walkObject(candidateBranches[0], value, path, state); + } + } + + const matches: unknown[] = []; + + for (const branch of schema.branches) { + const branchState: ValidationState = { issues: [] }; + const result = walkObject(branch, value, path, branchState); + + if (branchState.issues.length === 0 && result.present) { + matches.push(result.value); + } + } + + if (matches.length === 1) { + return { present: true, value: matches[0] }; + } + + addIssue( + state, + path, + "exactly one union branch", + matches.length === 0 ? "no matching branches" : `${matches.length} matching branches`, + `Expected exactly one union branch at ${formatPath(path)}` + ); + return { present: true, value }; +} + +function hasRequiredKeys(schema: ObjectSchema, value: Record): boolean { + for (const [key, propertySchema] of Object.entries(schema.shape) as Array<[string, AnySchema]>) { + if (propertySchema.kind !== "optional" && !Object.hasOwn(value, key)) { + return false; + } + } + + return true; +} + +function walkRecord( + schema: Extract, + value: unknown, + path: readonly string[], + state: ValidationState +): WalkResult { + if (!isPlainRecord(value)) { + addExpectedIssue(state, path, "object", value); + return { present: true, value }; + } + + const nextValue: Record = {}; + + for (const [key, propertyValue] of Object.entries(value)) { + const result = walkSchema(schema.value, propertyValue, [...path, key], state); + + if (result.present) { + nextValue[key] = result.value; + } + } + + return { present: true, value: nextValue }; +} + +function walkJson(value: unknown, path: readonly string[], state: ValidationState): WalkResult { + if (isJsonValue(value)) { + return { present: true, value }; + } + + addExpectedIssue(state, path, "JSON value", value); + return { present: true, value }; +} + +function getDefault(schema: AnySchema): WalkResult { + if (schema.default !== undefined) { + return { present: true, value: schema.default }; + } + + if (schema.kind === "optional") { + return getDefault(schema.inner); + } + + return { present: false }; +} + +function isPlainRecord(value: unknown): value is Record { + if (typeof value !== "object" || value === null || Array.isArray(value)) { + return false; + } + + const prototype = Object.getPrototypeOf(value); + + return prototype === Object.prototype || prototype === null; +} + +function isJsonValue(value: unknown): boolean { + if ( + value === null || + typeof value === "string" || + typeof value === "number" || + typeof value === "boolean" + ) { + return typeof value !== "number" || Number.isFinite(value); + } + + if (Array.isArray(value)) { + return value.every((item) => isJsonValue(item)); + } + + if (isPlainRecord(value)) { + return Object.values(value).every((item) => isJsonValue(item)); + } + + return false; +} + +function expectedFor(schema: AnySchema): string { + switch (schema.kind) { + case "string": + return "string"; + case "number": + return schema.jsonType === "integer" ? "integer" : "number"; + case "boolean": + return "boolean"; + case "enum": + return `one of ${schema.values.join(", ")}`; + case "array": + return "array"; + case "object": + case "oneOf": + case "record": + return "object"; + case "union": + return "exactly one union branch"; + case "json": + return "JSON value"; + case "optional": + return expectedFor(schema.inner); + } +} + +function addExpectedIssue( + state: ValidationState, + path: readonly string[], + expected: string, + value: unknown +): void { + addIssue( + state, + path, + expected, + receivedType(value), + `Expected ${expected} at ${formatPath(path)}` + ); +} + +function addUnexpectedPropertyIssue(state: ValidationState, path: readonly string[]): void { + addIssue( + state, + path, + "no additional properties", + "unknown property", + `Unexpected property ${formatPath(path)}` + ); +} + +function addIssue( + state: ValidationState, + path: readonly string[], + expected: string, + received: string, + message: string +): void { + state.issues.push({ path, expected, received, message }); +} + +function formatPath(path: readonly string[]): string { + return path.length === 0 ? "value" : path.join("."); +} + +function compilePattern(pattern: string): RegExp | undefined { + try { + return new RegExp(pattern); + } catch { + return undefined; + } +} + +function receivedType(value: unknown): string { + if (value === null) { + return "null"; + } + + if (Array.isArray(value)) { + return "array"; + } + + if (typeof value === "number" && Number.isInteger(value)) { + return "integer"; + } + + return typeof value; +} + +function receivedValue(value: unknown): string { + if (typeof value === "string") { + return value; + } + + if (value === undefined) { + return "undefined"; + } + + return String(value); +} From 1e6169cbed26f1af4631073f9b22eef677b04945 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 23:06:57 -0500 Subject: [PATCH 044/111] feat(agent-script): parse module exports --- docs/plans/agent-harness.md | 4 +- docs/plans/agent-harness.md.lock | 1 + packages/agent-script/src/parse.ts | 2 + .../src/parse/parse-export.test.ts | 111 ++++++++++++++++++ .../agent-script/src/parse/parse-export.ts | 45 +++++++ packages/agent-script/src/parse/parser.ts | 91 +++++++++++++- 6 files changed, 248 insertions(+), 6 deletions(-) create mode 100644 docs/plans/agent-harness.md.lock create mode 100644 packages/agent-script/src/parse/parse-export.test.ts create mode 100644 packages/agent-script/src/parse/parse-export.ts diff --git a/docs/plans/agent-harness.md b/docs/plans/agent-harness.md index f28dfeb064..59a4c970a3 100644 --- a/docs/plans/agent-harness.md +++ b/docs/plans/agent-harness.md @@ -83,8 +83,8 @@ tasks: Do not change runtime semantics yet; just parsing + AST. status: - implement: open - test: open + implement: done + test: done commit: open - id: agent-script-import-meta-parser diff --git a/docs/plans/agent-harness.md.lock b/docs/plans/agent-harness.md.lock new file mode 100644 index 0000000000..6b9c0e90c1 --- /dev/null +++ b/docs/plans/agent-harness.md.lock @@ -0,0 +1 @@ +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T04:06:09.074Z"} \ No newline at end of file diff --git a/packages/agent-script/src/parse.ts b/packages/agent-script/src/parse.ts index 47a78565ca..d913a8a6b6 100644 --- a/packages/agent-script/src/parse.ts +++ b/packages/agent-script/src/parse.ts @@ -17,6 +17,8 @@ export type { ContinueStatement, Expression, ExpressionStatement, + ExportDefaultDeclaration, + ExportNamedDeclaration, ImportDeclaration, ImportDefaultSpecifier, ImportNamespaceSpecifier, diff --git a/packages/agent-script/src/parse/parse-export.test.ts b/packages/agent-script/src/parse/parse-export.test.ts new file mode 100644 index 0000000000..2ba963125d --- /dev/null +++ b/packages/agent-script/src/parse/parse-export.test.ts @@ -0,0 +1,111 @@ +import { describe, expect, it } from "vitest"; + +import { DisallowedSyntaxError, parse, parseModule } from "./parser.js"; + +describe("parse exports", () => { + it("parses supported top-level export declarations in modules", () => { + expect(parseModule("export const x = 1").body[0]).toMatchObject({ + type: "ExportNamedDeclaration", + declaration: { + type: "VariableDeclaration", + kind: "const", + declarations: [ + { + type: "VariableDeclarator", + id: { + type: "Identifier", + name: "x" + }, + init: { + type: "NumericLiteral", + value: 1 + } + } + ] + } + }); + + expect(parseModule("export const schema = S.Object({})").body[0]).toMatchObject({ + type: "ExportNamedDeclaration", + declaration: { + type: "VariableDeclaration", + kind: "const", + declarations: [ + { + type: "VariableDeclarator", + id: { + type: "Identifier", + name: "schema" + }, + init: { + type: "CallExpression" + } + } + ] + } + }); + + expect(parseModule("export default async () => 1").body[0]).toMatchObject({ + type: "ExportDefaultDeclaration", + declaration: { + type: "ArrowFunctionExpression", + async: true, + expression: true + } + }); + + expect(parseModule("export default () => {}").body[0]).toMatchObject({ + type: "ExportDefaultDeclaration", + declaration: { + type: "ArrowFunctionExpression", + async: false, + expression: false + } + }); + + expect(parseModule("export default async x => x").body[0]).toMatchObject({ + type: "ExportDefaultDeclaration", + declaration: { + type: "ArrowFunctionExpression", + async: true, + expression: true, + params: [ + { + type: "Identifier", + name: "x" + } + ] + } + }); + }); + + it("rejects unsupported export declarations", () => { + expect(() => parseModule("export function run() {}")).toThrowError(DisallowedSyntaxError); + expect(() => parseModule("export class Run {}")).toThrowError(DisallowedSyntaxError); + expect(() => parseModule('export * from "tool"')).toThrowError(DisallowedSyntaxError); + expect(() => parseModule("export { x }")).toThrowError(DisallowedSyntaxError); + expect(() => parseModule("export default function () {}")).toThrowError(DisallowedSyntaxError); + expect(() => parseModule("export default class Run {}")).toThrowError(DisallowedSyntaxError); + expect(() => parseModule("export default 1")).toThrowError(DisallowedSyntaxError); + expect(() => parseModule("export const a = 1, b = 2")).toThrowError(DisallowedSyntaxError); + expect(() => parseModule("export const { x } = value")).toThrowError(DisallowedSyntaxError); + expect(() => parseModule("export const [x] = value")).toThrowError(DisallowedSyntaxError); + expect(() => parseModule("export let x = 1")).toThrowError(DisallowedSyntaxError); + }); + + it("rejects duplicate default exports in the same module", () => { + expect(() => parseModule("export default () => 1; export default () => 2")).toThrowError( + DisallowedSyntaxError + ); + }); + + it("rejects exports outside module top level", () => { + expect(() => parse("export const x = 1")).toThrowError(DisallowedSyntaxError); + expect(() => parseModule("if (ready) { export const x = 1 }")).toThrowError( + DisallowedSyntaxError + ); + expect(() => parseModule("const run = () => { export const x = 1 }")).toThrowError( + DisallowedSyntaxError + ); + }); +}); diff --git a/packages/agent-script/src/parse/parse-export.ts b/packages/agent-script/src/parse/parse-export.ts new file mode 100644 index 0000000000..e06879857d --- /dev/null +++ b/packages/agent-script/src/parse/parse-export.ts @@ -0,0 +1,45 @@ +import type { Token } from "./tokenizer.js"; +import type { ArrowFunctionExpression, SourceSpan, VariableDeclaration } from "./parser.js"; + +export type ExportNamedDeclaration = { + nodeId?: number; + type: "ExportNamedDeclaration"; + declaration: VariableDeclaration; + span: SourceSpan; +}; + +export type ExportDefaultDeclaration = { + nodeId?: number; + type: "ExportDefaultDeclaration"; + declaration: ArrowFunctionExpression; + span: SourceSpan; +}; + +export function createExportNamedDeclaration( + exportToken: Token, + declaration: VariableDeclaration +): ExportNamedDeclaration { + return { + type: "ExportNamedDeclaration", + declaration, + span: createSpan(exportToken.start, declaration.span.end) + }; +} + +export function createExportDefaultDeclaration( + exportToken: Token, + declaration: ArrowFunctionExpression +): ExportDefaultDeclaration { + return { + type: "ExportDefaultDeclaration", + declaration, + span: createSpan(exportToken.start, declaration.span.end) + }; +} + +function createSpan(start: SourceSpan["start"], end: SourceSpan["end"]): SourceSpan { + return { + start: { ...start }, + end: { ...end } + }; +} diff --git a/packages/agent-script/src/parse/parser.ts b/packages/agent-script/src/parse/parser.ts index d2f568c3b2..5270f88a75 100644 --- a/packages/agent-script/src/parse/parser.ts +++ b/packages/agent-script/src/parse/parser.ts @@ -1,6 +1,14 @@ import { tokenize, type Position, type Token } from "./tokenizer.js"; import { assignIds } from "./assign-ids.js"; import { formatParseError } from "./format-error.js"; +import { + createExportDefaultDeclaration, + createExportNamedDeclaration, + type ExportDefaultDeclaration, + type ExportNamedDeclaration +} from "./parse-export.js"; + +export type { ExportDefaultDeclaration, ExportNamedDeclaration } from "./parse-export.js"; export type SourceSpan = { start: Position; @@ -324,6 +332,8 @@ export type Module = BaseNode & { export type Statement = | BlockStatement | BreakStatement + | ExportDefaultDeclaration + | ExportNamedDeclaration | ImportDeclaration | TryStatement | ContinueStatement @@ -443,11 +453,18 @@ function parseExpressionTokens(tokens: Token[]): Expression { class Parser { private index = 0; + private hasDefaultExport = false; constructor(private readonly tokens: Token[]) {} parseTopLevel(): ParseResult { - const node = this.shouldParseTopLevelStatement() ? this.parseStatement() : this.parseExpression().node; + if (this.isExportToken(this.currentToken())) { + throw new DisallowedSyntaxError("export", this.currentToken().start); + } + + const node = this.shouldParseTopLevelStatement() + ? this.parseStatement() + : this.parseExpression().node; while (this.consumePunctuator(";") !== undefined) { continue; } @@ -483,6 +500,10 @@ class Parser { } private parseTopLevelItem(): Statement { + if (this.isExportToken(this.currentToken())) { + return this.parseExportDeclaration(); + } + if (this.shouldParseTopLevelStatement()) { return this.parseStatement(); } @@ -979,6 +1000,51 @@ class Parser { return specifiers; } + private parseExportDeclaration(): ExportDefaultDeclaration | ExportNamedDeclaration { + const exportToken = this.currentToken(); + if (!this.isExportToken(exportToken)) { + throw unexpectedTokenError(exportToken); + } + + this.index += 1; + + if (this.currentToken().value === "default") { + return this.parseExportDefaultDeclaration(exportToken); + } + + if (this.currentToken().type === "keyword" && this.currentToken().value === "const") { + return this.parseExportNamedDeclaration(exportToken); + } + + throw new DisallowedSyntaxError(`export ${this.currentToken().value}`, exportToken.start); + } + + private parseExportNamedDeclaration(exportToken: Token): ExportNamedDeclaration { + const declaration = this.parseVariableDeclaration({ singleDeclaratorSyntax: "export const" }); + const declarator = declaration.declarations[0]!; + if (declarator.id.type !== "Identifier") { + throw new DisallowedSyntaxError("export const", declarator.id.span.start); + } + + return createExportNamedDeclaration(exportToken, declaration); + } + + private parseExportDefaultDeclaration(exportToken: Token): ExportDefaultDeclaration { + this.index += 1; + + if (this.hasDefaultExport) { + throw new DisallowedSyntaxError("export default", exportToken.start); + } + + const declaration = this.tryParseArrowFunctionExpression(); + if (declaration === undefined) { + throw new DisallowedSyntaxError("export default", this.currentToken().start); + } + + this.hasDefaultExport = true; + return createExportDefaultDeclaration(exportToken, declaration); + } + private parseCatchClause(): CatchClause { const catchToken = this.expectKeyword("catch"); let param: ArrayPattern | Identifier | ObjectPattern | undefined; @@ -995,9 +1061,14 @@ class Parser { }; } - private parseVariableDeclaration(): VariableDeclaration { + private parseVariableDeclaration( + options: { singleDeclaratorSyntax?: string } = {} + ): VariableDeclaration { const kindToken = this.currentToken(); - if (kindToken.type !== "keyword" || (kindToken.value !== "const" && kindToken.value !== "let")) { + if ( + kindToken.type !== "keyword" || + (kindToken.value !== "const" && kindToken.value !== "let") + ) { throw unexpectedTokenError(kindToken); } @@ -1006,9 +1077,13 @@ class Parser { while (true) { declarations.push(this.parseVariableDeclarator(kindToken.value)); - if (this.consumePunctuator(",") === undefined) { + const comma = this.consumePunctuator(","); + if (comma === undefined) { break; } + if (options.singleDeclaratorSyntax !== undefined) { + throw new DisallowedSyntaxError(options.singleDeclaratorSyntax, comma.start); + } } return { @@ -2516,6 +2591,10 @@ class Parser { } private assertAllowedStatementStart(token: Token): void { + if (this.isExportToken(token)) { + throw new DisallowedSyntaxError("export", token.start); + } + if (token.type === "identifier" && token.value === "do") { throw new DisallowedSyntaxError("do/while", token.start); } @@ -2596,6 +2675,10 @@ class Parser { private previousToken(): Token { return this.tokens[this.index - 1] ?? this.tokens[0]; } + + private isExportToken(token: Token): boolean { + return token.value === "export"; + } } function createIdentifier(token: Token): Identifier { From c619bd9600cbf7cf927d55c1b81516d2964dd66a Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 23:12:01 -0500 Subject: [PATCH 045/111] feat(agent-script): parse import meta --- docs/plans/agent-harness.md | 8 +- docs/plans/agent-harness.md.lock | 2 +- packages/agent-script/src/parse.ts | 1 + .../src/parse/parse-import-meta.ts | 40 ++++++++ .../agent-script/src/parse/parser.test.ts | 92 +++++++++++++++++++ packages/agent-script/src/parse/parser.ts | 52 ++++++++++- 6 files changed, 189 insertions(+), 6 deletions(-) create mode 100644 packages/agent-script/src/parse/parse-import-meta.ts diff --git a/docs/plans/agent-harness.md b/docs/plans/agent-harness.md index 59a4c970a3..d867722447 100644 --- a/docs/plans/agent-harness.md +++ b/docs/plans/agent-harness.md @@ -85,7 +85,7 @@ tasks: status: implement: done test: done - commit: open + commit: done - id: agent-script-import-meta-parser title: Parse `import.meta` as a MetaProperty expression in agent-script @@ -117,9 +117,9 @@ tasks: Do not wire runtime resolution yet — that's a later task. status: - implement: open - test: open - commit: open + implement: done + test: done + commit: done - id: agent-script-export-lint title: Lint rules for export forms and import.meta in agent-script diff --git a/docs/plans/agent-harness.md.lock b/docs/plans/agent-harness.md.lock index 6b9c0e90c1..272a95e7da 100644 --- a/docs/plans/agent-harness.md.lock +++ b/docs/plans/agent-harness.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T04:06:09.074Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T04:11:06.130Z"} \ No newline at end of file diff --git a/packages/agent-script/src/parse.ts b/packages/agent-script/src/parse.ts index d913a8a6b6..0aa3040829 100644 --- a/packages/agent-script/src/parse.ts +++ b/packages/agent-script/src/parse.ts @@ -29,6 +29,7 @@ export type { IfStatement, LogicalExpression, MemberExpression, + MetaProperty, NullLiteral, NumericLiteral, ObjectExpression, diff --git a/packages/agent-script/src/parse/parse-import-meta.ts b/packages/agent-script/src/parse/parse-import-meta.ts new file mode 100644 index 0000000000..d4d9c8d060 --- /dev/null +++ b/packages/agent-script/src/parse/parse-import-meta.ts @@ -0,0 +1,40 @@ +import type { Token } from "./tokenizer.js"; +import type { Identifier, MetaProperty } from "./parser.js"; + +export function isImportMetaTokenSequence( + importToken: Token, + dotToken: Token, + metaToken: Token +): boolean { + return ( + importToken.type === "keyword" && + importToken.value === "import" && + dotToken.type === "punctuator" && + dotToken.value === "." && + metaToken.type === "identifier" && + metaToken.value === "meta" + ); +} + +export function createImportMeta(importToken: Token, metaToken: Token): MetaProperty { + return { + type: "MetaProperty", + meta: createIdentifier(importToken, "import"), + property: createIdentifier(metaToken, "meta"), + span: { + start: importToken.start, + end: metaToken.end + } + }; +} + +function createIdentifier(token: Token, name: TName): Identifier & { name: TName } { + return { + type: "Identifier", + name, + span: { + start: token.start, + end: token.end + } + }; +} diff --git a/packages/agent-script/src/parse/parser.test.ts b/packages/agent-script/src/parse/parser.test.ts index 2bab0a5810..bf1903c994 100644 --- a/packages/agent-script/src/parse/parser.test.ts +++ b/packages/agent-script/src/parse/parser.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "vitest"; import { DisallowedSyntaxError, parse } from "../parse.js"; +import { parseModule } from "./parser.js"; describe("parse", () => { it("tracks closing delimiters in empty arrays and objects", () => { @@ -1505,6 +1506,82 @@ describe("parse", () => { }); }); + it("parses import.meta as a standard expression", () => { + expect(parse("import.meta")).toMatchObject({ + type: "MetaProperty", + meta: { + type: "Identifier", + name: "import" + }, + property: { + type: "Identifier", + name: "meta" + } + }); + + expect(parse("import.meta.body")).toMatchObject({ + type: "MemberExpression", + object: { + type: "MetaProperty" + }, + property: { + type: "Identifier", + name: "body" + } + }); + + expect(parse("const { body } = import.meta")).toMatchObject({ + type: "VariableDeclaration", + declarations: [ + { + id: { + type: "ObjectPattern" + }, + init: { + type: "MetaProperty" + } + } + ] + }); + + expect(parseModule("const m = import.meta; m.body")).toMatchObject({ + type: "Module", + body: [ + { + type: "VariableDeclaration", + declarations: [ + { + init: { + type: "MetaProperty" + } + } + ] + }, + { + type: "ExpressionStatement", + expression: { + type: "MemberExpression", + object: { + type: "Identifier", + name: "m" + }, + property: { + type: "Identifier", + name: "body" + } + } + } + ] + }); + + expect(parse("import.meta()")).toMatchObject({ + type: "CallExpression", + callee: { + type: "MetaProperty" + } + }); + }); + it("parses array pattern elisions across declarations, params, and assignments", () => { expect(parse("const [, second = fallback, ...rest] = values")).toMatchObject({ type: "VariableDeclaration", @@ -2103,6 +2180,21 @@ describe("parse", () => { }); }); + it("rejects assignments to import.meta and its properties", () => { + expect(() => parse("import.meta = x")).toThrowError(DisallowedSyntaxError); + expect(() => parse("import.meta.x = 1")).toThrowError(DisallowedSyntaxError); + expect(() => parse("[import.meta] = [x]")).toThrowError(DisallowedSyntaxError); + }); + + it("rejects assignments to import.meta through parenthesized, computed, and nested targets", () => { + expect(() => parse("(import.meta) = x")).toThrowError(DisallowedSyntaxError); + expect(() => parse("(import.meta.x) = 1")).toThrowError(DisallowedSyntaxError); + expect(() => parse("import.meta[key] = 1")).toThrowError(DisallowedSyntaxError); + expect(() => parse("[import.meta.x] = [x]")).toThrowError(DisallowedSyntaxError); + expect(() => parse("({ body: import.meta } = x)")).toThrowError(DisallowedSyntaxError); + expect(() => parse("for (import.meta of xs) {}")).toThrowError(DisallowedSyntaxError); + }); + it("rejects disallowed statement syntax", () => { expect(() => parse("() => { do { work(); } while (ready); }")).toThrowError(DisallowedSyntaxError); expect(() => parse("() => { do { work(); } while (ready); }")).toThrowError( diff --git a/packages/agent-script/src/parse/parser.ts b/packages/agent-script/src/parse/parser.ts index 5270f88a75..d6079880a9 100644 --- a/packages/agent-script/src/parse/parser.ts +++ b/packages/agent-script/src/parse/parser.ts @@ -7,6 +7,7 @@ import { type ExportDefaultDeclaration, type ExportNamedDeclaration } from "./parse-export.js"; +import { createImportMeta, isImportMetaTokenSequence } from "./parse-import-meta.js"; export type { ExportDefaultDeclaration, ExportNamedDeclaration } from "./parse-export.js"; @@ -205,6 +206,12 @@ export type MemberExpression = BaseNode & { property: Expression; }; +export type MetaProperty = BaseNode & { + type: "MetaProperty"; + meta: Identifier & { name: "import" }; + property: Identifier & { name: "meta" }; +}; + export type AssignmentExpression = BaseNode & { type: "AssignmentExpression"; operator: "="; @@ -366,6 +373,7 @@ export type Expression = | Identifier | LogicalExpression | MemberExpression + | MetaProperty | NullLiteral | NumericLiteral | ObjectExpression @@ -672,7 +680,7 @@ class Parser { return this.parseTryStatement(); } - if (token.type === "keyword" && token.value === "import") { + if (token.type === "keyword" && token.value === "import" && !this.isImportMetaStart()) { return this.parseImportDeclaration(); } @@ -1474,6 +1482,8 @@ class Parser { return expression; } + this.assertNotImportMetaAssignmentTarget(expression); + if (expression.type === "MemberExpression" && !expression.optional) { return expression; } @@ -1977,6 +1987,13 @@ class Parser { } if (token.type === "keyword") { + if (this.isImportMetaStart()) { + return { + node: this.parseImportMeta(), + parenthesized: false + }; + } + this.index += 1; return { node: createKeywordLiteral(token), @@ -2292,6 +2309,8 @@ class Parser { return node; } + this.assertNotImportMetaAssignmentTarget(node); + if (node.type === "MemberExpression" && !node.optional) { return node; } @@ -2578,6 +2597,9 @@ class Parser { private shouldParseTopLevelStatement(): boolean { const token = this.currentToken(); if (token.type === "keyword" && TOP_LEVEL_STATEMENT_KEYWORDS.has(token.value)) { + if (token.value === "import" && this.isImportMetaStart()) { + return false; + } return true; } @@ -2679,6 +2701,26 @@ class Parser { private isExportToken(token: Token): boolean { return token.value === "export"; } + + private isImportMetaStart(): boolean { + return isImportMetaTokenSequence(this.currentToken(), this.peekToken(1), this.peekToken(2)); + } + + private parseImportMeta(): MetaProperty { + const importToken = this.currentToken(); + if (!this.isImportMetaStart()) { + throw unexpectedTokenError(importToken); + } + + this.index += 3; + return createImportMeta(importToken, this.previousToken()); + } + + private assertNotImportMetaAssignmentTarget(node: Expression): void { + if (isImportMetaReference(node)) { + throw new DisallowedSyntaxError("import.meta assignment", node.span.start); + } + } } function createIdentifier(token: Token): Identifier { @@ -2697,6 +2739,14 @@ function createIdentifierName(token: Token): Identifier { }; } +function isImportMetaReference(node: Expression): boolean { + if (node.type === "MetaProperty") { + return true; + } + + return node.type === "MemberExpression" && isImportMetaReference(node.object); +} + function createNumericLiteral(token: Token): NumericLiteral { return { type: "NumericLiteral", From 385af05c055dd5c3f808dff6d69e9397e47b9622 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 23:22:42 -0500 Subject: [PATCH 046/111] feat(agent-script): lint module export syntax --- docs/plans/agent-harness.md | 4 +- docs/plans/agent-harness.md.lock | 2 +- packages/agent-script/src/lint.test.ts | 62 +++ packages/agent-script/src/lint/index.ts | 5 +- .../src/lint/rules/AS-export-import-meta.ts | 457 ++++++++++++++++++ packages/agent-script/src/lint/rules/AS008.ts | 5 +- packages/agent-script/src/lint/rules/AS009.ts | 3 +- packages/agent-script/src/lint/rules/AS011.ts | 6 +- packages/agent-script/src/lint/rules/AS012.ts | 3 +- .../src/parse/parse-export.test.ts | 15 +- .../agent-script/src/parse/parse-export.ts | 6 +- packages/agent-script/src/parse/parser.ts | 213 ++++++-- 12 files changed, 731 insertions(+), 50 deletions(-) create mode 100644 packages/agent-script/src/lint.test.ts create mode 100644 packages/agent-script/src/lint/rules/AS-export-import-meta.ts diff --git a/docs/plans/agent-harness.md b/docs/plans/agent-harness.md index d867722447..0b88c25de1 100644 --- a/docs/plans/agent-harness.md +++ b/docs/plans/agent-harness.md @@ -152,8 +152,8 @@ tasks: `export default`. That decision belongs to the agent-harness loader, not the linter. status: - implement: open - test: open + implement: done + test: done commit: open - id: agent-script-runtime-entry diff --git a/docs/plans/agent-harness.md.lock b/docs/plans/agent-harness.md.lock index 272a95e7da..d37b24cb2f 100644 --- a/docs/plans/agent-harness.md.lock +++ b/docs/plans/agent-harness.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T04:11:06.130Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T04:21:41.351Z"} \ No newline at end of file diff --git a/packages/agent-script/src/lint.test.ts b/packages/agent-script/src/lint.test.ts new file mode 100644 index 0000000000..892a380588 --- /dev/null +++ b/packages/agent-script/src/lint.test.ts @@ -0,0 +1,62 @@ +import { describe, expect, it } from "vitest"; + +import { lint } from "./lint.js"; + +function diagnosticCodes(source: string, options: Parameters[1] = {}): string[] { + return lint(source, { filename: "rule.js", ...options }).map((diagnostic) => diagnostic.code); +} + +function diagnostics(source: string, options: Parameters[1] = {}) { + return lint(source, { filename: "rule.js", ...options }); +} + +describe("lint export and import.meta module syntax", () => { + it("reports unknown named exports unless the name is allowed", () => { + expect(diagnosticCodes("export const schema = {};", { allowedExportNames: ["schema"] })).not.toContain( + "AS-EXPORT-UNKNOWN" + ); + expect(diagnosticCodes("export const schema = {};")).toContain("AS-EXPORT-UNKNOWN"); + expect(diagnosticCodes("export const schema = {}; export const tools = [];", { allowedExportNames: ["schema"] })) + .toContain("AS-EXPORT-UNKNOWN"); + }); + + it("reports multiple default exports", () => { + expect(diagnosticCodes("export default () => 1;")).not.toContain("AS-EXPORT-DEFAULT-MULTIPLE"); + expect(diagnosticCodes("export default () => 1; export default () => 2;")).toContain( + "AS-EXPORT-DEFAULT-MULTIPLE" + ); + }); + + it("reports default exports whose initializer is not an arrow expression", () => { + expect(diagnosticCodes("export default async () => 1;")).not.toContain("AS-EXPORT-DEFAULT-NOT-ARROW"); + expect(diagnosticCodes("export default (() => 1);")).not.toContain("AS-EXPORT-DEFAULT-NOT-ARROW"); + expect(diagnosticCodes("export default 1;")).toContain("AS-EXPORT-DEFAULT-NOT-ARROW"); + }); + + it("warns when a top-level return appears alongside a default export", () => { + expect(diagnosticCodes("return 1;")).not.toContain("AS-RETURN-AT-TOP"); + expect(diagnosticCodes("export default () => { return 1; };")).not.toContain("AS-RETURN-AT-TOP"); + expect(diagnosticCodes("export default () => 1; return 2;")).toContain("AS-RETURN-AT-TOP"); + expect(diagnostics("export default () => 1; return 2;").find((diagnostic) => diagnostic.code === "AS-RETURN-AT-TOP")) + .toMatchObject({ severity: "warning" }); + }); + + it("reports assignment targets that involve import.meta", () => { + expect(diagnosticCodes("const url = import.meta.url;")).not.toContain("AS-IMPORT-META-ASSIGN"); + expect(diagnosticCodes("import.meta = {};")).toContain("AS-IMPORT-META-ASSIGN"); + expect(diagnosticCodes("import.meta.url = 'agent.md';")).toContain("AS-IMPORT-META-ASSIGN"); + expect(diagnosticCodes("target[import.meta.url] = value;")).toContain("AS-IMPORT-META-ASSIGN"); + expect(diagnosticCodes("[import.meta.url] = [url];")).toContain("AS-IMPORT-META-ASSIGN"); + expect(diagnosticCodes("({ url: import.meta.url } = source);")).toContain("AS-IMPORT-META-ASSIGN"); + expect(diagnosticCodes("for (import.meta.url of urls) {}")).toContain("AS-IMPORT-META-ASSIGN"); + }); + + it("does not require a default export", () => { + expect(diagnosticCodes("export const schema = {};", { allowedExportNames: ["schema"] })).not.toContain( + "AS-EXPORT-DEFAULT-NOT-ARROW" + ); + expect(diagnosticCodes("export const schema = {};", { allowedExportNames: ["schema"] })).not.toContain( + "AS-EXPORT-DEFAULT-MULTIPLE" + ); + }); +}); diff --git a/packages/agent-script/src/lint/index.ts b/packages/agent-script/src/lint/index.ts index b212eb3caf..1760979600 100644 --- a/packages/agent-script/src/lint/index.ts +++ b/packages/agent-script/src/lint/index.ts @@ -12,6 +12,7 @@ import { AS012 } from "./rules/AS012.js"; import { AS013 } from "./rules/AS013.js"; import { AS014 } from "./rules/AS014.js"; import { AS015 } from "./rules/AS015.js"; +import { AS_EXPORT_IMPORT_META } from "./rules/AS-export-import-meta.js"; import type { SourceSpan } from "../parse/parser.js"; import type { Modules } from "./rules/module-registry.js"; @@ -27,6 +28,7 @@ export type Diagnostic = { }; export type LintOptions = { + allowedExportNames?: readonly string[]; filename?: string; modules?: Modules; }; @@ -46,7 +48,8 @@ const RULES: readonly LintRule[] = [ AS012, AS013, AS014, - AS015 + AS015, + AS_EXPORT_IMPORT_META ]; export function lint(source: string, options: LintOptions = {}): Diagnostic[] { diff --git a/packages/agent-script/src/lint/rules/AS-export-import-meta.ts b/packages/agent-script/src/lint/rules/AS-export-import-meta.ts new file mode 100644 index 0000000000..707ee69901 --- /dev/null +++ b/packages/agent-script/src/lint/rules/AS-export-import-meta.ts @@ -0,0 +1,457 @@ +import { + parseModule, + type ArrayExpression, + type AssignmentExpression, + type AssignmentPattern, + type BinaryExpression, + type CallExpression, + type ConditionalExpression, + type Expression, + type ForOfStatement, + type ForStatement, + type IfStatement, + type LogicalExpression, + type MemberExpression, + type Module, + type ObjectExpression, + type Property, + type RestElement, + type SourceSpan, + type SpreadElement, + type Statement, + type TemplateLiteral, + type ThrowStatement, + type TryStatement, + type UnaryExpression, + type VariableDeclaration, + type VariableDeclarator, + type WhileStatement +} from "../../parse/parser.js"; + +type DiagnosticCode = + | "AS-EXPORT-DEFAULT-MULTIPLE" + | "AS-EXPORT-DEFAULT-NOT-ARROW" + | "AS-EXPORT-UNKNOWN" + | "AS-IMPORT-META-ASSIGN" + | "AS-RETURN-AT-TOP"; + +export type Diagnostic = { + code: DiagnosticCode; + severity: "error" | "warning"; + message: string; + filename: string; + line: number; + column: number; + span: SourceSpan; +}; + +export function AS_EXPORT_IMPORT_META( + source: string, + options: { allowedExportNames?: readonly string[]; filename?: string } = {} +): Diagnostic[] { + return new Scanner(options.filename ?? "", new Set(options.allowedExportNames ?? [])).scan(source); +} + +class Scanner { + private readonly diagnostics: Diagnostic[] = []; + + constructor( + private readonly filename: string, + private readonly allowedExportNames: ReadonlySet + ) {} + + scan(source: string): Diagnostic[] { + this.visitModule(parseModule(source, this.filename)); + return this.diagnostics; + } + + private visitModule(node: Module): void { + const defaultExports = node.body.filter((statement) => statement.type === "ExportDefaultDeclaration"); + const hasDefaultExport = defaultExports.length > 0; + + for (const [index, statement] of defaultExports.entries()) { + if (index > 0) { + this.pushDiagnostic( + "AS-EXPORT-DEFAULT-MULTIPLE", + "error", + "Module contains more than one export default declaration.", + statement.span + ); + } + } + + for (const statement of node.body) { + if (hasDefaultExport && statement.type === "ReturnStatement") { + this.pushDiagnostic( + "AS-RETURN-AT-TOP", + "warning", + "Top-level return statement is present alongside an export default declaration.", + statement.span + ); + } + + this.visitStatement(statement); + } + } + + private visitStatement(node: Statement): void { + switch (node.type) { + case "ExportNamedDeclaration": + this.visitExportNamedDeclaration(node.declaration); + return; + case "ExportDefaultDeclaration": + if (node.declaration.type !== "ArrowFunctionExpression") { + this.pushDiagnostic( + "AS-EXPORT-DEFAULT-NOT-ARROW", + "error", + "Export default initializer must be an arrow expression.", + node.declaration.span + ); + } + this.visitExpression(node.declaration); + return; + case "BlockStatement": + for (const statement of node.body) { + this.visitStatement(statement); + } + return; + case "ExpressionStatement": + this.visitExpression(node.expression); + return; + case "IfStatement": + this.visitIfStatement(node); + return; + case "ForStatement": + this.visitForStatement(node); + return; + case "ForOfStatement": + this.visitForOfStatement(node); + return; + case "WhileStatement": + this.visitWhileStatement(node); + return; + case "TryStatement": + this.visitTryStatement(node); + return; + case "VariableDeclaration": + this.visitVariableDeclaration(node); + return; + case "ReturnStatement": + if (node.argument !== undefined) { + this.visitExpression(node.argument); + } + return; + case "ThrowStatement": + this.visitThrowStatement(node); + return; + case "ImportDeclaration": + case "BreakStatement": + case "ContinueStatement": + return; + } + } + + private visitExportNamedDeclaration(node: VariableDeclaration): void { + const declarator = node.declarations[0]; + if (declarator?.id.type === "Identifier" && !this.allowedExportNames.has(declarator.id.name)) { + this.pushDiagnostic( + "AS-EXPORT-UNKNOWN", + "error", + `Named export '${declarator.id.name}' is not allowed.`, + declarator.id.span + ); + } + + this.visitVariableDeclaration(node); + } + + private visitIfStatement(node: IfStatement): void { + this.visitExpression(node.test); + this.visitStatement(node.consequent); + if (node.alternate !== undefined) { + this.visitStatement(node.alternate); + } + } + + private visitForStatement(node: ForStatement): void { + if (node.init !== undefined) { + if (node.init.type === "VariableDeclaration") { + this.visitVariableDeclaration(node.init); + } else { + this.visitExpression(node.init); + } + } + if (node.test !== undefined) { + this.visitExpression(node.test); + } + if (node.update !== undefined) { + this.visitExpression(node.update); + } + this.visitStatement(node.body); + } + + private visitForOfStatement(node: ForOfStatement): void { + if (node.left.type === "VariableDeclaration") { + this.visitVariableDeclaration(node.left); + } else { + if (isImportMetaAssignmentTarget(node.left)) { + this.pushDiagnostic( + "AS-IMPORT-META-ASSIGN", + "error", + "Assignment target must not involve import.meta.", + node.left.span + ); + } + this.visitAssignmentTarget(node.left); + } + this.visitExpression(node.right); + this.visitStatement(node.body); + } + + private visitWhileStatement(node: WhileStatement): void { + this.visitExpression(node.test); + this.visitStatement(node.body); + } + + private visitTryStatement(node: TryStatement): void { + this.visitStatement(node.block); + if (node.handler !== undefined) { + this.visitStatement(node.handler.body); + } + if (node.finalizer !== undefined) { + this.visitStatement(node.finalizer); + } + } + + private visitVariableDeclaration(node: VariableDeclaration): void { + for (const declarator of node.declarations) { + this.visitVariableDeclarator(declarator); + } + } + + private visitVariableDeclarator(node: VariableDeclarator): void { + if (node.init !== undefined) { + this.visitExpression(node.init); + } + } + + private visitThrowStatement(node: ThrowStatement): void { + this.visitExpression(node.argument); + } + + private visitExpression(node: Expression): void { + switch (node.type) { + case "ArrowFunctionExpression": + if (node.body.type === "BlockStatement") { + this.visitStatement(node.body); + } else { + this.visitExpression(node.body); + } + return; + case "AwaitExpression": + this.visitExpression(node.argument); + return; + case "ArrayExpression": + this.visitArrayExpression(node); + return; + case "ObjectExpression": + this.visitObjectExpression(node); + return; + case "UnaryExpression": + this.visitUnaryExpression(node); + return; + case "BinaryExpression": + case "LogicalExpression": + this.visitBinaryLikeExpression(node); + return; + case "ConditionalExpression": + this.visitConditionalExpression(node); + return; + case "MemberExpression": + this.visitMemberExpression(node); + return; + case "AssignmentExpression": + this.visitAssignmentExpression(node); + return; + case "CallExpression": + this.visitCallExpression(node); + return; + case "TemplateLiteral": + this.visitTemplateLiteral(node); + return; + case "Identifier": + case "BooleanLiteral": + case "NullLiteral": + case "NumericLiteral": + case "StringLiteral": + case "RegexLiteral": + case "MetaProperty": + case "UndefinedLiteral": + return; + } + } + + private visitArrayExpression(node: ArrayExpression): void { + for (const element of node.elements) { + this.visitExpressionOrSpread(element); + } + } + + private visitObjectExpression(node: ObjectExpression): void { + for (const property of node.properties) { + if (property.type === "SpreadElement") { + this.visitExpression(property.argument); + } else { + this.visitProperty(property); + } + } + } + + private visitProperty(node: Property): void { + if (node.computed) { + this.visitExpression(node.key); + } + this.visitExpression(node.value); + } + + private visitUnaryExpression(node: UnaryExpression): void { + this.visitExpression(node.argument); + } + + private visitBinaryLikeExpression(node: BinaryExpression | LogicalExpression): void { + this.visitExpression(node.left); + this.visitExpression(node.right); + } + + private visitConditionalExpression(node: ConditionalExpression): void { + this.visitExpression(node.test); + this.visitExpression(node.consequent); + this.visitExpression(node.alternate); + } + + private visitMemberExpression(node: MemberExpression): void { + this.visitExpression(node.object); + if (node.computed) { + this.visitExpression(node.property); + } + } + + private visitAssignmentExpression(node: AssignmentExpression): void { + if (isImportMetaAssignmentTarget(node.left)) { + this.pushDiagnostic( + "AS-IMPORT-META-ASSIGN", + "error", + "Assignment target must not involve import.meta.", + node.left.span + ); + } + + this.visitAssignmentTarget(node.left); + this.visitExpression(node.right); + } + + private visitAssignmentTarget(node: AssignmentExpression["left"] | AssignmentPattern | RestElement): void { + switch (node.type) { + case "AssignmentPattern": + this.visitAssignmentTarget(node.left); + this.visitExpression(node.right); + return; + case "RestElement": + this.visitAssignmentTarget(node.argument); + return; + case "MemberExpression": + this.visitMemberExpression(node); + return; + case "ArrayPattern": + for (const element of node.elements) { + if (element !== null) { + this.visitAssignmentTarget(element); + } + } + return; + case "ObjectPattern": + for (const property of node.properties) { + if (property.type === "RestElement") { + this.visitAssignmentTarget(property); + } else { + this.visitAssignmentTarget(property.value); + } + } + return; + case "Identifier": + case "MetaProperty": + return; + } + } + + private visitCallExpression(node: CallExpression): void { + this.visitExpression(node.callee); + for (const argument of node.arguments) { + this.visitExpressionOrSpread(argument); + } + } + + private visitTemplateLiteral(node: TemplateLiteral): void { + for (const expression of node.expressions) { + this.visitExpression(expression); + } + } + + private visitExpressionOrSpread(node: Expression | SpreadElement): void { + if (node.type === "SpreadElement") { + this.visitExpression(node.argument); + return; + } + + this.visitExpression(node); + } + + private pushDiagnostic( + code: DiagnosticCode, + severity: Diagnostic["severity"], + message: string, + span: SourceSpan + ): void { + this.diagnostics.push({ + code, + severity, + message, + filename: this.filename, + line: span.start.line, + column: span.start.column, + span + }); + } +} + +function isImportMetaReference(node: AssignmentExpression["left"] | Expression): boolean { + if (node.type === "MetaProperty") { + return true; + } + + return ( + node.type === "MemberExpression" && + (isImportMetaReference(node.object) || (node.computed && isImportMetaReference(node.property))) + ); +} + +function isImportMetaAssignmentTarget(node: AssignmentExpression["left"] | AssignmentPattern | RestElement): boolean { + switch (node.type) { + case "MetaProperty": + return true; + case "MemberExpression": + return isImportMetaReference(node); + case "AssignmentPattern": + return isImportMetaAssignmentTarget(node.left); + case "RestElement": + return isImportMetaAssignmentTarget(node.argument); + case "ArrayPattern": + return node.elements.some((element) => element !== null && isImportMetaAssignmentTarget(element)); + case "ObjectPattern": + return node.properties.some((property) => + isImportMetaAssignmentTarget(property.type === "RestElement" ? property : property.value) + ); + case "Identifier": + return false; + } +} diff --git a/packages/agent-script/src/lint/rules/AS008.ts b/packages/agent-script/src/lint/rules/AS008.ts index dee43ae4d8..b8ceec2aa5 100644 --- a/packages/agent-script/src/lint/rules/AS008.ts +++ b/packages/agent-script/src/lint/rules/AS008.ts @@ -358,10 +358,13 @@ class AS008Scanner { this.visitExpression(node.argument); } - private visitAssignmentTarget(node: ArrayPattern | Identifier | MemberExpression | ObjectPattern): void { + private visitAssignmentTarget(node: AssignmentExpression["left"]): void { if (node.type === "Identifier") { return; } + if (node.type === "MetaProperty") { + return; + } if (node.type === "MemberExpression") { this.visitMemberExpression(node); return; diff --git a/packages/agent-script/src/lint/rules/AS009.ts b/packages/agent-script/src/lint/rules/AS009.ts index fc841d673f..193fdb56e7 100644 --- a/packages/agent-script/src/lint/rules/AS009.ts +++ b/packages/agent-script/src/lint/rules/AS009.ts @@ -364,10 +364,11 @@ class AS009Scanner { } private visitAssignmentTarget( - node: ArrayPattern | AssignmentPattern | Identifier | MemberExpression | ObjectPattern | RestElement + node: AssignmentExpression["left"] | AssignmentPattern | RestElement ): void { switch (node.type) { case "Identifier": + case "MetaProperty": return; case "MemberExpression": this.visitMemberExpression(node); diff --git a/packages/agent-script/src/lint/rules/AS011.ts b/packages/agent-script/src/lint/rules/AS011.ts index 1b0b44ed96..a6d6ac9c3d 100644 --- a/packages/agent-script/src/lint/rules/AS011.ts +++ b/packages/agent-script/src/lint/rules/AS011.ts @@ -317,15 +317,13 @@ class AS011Scanner { } private visitAssignmentTarget( - node: import("../../parse/parser.js").ArrayPattern | + node: AssignmentExpression["left"] | import("../../parse/parser.js").AssignmentPattern | - import("../../parse/parser.js").Identifier | - MemberExpression | - import("../../parse/parser.js").ObjectPattern | import("../../parse/parser.js").RestElement ): void { switch (node.type) { case "Identifier": + case "MetaProperty": return; case "MemberExpression": this.visitMemberExpression(node); diff --git a/packages/agent-script/src/lint/rules/AS012.ts b/packages/agent-script/src/lint/rules/AS012.ts index bbcad11ce3..a96dd8b654 100644 --- a/packages/agent-script/src/lint/rules/AS012.ts +++ b/packages/agent-script/src/lint/rules/AS012.ts @@ -334,10 +334,11 @@ class AS012Scanner { } private visitPattern( - node: ArrayPattern | AssignmentPattern | Identifier | MemberExpression | ObjectPattern | RestElement + node: AssignmentExpression["left"] | AssignmentPattern | RestElement ): void { switch (node.type) { case "Identifier": + case "MetaProperty": return; case "MemberExpression": this.visitMemberExpression(node); diff --git a/packages/agent-script/src/parse/parse-export.test.ts b/packages/agent-script/src/parse/parse-export.test.ts index 2ba963125d..6e8a231d40 100644 --- a/packages/agent-script/src/parse/parse-export.test.ts +++ b/packages/agent-script/src/parse/parse-export.test.ts @@ -86,17 +86,22 @@ describe("parse exports", () => { expect(() => parseModule("export { x }")).toThrowError(DisallowedSyntaxError); expect(() => parseModule("export default function () {}")).toThrowError(DisallowedSyntaxError); expect(() => parseModule("export default class Run {}")).toThrowError(DisallowedSyntaxError); - expect(() => parseModule("export default 1")).toThrowError(DisallowedSyntaxError); expect(() => parseModule("export const a = 1, b = 2")).toThrowError(DisallowedSyntaxError); expect(() => parseModule("export const { x } = value")).toThrowError(DisallowedSyntaxError); expect(() => parseModule("export const [x] = value")).toThrowError(DisallowedSyntaxError); expect(() => parseModule("export let x = 1")).toThrowError(DisallowedSyntaxError); }); - it("rejects duplicate default exports in the same module", () => { - expect(() => parseModule("export default () => 1; export default () => 2")).toThrowError( - DisallowedSyntaxError - ); + it("parses default export forms that the linter validates", () => { + expect(parseModule("export default 1").body[0]).toMatchObject({ + type: "ExportDefaultDeclaration", + declaration: { + type: "NumericLiteral", + value: 1 + } + }); + + expect(parseModule("export default () => 1; export default () => 2").body).toHaveLength(2); }); it("rejects exports outside module top level", () => { diff --git a/packages/agent-script/src/parse/parse-export.ts b/packages/agent-script/src/parse/parse-export.ts index e06879857d..750c5b87f5 100644 --- a/packages/agent-script/src/parse/parse-export.ts +++ b/packages/agent-script/src/parse/parse-export.ts @@ -1,5 +1,5 @@ import type { Token } from "./tokenizer.js"; -import type { ArrowFunctionExpression, SourceSpan, VariableDeclaration } from "./parser.js"; +import type { Expression, SourceSpan, VariableDeclaration } from "./parser.js"; export type ExportNamedDeclaration = { nodeId?: number; @@ -11,7 +11,7 @@ export type ExportNamedDeclaration = { export type ExportDefaultDeclaration = { nodeId?: number; type: "ExportDefaultDeclaration"; - declaration: ArrowFunctionExpression; + declaration: Expression; span: SourceSpan; }; @@ -28,7 +28,7 @@ export function createExportNamedDeclaration( export function createExportDefaultDeclaration( exportToken: Token, - declaration: ArrowFunctionExpression + declaration: Expression ): ExportDefaultDeclaration { return { type: "ExportDefaultDeclaration", diff --git a/packages/agent-script/src/parse/parser.ts b/packages/agent-script/src/parse/parser.ts index d6079880a9..91b2dbba63 100644 --- a/packages/agent-script/src/parse/parser.ts +++ b/packages/agent-script/src/parse/parser.ts @@ -98,6 +98,7 @@ export type Property = BaseNode & { }; export type PatternTarget = ArrayPattern | Identifier | MemberExpression | ObjectPattern; +export type AssignmentTarget = MetaProperty | PatternTarget; export type AssignmentPattern = BaseNode & { type: "AssignmentPattern"; @@ -215,7 +216,7 @@ export type MetaProperty = BaseNode & { export type AssignmentExpression = BaseNode & { type: "AssignmentExpression"; operator: "="; - left: PatternTarget; + left: AssignmentTarget; right: Expression; }; @@ -421,6 +422,10 @@ export function parse(source: string, filename = ""): ParseResult { `Regular expression literals are not supported at line ${regexLiteral.span.start.line}, column ${regexLiteral.span.start.column}.` ); } + const importMetaAssignment = findImportMetaAssignmentTarget(result); + if (importMetaAssignment !== undefined) { + throw new DisallowedSyntaxError("import.meta assignment", importMetaAssignment.start); + } return result; } catch (error) { if (error instanceof DisallowedSyntaxError) { @@ -461,7 +466,6 @@ function parseExpressionTokens(tokens: Token[]): Expression { class Parser { private index = 0; - private hasDefaultExport = false; constructor(private readonly tokens: Token[]) {} @@ -846,7 +850,7 @@ class Parser { return this.parseForOfDeclaration(); } - return this.parseAssignmentTarget(); + return this.toPatternTarget(this.parseAssignmentTarget()); } private parseForOfDeclaration(): VariableDeclaration { @@ -1040,16 +1044,11 @@ class Parser { private parseExportDefaultDeclaration(exportToken: Token): ExportDefaultDeclaration { this.index += 1; - if (this.hasDefaultExport) { - throw new DisallowedSyntaxError("export default", exportToken.start); - } - - const declaration = this.tryParseArrowFunctionExpression(); - if (declaration === undefined) { - throw new DisallowedSyntaxError("export default", this.currentToken().start); + if (this.currentToken().value === "function" || this.currentToken().value === "class") { + throw new DisallowedSyntaxError(`export default ${this.currentToken().value}`, this.currentToken().start); } - this.hasDefaultExport = true; + const declaration = this.parseExpression().node; return createExportDefaultDeclaration(exportToken, declaration); } @@ -1444,7 +1443,7 @@ class Parser { | RestElement { if (this.consumePunctuator("...") !== undefined) { const start = this.previousToken().start; - const argument = this.parseAssignmentTarget(); + const argument = this.toPatternTarget(this.parseAssignmentTarget()); return { type: "RestElement", argument, @@ -1454,19 +1453,19 @@ class Parser { const left = this.parseAssignmentTarget(); if (this.consumePunctuator("=") === undefined) { - return left; + return this.toPatternTarget(left); } const right = this.parseAssignmentExpression().node; return { type: "AssignmentPattern", - left, + left: this.toPatternTarget(left), right, span: createSpan(left.span.start, right.span.end) }; } - private parseAssignmentTarget(): PatternTarget { + private parseAssignmentTarget(): AssignmentTarget { const token = this.currentToken(); if (token.type === "punctuator" && token.value === "[") { @@ -1482,9 +1481,7 @@ class Parser { return expression; } - this.assertNotImportMetaAssignmentTarget(expression); - - if (expression.type === "MemberExpression" && !expression.optional) { + if (expression.type === "MetaProperty" || (expression.type === "MemberExpression" && !expression.optional)) { return expression; } @@ -2304,14 +2301,12 @@ class Parser { } } - private toAssignmentTarget(node: Expression): PatternTarget { + private toAssignmentTarget(node: Expression): AssignmentTarget { if (node.type === "Identifier") { return node; } - this.assertNotImportMetaAssignmentTarget(node); - - if (node.type === "MemberExpression" && !node.optional) { + if (node.type === "MetaProperty" || (node.type === "MemberExpression" && !node.optional)) { return node; } @@ -2338,7 +2333,7 @@ class Parser { element: Expression | SpreadElement ): AssignmentPattern | ArrayPattern | Identifier | MemberExpression | ObjectPattern | RestElement { if (element.type === "SpreadElement") { - const argument = this.toAssignmentTarget(element.argument); + const argument = this.toPatternTarget(this.toAssignmentTarget(element.argument)); return { type: "RestElement", argument, @@ -2349,13 +2344,13 @@ class Parser { if (element.type === "AssignmentExpression" && element.operator === "=") { return { type: "AssignmentPattern", - left: element.left, + left: this.toPatternTarget(element.left), right: element.right, span: element.span }; } - return this.toAssignmentTarget(element); + return this.toPatternTarget(this.toAssignmentTarget(element)); } private objectExpressionToPattern(node: ObjectExpression): ObjectPattern { @@ -2408,13 +2403,13 @@ class Parser { if (value.type === "AssignmentExpression" && value.operator === "=") { return { type: "AssignmentPattern", - left: value.left, + left: this.toPatternTarget(value.left), right: value.right, span: value.span }; } - return this.toAssignmentTarget(value); + return this.toPatternTarget(this.toAssignmentTarget(value)); } private isPatternAssignmentStart(startIndex: number): boolean { @@ -2716,11 +2711,14 @@ class Parser { return createImportMeta(importToken, this.previousToken()); } - private assertNotImportMetaAssignmentTarget(node: Expression): void { - if (isImportMetaReference(node)) { - throw new DisallowedSyntaxError("import.meta assignment", node.span.start); + private toPatternTarget(target: AssignmentTarget): PatternTarget { + if (target.type === "MetaProperty") { + throw new DisallowedSyntaxError("import.meta assignment", target.span.start); } + + return target; } + } function createIdentifier(token: Token): Identifier { @@ -2739,12 +2737,165 @@ function createIdentifierName(token: Token): Identifier { }; } +function findImportMetaAssignmentTarget(node: ParseResult): SourceSpan | undefined { + return findImportMetaAssignmentInNode(node); +} + +function findImportMetaAssignmentInNode(node: Expression | Statement): SourceSpan | undefined { + switch (node.type) { + case "AssignmentExpression": + if (isImportMetaAssignmentTarget(node.left)) { + return node.left.span; + } + return findImportMetaAssignmentInNode(node.right); + case "ForOfStatement": + if (node.left.type !== "VariableDeclaration" && isImportMetaAssignmentTarget(node.left)) { + return node.left.span; + } + return findImportMetaAssignmentInNode(node.right) ?? findImportMetaAssignmentInNode(node.body); + case "BlockStatement": + return findImportMetaAssignmentInList(node.body); + case "ExpressionStatement": + return findImportMetaAssignmentInNode(node.expression); + case "IfStatement": + return ( + findImportMetaAssignmentInNode(node.test) ?? + findImportMetaAssignmentInNode(node.consequent) ?? + (node.alternate === undefined ? undefined : findImportMetaAssignmentInNode(node.alternate)) + ); + case "ForStatement": + return ( + findImportMetaAssignmentInOptionalForInit(node.init) ?? + findImportMetaAssignmentInOptionalExpression(node.test) ?? + findImportMetaAssignmentInOptionalExpression(node.update) ?? + findImportMetaAssignmentInNode(node.body) + ); + case "WhileStatement": + return findImportMetaAssignmentInNode(node.test) ?? findImportMetaAssignmentInNode(node.body); + case "TryStatement": + return ( + findImportMetaAssignmentInNode(node.block) ?? + (node.handler === undefined ? undefined : findImportMetaAssignmentInNode(node.handler.body)) ?? + (node.finalizer === undefined ? undefined : findImportMetaAssignmentInNode(node.finalizer)) + ); + case "VariableDeclaration": + for (const declarator of node.declarations) { + if (declarator.init !== undefined) { + const result = findImportMetaAssignmentInNode(declarator.init); + if (result !== undefined) { + return result; + } + } + } + return undefined; + case "ReturnStatement": + return node.argument === undefined ? undefined : findImportMetaAssignmentInNode(node.argument); + case "ThrowStatement": + return findImportMetaAssignmentInNode(node.argument); + case "ArrowFunctionExpression": + return node.body.type === "BlockStatement" ? findImportMetaAssignmentInNode(node.body) : findImportMetaAssignmentInNode(node.body); + case "AwaitExpression": + return findImportMetaAssignmentInNode(node.argument); + case "ArrayExpression": + return findImportMetaAssignmentInList(node.elements); + case "ObjectExpression": + for (const property of node.properties) { + const result = + property.type === "SpreadElement" + ? findImportMetaAssignmentInNode(property.argument) + : findImportMetaAssignmentInNode(property.value); + if (result !== undefined) { + return result; + } + } + return undefined; + case "UnaryExpression": + return findImportMetaAssignmentInNode(node.argument); + case "BinaryExpression": + case "LogicalExpression": + return findImportMetaAssignmentInNode(node.left) ?? findImportMetaAssignmentInNode(node.right); + case "ConditionalExpression": + return ( + findImportMetaAssignmentInNode(node.test) ?? + findImportMetaAssignmentInNode(node.consequent) ?? + findImportMetaAssignmentInNode(node.alternate) + ); + case "MemberExpression": + return ( + findImportMetaAssignmentInNode(node.object) ?? + (node.computed ? findImportMetaAssignmentInNode(node.property) : undefined) + ); + case "CallExpression": + return findImportMetaAssignmentInNode(node.callee) ?? findImportMetaAssignmentInList(node.arguments); + case "TemplateLiteral": + return findImportMetaAssignmentInList(node.expressions); + case "BreakStatement": + case "ContinueStatement": + case "ExportDefaultDeclaration": + case "ExportNamedDeclaration": + case "Identifier": + case "ImportDeclaration": + case "BooleanLiteral": + case "NullLiteral": + case "NumericLiteral": + case "StringLiteral": + case "RegexLiteral": + case "MetaProperty": + case "UndefinedLiteral": + return undefined; + } +} + +function findImportMetaAssignmentInOptionalForInit(node: Expression | VariableDeclaration | undefined): SourceSpan | undefined { + return node === undefined ? undefined : findImportMetaAssignmentInNode(node); +} + +function findImportMetaAssignmentInOptionalExpression(node: Expression | undefined): SourceSpan | undefined { + return node === undefined ? undefined : findImportMetaAssignmentInNode(node); +} + +function findImportMetaAssignmentInList(nodes: ReadonlyArray): SourceSpan | undefined { + for (const node of nodes) { + const result = + node.type === "SpreadElement" ? findImportMetaAssignmentInNode(node.argument) : findImportMetaAssignmentInNode(node); + if (result !== undefined) { + return result; + } + } + + return undefined; +} + +function isImportMetaAssignmentTarget(node: AssignmentExpression["left"] | AssignmentPattern | RestElement): boolean { + switch (node.type) { + case "MetaProperty": + return true; + case "MemberExpression": + return isImportMetaReference(node); + case "AssignmentPattern": + return isImportMetaAssignmentTarget(node.left); + case "RestElement": + return isImportMetaAssignmentTarget(node.argument); + case "ArrayPattern": + return node.elements.some((element) => element !== null && isImportMetaAssignmentTarget(element)); + case "ObjectPattern": + return node.properties.some((property) => + isImportMetaAssignmentTarget(property.type === "RestElement" ? property : property.value) + ); + case "Identifier": + return false; + } +} + function isImportMetaReference(node: Expression): boolean { if (node.type === "MetaProperty") { return true; } - return node.type === "MemberExpression" && isImportMetaReference(node.object); + return ( + node.type === "MemberExpression" && + (isImportMetaReference(node.object) || (node.computed && isImportMetaReference(node.property))) + ); } function createNumericLiteral(token: Token): NumericLiteral { From 400b80cc2f065816c2c9c307dc82dc72826f8dbf Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 23:32:05 -0500 Subject: [PATCH 047/111] feat(agent-script): add runtime entry point support --- docs/plans/agent-harness.md | 8 +- docs/plans/agent-harness.md.lock | 2 +- packages/agent-script/src/interp/async.ts | 52 ++-- .../agent-script/src/interp/interpreter.ts | 102 +++++++- packages/agent-script/src/interp/scope.ts | 22 +- packages/agent-script/src/run.test.ts | 232 ++++++++++++++++-- packages/agent-script/src/run.ts | 120 ++++++++- 7 files changed, 476 insertions(+), 62 deletions(-) diff --git a/docs/plans/agent-harness.md b/docs/plans/agent-harness.md index 0b88c25de1..d26f8d86cd 100644 --- a/docs/plans/agent-harness.md +++ b/docs/plans/agent-harness.md @@ -154,7 +154,7 @@ tasks: status: implement: done test: done - commit: open + commit: done - id: agent-script-runtime-entry title: Wire importMeta and entryPointArgs into agent-script run() @@ -198,9 +198,9 @@ tasks: No regex use, no string-level surgery. Use the parser + interpreter end-to-end. status: - implement: open - test: open - commit: open + implement: done + test: done + commit: done - id: agent-script-find-exported title: Add findExportedConstInitializer to agent-script diff --git a/docs/plans/agent-harness.md.lock b/docs/plans/agent-harness.md.lock index d37b24cb2f..6e12dbb0f8 100644 --- a/docs/plans/agent-harness.md.lock +++ b/docs/plans/agent-harness.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T04:21:41.351Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T04:31:10.357Z"} \ No newline at end of file diff --git a/packages/agent-script/src/interp/async.ts b/packages/agent-script/src/interp/async.ts index b6ca56272d..32b708ad5f 100644 --- a/packages/agent-script/src/interp/async.ts +++ b/packages/agent-script/src/interp/async.ts @@ -53,31 +53,33 @@ export async function evaluateArrowFunctionExpression( context: AsyncEvaluationContext, evaluateNode: EvaluateAsyncNode ): Promise { - if (!node.async) { - return { - kind: "error", - error: { - code: "UNSUPPORTED_NODE", - message: "Only async arrow functions are currently supported.", - nodeId: node.nodeId, - nodeType: node.type, - span: node.span - } - }; - } - return { kind: "normal", hasValue: true, value: createSandboxClosure({ - async: true, + ...(node.async ? { async: true } : {}), call: (args, callContext) => - createSandboxPromise( - executeAsyncArrow(node, args, { - ...context, - callStack: [...(callContext?.stack ?? context.callStack)] - }, evaluateNode) - ) + node.async + ? createSandboxPromise( + executeArrow( + node, + args, + { + ...context, + callStack: [...(callContext?.stack ?? context.callStack)] + }, + evaluateNode + ) + ) + : executeArrow( + node, + args, + { + ...context, + callStack: [...(callContext?.stack ?? context.callStack)] + }, + evaluateNode + ) }) }; } @@ -105,14 +107,16 @@ export async function evaluateAwaitExpression( return { kind: "normal", hasValue: true, - value: await (isSandboxPromise(argument.value) ? argument.value.promise : Promise.resolve(argument.value)) + value: await (isSandboxPromise(argument.value) + ? argument.value.promise + : Promise.resolve(argument.value)) }; } finally { leaveAwait(); } } -async function executeAsyncArrow( +async function executeArrow( node: ArrowFunctionExpression, args: readonly SandboxValue[], context: AsyncEvaluationContext, @@ -189,6 +193,8 @@ export async function resolveClosureResult( return result; } -function isPromiseLike(value: SandboxValue | Promise | PromiseLike): value is PromiseLike { +function isPromiseLike( + value: SandboxValue | Promise | PromiseLike +): value is PromiseLike { return typeof value === "object" && value !== null && "then" in value; } diff --git a/packages/agent-script/src/interp/interpreter.ts b/packages/agent-script/src/interp/interpreter.ts index 20cb117d68..826f4b9ecd 100644 --- a/packages/agent-script/src/interp/interpreter.ts +++ b/packages/agent-script/src/interp/interpreter.ts @@ -8,7 +8,10 @@ import type { ContinueStatement, Expression, Identifier, + ExportDefaultDeclaration, + ExportNamedDeclaration, MemberExpression, + MetaProperty, NullLiteral, NumericLiteral, ObjectExpression, @@ -23,7 +26,8 @@ import type { TryStatement, UnaryExpression, UndefinedLiteral, - ExpressionStatement + ExpressionStatement, + VariableDeclaration } from "../parse.js"; import { evaluateArrowFunctionExpression, @@ -49,11 +53,7 @@ import { type ArrayMethodName, type ArrayMethodOptions } from "./methods/array.js"; -import { - callNumberMethod, - getNumberMember, - isNumberMethodName -} from "./methods/number.js"; +import { callNumberMethod, getNumberMember, isNumberMethodName } from "./methods/number.js"; import { callStringMethod, getStringMember, @@ -108,6 +108,7 @@ export type InterpretOptions = { budget?: Budget; onYield?: (yieldPoint: InterpreterYieldPoint) => void; scope?: Scope; + useScopeDirectly?: boolean; }; type EvaluationContext = AsyncEvaluationContext; @@ -141,9 +142,12 @@ const dispatchTable: DispatchTable = { BooleanLiteral: evaluatePrimitiveLiteral, CallExpression: evaluateCallExpression, ContinueStatement: evaluateContinueStatement, + ExportDefaultDeclaration: evaluateExportDefaultDeclaration, + ExportNamedDeclaration: evaluateExportNamedDeclaration, ExpressionStatement: evaluateExpressionStatement, Identifier: evaluateIdentifier, MemberExpression: evaluateMemberExpression, + MetaProperty: evaluateMetaProperty, NullLiteral: evaluatePrimitiveLiteral, NumericLiteral: evaluatePrimitiveLiteral, ObjectExpression: evaluateObjectExpression, @@ -153,6 +157,7 @@ const dispatchTable: DispatchTable = { ThrowStatement: evaluateThrowStatement, TryStatement: evaluateTryStatement, UnaryExpression: evaluateUnaryExpression, + VariableDeclaration: evaluateVariableDeclaration, UndefinedLiteral: evaluatePrimitiveLiteral }; @@ -161,7 +166,12 @@ export async function interpret( options: InterpretOptions = {} ): Promise { const budget = options.budget ?? new Budget(); - const scope = options.scope?.child(options.bindings ?? {}) ?? new Scope(options.bindings); + const scope = + options.scope === undefined + ? new Scope(options.bindings) + : options.useScopeDirectly === true && options.bindings === undefined + ? options.scope + : options.scope.child(options.bindings ?? {}); const stats: InterpreterStats = { nodeVisits: 0 }; @@ -365,6 +375,74 @@ async function evaluateIdentifier( }; } +async function evaluateMetaProperty( + _node: MetaProperty, + context: EvaluationContext +): Promise { + return { + kind: "normal", + hasValue: true, + value: context.scope.lookupImportMeta() + }; +} + +async function evaluateExportDefaultDeclaration( + node: ExportDefaultDeclaration, + context: EvaluationContext +): Promise { + const declaration = await evaluateNode(node.declaration, context); + if (declaration.kind !== "normal") { + return declaration; + } + + context.scope.declare("default", "const", declaration.value); + + return { + kind: "normal", + hasValue: false, + value: undefined + }; +} + +async function evaluateExportNamedDeclaration( + node: ExportNamedDeclaration, + context: EvaluationContext +): Promise { + return evaluateVariableDeclaration(node.declaration, context); +} + +async function evaluateVariableDeclaration( + node: VariableDeclaration, + context: EvaluationContext +): Promise { + for (const declarator of node.declarations) { + if (declarator.id.type !== "Identifier") { + throw new TypeError(`Unsupported variable declaration pattern '${declarator.id.type}'.`); + } + + const value = + declarator.init === undefined + ? { + kind: "normal" as const, + hasValue: true as const, + value: undefined + } + : await evaluateNode(declarator.init, context); + + if (value.kind !== "normal") { + return value; + } + + context.scope.declare(declarator.id.name, node.kind, value.value); + } + + return { + kind: "normal", + hasValue: false, + value: undefined + }; +} + async function evaluateBlockStatement( node: BlockStatement, context: EvaluationContext @@ -511,7 +589,11 @@ async function evaluateMemberExpression( } if (Array.isArray(member.object)) { - const arrayMember = getArrayMember(member.object, member.property, createArrayMethodOptions(context)); + const arrayMember = getArrayMember( + member.object, + member.property, + createArrayMethodOptions(context) + ); if (arrayMember !== undefined) { return { kind: "normal", @@ -1046,8 +1128,8 @@ function isInterpreterError(value: unknown): value is InterpreterError { "message" in value && "nodeType" in value && "span" in value && - (((value as { code: unknown }).code === "UNBOUND_IDENTIFIER") || - ((value as { code: unknown }).code === "UNSUPPORTED_NODE")) + ((value as { code: unknown }).code === "UNBOUND_IDENTIFIER" || + (value as { code: unknown }).code === "UNSUPPORTED_NODE") ); } diff --git a/packages/agent-script/src/interp/scope.ts b/packages/agent-script/src/interp/scope.ts index 7b72e8ad69..22e3df5bfd 100644 --- a/packages/agent-script/src/interp/scope.ts +++ b/packages/agent-script/src/interp/scope.ts @@ -19,7 +19,11 @@ type ScopeLookupResult = export class Scope { readonly #bindings = new Map(); - constructor(bindings: Record = {}, private readonly parent?: Scope) { + constructor( + bindings: Record = {}, + private readonly parent?: Scope, + private readonly importMeta?: InterpreterValue + ) { for (const [name, value] of Object.entries(bindings)) { this.#bindings.set(name, { kind: "const", @@ -32,6 +36,18 @@ export class Scope { return new Scope(bindings, this); } + lookupImportMeta(): InterpreterValue { + if (this.importMeta !== undefined) { + return this.importMeta; + } + + if (this.parent !== undefined) { + return this.parent.lookupImportMeta(); + } + + return {}; + } + declare(name: string, kind: VariableDeclarationKind, value: InterpreterValue): void { if (this.#bindings.has(name)) { throw new Error(`Cannot redeclare binding '${name}' in the same scope.`); @@ -87,7 +103,9 @@ export class Scope { return { bindings: { ...inheritedBindings, - ...Object.fromEntries([...this.#bindings.entries()].map(([name, binding]) => [name, binding.value])) + ...Object.fromEntries( + [...this.#bindings.entries()].map(([name, binding]) => [name, binding.value]) + ) } }; } diff --git a/packages/agent-script/src/run.test.ts b/packages/agent-script/src/run.test.ts index 43f6ab4f48..7550b3eb66 100644 --- a/packages/agent-script/src/run.test.ts +++ b/packages/agent-script/src/run.test.ts @@ -582,29 +582,144 @@ try { expect(after).not.toHaveBeenCalled(); }); - it("blocks imported module calls when the signal is already aborted", async () => { - const controller = new AbortController(); - const request = vi.fn(() => "called"); - controller.abort(); - + it("resolves import.meta from an injected deep copy", async () => { + const importMeta = { + filepath: "script.ajs", + nested: { + value: "before" + } + }; + const first = createDeferred(); const result = run( [ - 'import { request } from "api";', - "return request();" + "await wait();", + "return JSON.stringify(Array.of(import.meta.filepath, import.meta.nested.value));" ].join("\n"), { - modules: { - api: { - request: createSandboxClosure({ - call: () => request(), - name: "request" - }) - } + bindings: { + wait: createSandboxClosure({ + async: true, + call: () => createSandboxPromise(first.promise), + name: "wait" + }) }, - signal: controller.signal + importMeta } ); + importMeta.filepath = "changed.ajs"; + importMeta.nested.value = "after"; + first.resolve(); + + await expect(result).resolves.toMatchObject({ + ok: true, + returnValue: JSON.stringify(["script.ajs", "before"]) + }); + }); + + it("calls the default export with entryPointArgs and returns its awaited result", async () => { + const result = await run( + [ + "export const schema = { type: 'object' };", + "export default (first, second) => JSON.stringify(Array.of(schema.type, first, second));" + ].join("\n"), + { + entryPointArgs: [ + { + label: "alpha" + }, + [1, 2] + ] + } + ); + + expect(result).toMatchObject({ + ok: true, + returnValue: JSON.stringify([ + "object", + { + label: "alpha" + }, + [1, 2] + ]) + }); + }); + + it("copies entryPointArgs before top-level evaluation can yield", async () => { + const input = { + nested: { + value: "before" + } + }; + const first = createDeferred(); + const result = run( + ["await wait();", "export default (arg) => JSON.stringify(Array.of(arg.nested.value));"].join( + "\n" + ), + { + bindings: { + wait: createSandboxClosure({ + async: true, + call: () => createSandboxPromise(first.promise), + name: "wait" + }) + }, + entryPointArgs: [input] + } + ); + + input.nested.value = "after"; + first.resolve(); + + await expect(result).resolves.toMatchObject({ + ok: true, + returnValue: JSON.stringify(["before"]) + }); + }); + + it("throws a runtime error with the filename when entryPointArgs is set without a default export", async () => { + await expect( + run("return 'top-level';", { entryPointArgs: [], filename: "script.ajs" }) + ).rejects.toThrow("Script script.ajs does not export a default function."); + }); + + it("propagates default export throws with sandbox stack formatting", async () => { + await expect( + run(["export default () => {", ' explode("boom");', "};"].join("\n"), { + bindings: { + explode(message: string) { + throw new TypeError(message); + } + }, + entryPointArgs: [] + }) + ).rejects.toEqual( + expect.objectContaining({ + message: "boom", + name: "TypeError", + stack: + "TypeError: boom\n at explode (line 2, column 3)\n at (line 1, column 1)" + }) + ); + }); + + it("blocks imported module calls when the signal is already aborted", async () => { + const controller = new AbortController(); + const request = vi.fn(() => "called"); + controller.abort(); + + const result = run(['import { request } from "api";', "return request();"].join("\n"), { + modules: { + api: { + request: createSandboxClosure({ + call: () => request(), + name: "request" + }) + } + }, + signal: controller.signal + }); + await expect(result).rejects.toMatchObject({ message: "aborted", name: "SandboxError" @@ -612,6 +727,93 @@ try { expect(request).not.toHaveBeenCalled(); }); + it("aborts at the next host call inside the entry function and can restore a pre-abort snapshot", async () => { + const source = [ + "export default async () => {", + " await first();", + " await second();", + " await third();", + " return 'done';", + "};" + ].join("\n"); + const controller = new AbortController(); + const first = createDeferred(); + const second = createDeferred(); + const third = vi.fn(() => "missed"); + const result = run(source, { + bindings: { + first: createSandboxClosure({ + async: true, + call: () => createSandboxPromise(first.promise), + name: "first" + }), + second: createSandboxClosure({ + async: true, + call: () => createSandboxPromise(second.promise), + name: "second" + }), + third: createSandboxClosure({ + call: () => third(), + name: "third" + }) + }, + entryPointArgs: [], + signal: controller.signal + }); + const snapshotPromise = dump(result); + + first.resolve(); + const snapshot = JSON.parse(await snapshotPromise); + second.resolve(); + controller.abort(); + + await expect(result).rejects.toMatchObject({ + message: "aborted", + name: "SandboxError" + }); + expect(third).not.toHaveBeenCalled(); + + const restored = restore(snapshot, { source }); + const resumed = await run(source, { + bindings: { + first: createSandboxClosure({ + async: true, + call: () => createSandboxPromise(Promise.resolve()), + name: "first" + }), + second: createSandboxClosure({ + async: true, + call: () => createSandboxPromise(Promise.resolve()), + name: "second" + }), + third: createSandboxClosure({ + async: true, + call: () => createSandboxPromise(Promise.resolve()), + name: "third" + }) + }, + entryPointArgs: [], + snapshot: restored + }); + + expect(resumed).toMatchObject({ + ok: true, + returnValue: "done" + }); + }); + + function createDeferred() { + let resolve: (value: T) => void = () => undefined; + const promise = new Promise((nextResolve) => { + resolve = nextResolve; + }); + + return { + promise, + resolve + }; + } + it("wraps caller-injected host function arguments and return values across the sandbox boundary", async () => { const observedArgs: unknown[] = []; const host = vi.fn((input: { nested: { value: number } }, items: number[]) => { diff --git a/packages/agent-script/src/run.ts b/packages/agent-script/src/run.ts index 40d0ec27a7..04f3936a56 100644 --- a/packages/agent-script/src/run.ts +++ b/packages/agent-script/src/run.ts @@ -1,6 +1,14 @@ import { hashSource } from "./parse/hash.js"; import type { ParseResult } from "./parse.js"; -import { parseModule, type Module, type Statement } from "./parse/parser.js"; +import { + parseModule, + type AwaitExpression, + type CallExpression, + type Identifier, + type Module, + type SourceSpan, + type Statement +} from "./parse/parser.js"; import { restore, type AgentScriptSnapshot } from "./restore.js"; import { Budget } from "./interp/budget.js"; import { wrapCancelableBindings } from "./interp/cancel.js"; @@ -11,6 +19,7 @@ import { createObjectArrayGlobals } from "./interp/globals/object-array.js"; import { wrapCallerInjectedBindings, type CallerInjectedBinding } from "./interp/host-bridge.js"; import { interpret, Scope, type InterpreterResult } from "./interp/interpreter.js"; import { createPromiseGlobals } from "./interp/promise.js"; +import { deepCopyToSandbox, isSandboxClosure, type SandboxValue } from "./interp/values.js"; import { resolveModuleImports, type ModuleRegistry } from "./modules/registry.js"; import { attachDumpController, createDumpController } from "./snapshot/dump.js"; import { createSnapshotScheduler } from "./snapshot/scheduler.js"; @@ -18,6 +27,9 @@ import { createSnapshotScheduler } from "./snapshot/scheduler.js"; export type RunOptions = { bindings?: Record; budget?: Budget; + entryPointArgs?: readonly unknown[]; + filename?: string; + importMeta?: Record; modules?: ModuleRegistry; randomSeed?: number; signal?: AbortSignal; @@ -45,9 +57,11 @@ export function run(source: string, options: RunOptions = {}): Promise"; + const module = parseModule(source, filename); const sourceHash = hashSource(source); const random = createRandomState(restoredSnapshot, options.randomSeed); + const entryPointArgs = options.entryPointArgs?.map((value) => deepCopyToSandbox(value)); const callerBindings = options.bindings === undefined ? {} @@ -77,14 +91,16 @@ export function run(source: string, options: RunOptions = {}): Promise({ snapshotIntervalMs: options.snapshotIntervalMs, snapshotPath: options.snapshotPath }); try { - const result = await interpret(createExecutableNode(module), { + const topLevelResult = await interpret(createExecutableNode(module), { budget, onYield: (yieldPoint) => { let snapshot: RunSnapshot | undefined; @@ -98,12 +114,35 @@ export function run(source: string, options: RunOptions = {}): Promise { + let snapshot: RunSnapshot | undefined; + const createSnapshot = () => + (snapshot ??= createRunSnapshot({ + bindings: yieldPoint.snapshot.bindings, + random, + sourceHash + })); + + snapshotScheduler.onYield(createSnapshot); + dumpController.onYield(createSnapshot); + }, + scope + }); await snapshotScheduler.finish(); const snapshot = createRunSnapshot({ - bindings: result.snapshot.bindings, + bindings: scope.snapshot().bindings, random, sourceHash }); @@ -122,6 +161,72 @@ export function run(source: string, options: RunOptions = {}): Promise[1]>["onYield"]; + scope: Scope; +}): Promise { + const defaultExport = input.scope.lookup("default"); + + if (!defaultExport.found) { + throw new Error(`Script ${input.filename} does not export a default function.`); + } + + if (!isSandboxClosure(defaultExport.value)) { + throw new TypeError(`Default export in ${input.filename} must be callable.`); + } + + const argumentBindings = Object.fromEntries( + input.args.map((value, index) => [createEntryPointArgName(index), value]) + ) as Record; + const entryScope = input.scope.child({ + __agentScriptEntryPoint: defaultExport.value, + ...argumentBindings + }); + + return interpret(createEntryPointAwait(input.args.length, input.module.span), { + budget: input.budget, + onYield: input.onYield, + scope: entryScope, + useScopeDirectly: true + }); +} + +function createEntryPointAwait(argCount: number, span: SourceSpan): AwaitExpression { + return { + type: "AwaitExpression", + argument: createEntryPointCall(argCount, span), + span + }; +} + +function createEntryPointCall(argCount: number, span: SourceSpan): CallExpression { + return { + type: "CallExpression", + callee: createIdentifier("__agentScriptEntryPoint", span), + arguments: Array.from({ length: argCount }, (_value, index) => + createIdentifier(createEntryPointArgName(index), span) + ), + optional: false, + span + }; +} + +function createIdentifier(name: string, span: SourceSpan): Identifier { + return { + type: "Identifier", + name, + span + }; +} + +function createEntryPointArgName(index: number): string { + return `__agentScriptEntryPointArg${index}`; +} + function createRandomState( snapshot: AgentScriptSnapshot | undefined, randomSeed: number | undefined @@ -145,7 +250,8 @@ function createRandomState( function createExecutableNode(module: Module): ParseResult { const executableStatements = module.body.filter( - (statement): statement is Exclude => statement.type !== "ImportDeclaration" + (statement): statement is Exclude => + statement.type !== "ImportDeclaration" ); if (executableStatements.length === 0) { From 646ce7e18e87a2b4a330a9d66138f344713012f2 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 23:36:25 -0500 Subject: [PATCH 048/111] feat(agent-script): export const initializer lookup --- docs/plans/agent-harness.md | 4 +- docs/plans/agent-harness.md.lock | 2 +- packages/agent-script/src/index.test.ts | 3 + packages/agent-script/src/index.ts | 6 ++ .../src/loader/find-exported.test.ts | 95 +++++++++++++++++++ .../agent-script/src/loader/find-exported.ts | 24 +++++ 6 files changed, 131 insertions(+), 3 deletions(-) create mode 100644 packages/agent-script/src/loader/find-exported.test.ts create mode 100644 packages/agent-script/src/loader/find-exported.ts diff --git a/docs/plans/agent-harness.md b/docs/plans/agent-harness.md index d26f8d86cd..d26b9c0a8b 100644 --- a/docs/plans/agent-harness.md +++ b/docs/plans/agent-harness.md @@ -236,8 +236,8 @@ tasks: Tests with parsed fixtures: present, absent, wrong name, nested block (should be ignored), `let`/`var` (should be ignored). status: - implement: open - test: open + implement: done + test: done commit: open - id: agent-harness-skeleton diff --git a/docs/plans/agent-harness.md.lock b/docs/plans/agent-harness.md.lock index 6e12dbb0f8..a13c8f5aa2 100644 --- a/docs/plans/agent-harness.md.lock +++ b/docs/plans/agent-harness.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T04:31:10.357Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T04:35:22.098Z"} \ No newline at end of file diff --git a/packages/agent-script/src/index.test.ts b/packages/agent-script/src/index.test.ts index 9dc6bcec61..e8885eafab 100644 --- a/packages/agent-script/src/index.test.ts +++ b/packages/agent-script/src/index.test.ts @@ -18,6 +18,7 @@ import { makeMetricModule } from "./modules/metric.js"; import { makeMcpModule } from "./modules/mcp.js"; import { makeTimeModule } from "./modules/time.js"; import { parse } from "./parse.js"; +import { findExportedConstInitializer } from "./loader/find-exported.js"; import { hashSource } from "./parse/hash.js"; import { restore } from "./restore.js"; import { run } from "./run.js"; @@ -33,6 +34,7 @@ describe("@poe-code/agent-script public exports", () => { expect(api.dump).toBe(dump); expect(api.restore).toBe(restore); expect(api.extractBlock).toBe(extractBlock); + expect(api.findExportedConstInitializer).toBe(findExportedConstInitializer); expect(api.splitFrontmatter).toBe(splitFrontmatter); expect(api.formatInterpreterError).toBe(formatInterpreterError); expect(api.deepCopyToSandbox).toBe(deepCopyToSandbox); @@ -51,6 +53,7 @@ describe("@poe-code/agent-script public exports", () => { "deepCopyToSandbox", "dump", "extractBlock", + "findExportedConstInitializer", "formatInterpreterError", "lint", "makeAgentModule", diff --git a/packages/agent-script/src/index.ts b/packages/agent-script/src/index.ts index a0a19ca6c4..c01f8a8254 100644 --- a/packages/agent-script/src/index.ts +++ b/packages/agent-script/src/index.ts @@ -7,7 +7,13 @@ export { formatInterpreterError, type InterpreterDiagnostic } from "./error/form export { deepCopyFromSandbox, deepCopyToSandbox } from "./interp/values.js"; export { runHarness } from "./runner/run-harness.js"; export { extractBlock } from "./loader/extract-block.js"; +export { findExportedConstInitializer } from "./loader/find-exported.js"; export { splitFrontmatter } from "./loader/frontmatter.js"; +export type { + ExportDefaultDeclaration, + ExportNamedDeclaration, + MetaProperty +} from "./parse.js"; export { makeAgentModule } from "./modules/agent.js"; export { makeEnvModule } from "./modules/env.js"; export { makeFailModule } from "./modules/fail.js"; diff --git a/packages/agent-script/src/loader/find-exported.test.ts b/packages/agent-script/src/loader/find-exported.test.ts new file mode 100644 index 0000000000..669794cc6e --- /dev/null +++ b/packages/agent-script/src/loader/find-exported.test.ts @@ -0,0 +1,95 @@ +import { describe, expect, it } from "vitest"; + +import { + parseModule, + type ExportNamedDeclaration, + type Module, + type VariableDeclaration, + type VariableDeclarationKind +} from "../parse/parser.js"; +import { findExportedConstInitializer } from "./find-exported.js"; + +describe("findExportedConstInitializer", () => { + it("returns the initializer expression for a matching top-level exported const", () => { + const module = parseModule("export const schema = S.Object({ value: true });"); + const statement = module.body[0] as ExportNamedDeclaration; + + const initializer = findExportedConstInitializer(module, "schema"); + + expect(initializer).toBe(statement.declaration.declarations[0]!.init); + expect(initializer).toMatchObject({ + type: "CallExpression", + callee: { + type: "MemberExpression", + object: { + type: "Identifier", + name: "S" + }, + property: { + type: "Identifier", + name: "Object" + } + } + }); + }); + + it("returns undefined when the export is absent", () => { + const module = parseModule("const schema = S.Object({});"); + + expect(findExportedConstInitializer(module, "schema")).toBeUndefined(); + }); + + it("returns undefined when the exported const has a different name", () => { + const module = parseModule("export const config = S.Object({});"); + + expect(findExportedConstInitializer(module, "schema")).toBeUndefined(); + }); + + it("does not recurse into nested blocks", () => { + const nestedExport = parseModule("export const schema = S.Object({});").body[0]!; + const module = parseModule("if (ready) {}"); + const statement = module.body[0]!; + if (statement.type !== "IfStatement" || statement.consequent.type !== "BlockStatement") { + throw new Error("Expected parsed if block fixture."); + } + statement.consequent.body = [nestedExport]; + + expect(findExportedConstInitializer(module, "schema")).toBeUndefined(); + }); + + it.each(["let", "var"] as const)("returns undefined for %s exports", (kind) => { + const module = moduleWithExportKind(kind); + + expect(findExportedConstInitializer(module, "schema")).toBeUndefined(); + }); + + it("returns undefined when the exported const has multiple declarators", () => { + const module = parseModule("export const schema = S.Object({});"); + const statement = module.body[0] as ExportNamedDeclaration; + statement.declaration.declarations.push({ + ...statement.declaration.declarations[0]!, + id: { + ...statement.declaration.declarations[0]!.id, + name: "config" + } + }); + + expect(findExportedConstInitializer(module, "schema")).toBeUndefined(); + }); + + it("returns undefined when the exported const binding is not an identifier", () => { + const module = parseModule("export const schema = S.Object({});"); + const statement = module.body[0] as ExportNamedDeclaration; + const destructuring = parseModule("const { schema } = source;").body[0] as VariableDeclaration; + statement.declaration.declarations[0]!.id = destructuring.declarations[0]!.id; + + expect(findExportedConstInitializer(module, "schema")).toBeUndefined(); + }); +}); + +function moduleWithExportKind(kind: VariableDeclarationKind | "var"): Module { + const module = parseModule("export const schema = S.Object({});"); + const statement = module.body[0] as ExportNamedDeclaration; + statement.declaration.kind = kind as VariableDeclarationKind; + return module; +} diff --git a/packages/agent-script/src/loader/find-exported.ts b/packages/agent-script/src/loader/find-exported.ts new file mode 100644 index 0000000000..4aad31ad99 --- /dev/null +++ b/packages/agent-script/src/loader/find-exported.ts @@ -0,0 +1,24 @@ +import type { Expression, Module } from "../parse/parser.js"; + +export function findExportedConstInitializer( + module: Module, + name: string +): Expression | undefined { + for (const statement of module.body) { + if (statement.type !== "ExportNamedDeclaration") { + continue; + } + + const declaration = statement.declaration; + if (declaration.kind !== "const" || declaration.declarations.length !== 1) { + continue; + } + + const declarator = declaration.declarations[0]!; + if (declarator.id.type === "Identifier" && declarator.id.name === name) { + return declarator.init; + } + } + + return undefined; +} From 470995e62232fe514d3ddb760337734845dfce82 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 23:38:37 -0500 Subject: [PATCH 049/111] feat(agent-harness): add package scaffold --- docs/plans/agent-harness.md | 4 ++-- docs/plans/agent-harness.md.lock | 2 +- package-lock.json | 14 ++++++++++++++ package.json | 1 + packages/agent-harness/README.md | 13 +++++++++++++ packages/agent-harness/package.json | 27 +++++++++++++++++++++++++++ packages/agent-harness/src/index.ts | 1 + packages/agent-harness/tsconfig.json | 11 +++++++++++ 8 files changed, 70 insertions(+), 3 deletions(-) create mode 100644 packages/agent-harness/README.md create mode 100644 packages/agent-harness/package.json create mode 100644 packages/agent-harness/src/index.ts create mode 100644 packages/agent-harness/tsconfig.json diff --git a/docs/plans/agent-harness.md b/docs/plans/agent-harness.md index d26b9c0a8b..2c2814a8cf 100644 --- a/docs/plans/agent-harness.md +++ b/docs/plans/agent-harness.md @@ -238,7 +238,7 @@ tasks: status: implement: done test: done - commit: open + commit: done - id: agent-harness-skeleton title: Create @poe-code/agent-harness package skeleton @@ -269,7 +269,7 @@ tasks: those land in subsequent tasks. The package must build green (`npm run build` succeeds) at the end of this task. status: - implement: open + implement: done commit: open - id: agent-harness-schema-module diff --git a/docs/plans/agent-harness.md.lock b/docs/plans/agent-harness.md.lock index a13c8f5aa2..42005aae8b 100644 --- a/docs/plans/agent-harness.md.lock +++ b/docs/plans/agent-harness.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T04:35:22.098Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T04:37:50.142Z"} \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 3e97f21b0e..411db9e4f7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -47,6 +47,7 @@ "@eslint/js": "^9.0.0", "@modelcontextprotocol/sdk": "^1.26.0", "@poe-code/agent-defs": "*", + "@poe-code/agent-harness": "*", "@poe-code/agent-harness-tools": "*", "@poe-code/agent-human-in-loop": "*", "@poe-code/agent-mcp-config": "*", @@ -1682,6 +1683,10 @@ "resolved": "packages/agent-defs", "link": true }, + "node_modules/@poe-code/agent-harness": { + "resolved": "packages/agent-harness", + "link": true + }, "node_modules/@poe-code/agent-harness-tools": { "resolved": "packages/agent-harness-tools", "link": true @@ -7263,6 +7268,15 @@ "name": "@poe-code/agent-defs", "version": "0.0.1" }, + "packages/agent-harness": { + "name": "@poe-code/agent-harness", + "version": "0.0.1", + "dependencies": { + "@poe-code/agent-harness-tools": "*", + "@poe-code/agent-script": "*", + "toolcraft-schema": "*" + } + }, "packages/agent-harness-tools": { "name": "@poe-code/agent-harness-tools", "version": "0.0.1", diff --git a/package.json b/package.json index 1af5fb3d9a..b7f4911556 100644 --- a/package.json +++ b/package.json @@ -126,6 +126,7 @@ "@eslint/js": "^9.0.0", "@modelcontextprotocol/sdk": "^1.26.0", "@poe-code/agent-defs": "*", + "@poe-code/agent-harness": "*", "@poe-code/agent-harness-tools": "*", "@poe-code/agent-human-in-loop": "*", "@poe-code/agent-mcp-config": "*", diff --git a/packages/agent-harness/README.md b/packages/agent-harness/README.md new file mode 100644 index 0000000000..9a223e0242 --- /dev/null +++ b/packages/agent-harness/README.md @@ -0,0 +1,13 @@ +# @poe-code/agent-harness + +Shared package for agent harness types and runtime orchestration APIs. + +This package is currently a scaffold. Loader, module, template, codegen, and CLI behavior will be added in later tasks. + +## Environment Variables + +This package does not read any environment variables. + +## Configuration + +This package does not read any configuration options. diff --git a/packages/agent-harness/package.json b/packages/agent-harness/package.json new file mode 100644 index 0000000000..a3a41675ff --- /dev/null +++ b/packages/agent-harness/package.json @@ -0,0 +1,27 @@ +{ + "name": "@poe-code/agent-harness", + "version": "0.0.1", + "private": true, + "type": "module", + "main": "dist/index.js", + "types": "dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.js" + } + }, + "scripts": { + "build": "tsc", + "test": "cd ../.. && vitest run packages/agent-harness/src", + "test:unit": "cd ../.. && vitest run packages/agent-harness/src" + }, + "files": [ + "dist" + ], + "dependencies": { + "@poe-code/agent-harness-tools": "*", + "@poe-code/agent-script": "*", + "toolcraft-schema": "*" + } +} diff --git a/packages/agent-harness/src/index.ts b/packages/agent-harness/src/index.ts new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/packages/agent-harness/src/index.ts @@ -0,0 +1 @@ + diff --git a/packages/agent-harness/tsconfig.json b/packages/agent-harness/tsconfig.json new file mode 100644 index 0000000000..44b01ee753 --- /dev/null +++ b/packages/agent-harness/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "outDir": "dist", + "rootDir": "src", + "noEmit": false, + "declaration": true + }, + "include": ["src"], + "exclude": ["**/*.test.ts"] +} From 01c1655150a083ca879dd43634bdda4d4d081f64 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 23:43:04 -0500 Subject: [PATCH 050/111] feat(agent-harness): add schema module --- docs/plans/agent-harness.md | 6 ++-- docs/plans/agent-harness.md.lock | 2 +- packages/agent-harness/src/index.ts | 2 +- .../agent-harness/src/modules/schema.test.ts | 35 +++++++++++++++++++ packages/agent-harness/src/modules/schema.ts | 5 +++ .../agent-script/src/interp/host-bridge.ts | 2 +- 6 files changed, 46 insertions(+), 6 deletions(-) create mode 100644 packages/agent-harness/src/modules/schema.test.ts create mode 100644 packages/agent-harness/src/modules/schema.ts diff --git a/docs/plans/agent-harness.md b/docs/plans/agent-harness.md index 2c2814a8cf..e7c37debee 100644 --- a/docs/plans/agent-harness.md +++ b/docs/plans/agent-harness.md @@ -270,7 +270,7 @@ tasks: (`npm run build` succeeds) at the end of this task. status: implement: done - commit: open + commit: done - id: agent-harness-schema-module title: Implement schema host module exposing toolcraft-schema S @@ -300,8 +300,8 @@ tasks: `lint({ modules })` accepts `import { S } from "schema"`. - All filesystem state through memfs (none expected here). status: - implement: open - test: open + implement: done + test: done commit: open - id: agent-harness-pair-resolver diff --git a/docs/plans/agent-harness.md.lock b/docs/plans/agent-harness.md.lock index 42005aae8b..4eb460e2ce 100644 --- a/docs/plans/agent-harness.md.lock +++ b/docs/plans/agent-harness.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T04:37:50.142Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T04:42:11.498Z"} \ No newline at end of file diff --git a/packages/agent-harness/src/index.ts b/packages/agent-harness/src/index.ts index 8b13789179..559402564b 100644 --- a/packages/agent-harness/src/index.ts +++ b/packages/agent-harness/src/index.ts @@ -1 +1 @@ - +export { makeSchemaModule } from "./modules/schema.js"; diff --git a/packages/agent-harness/src/modules/schema.test.ts b/packages/agent-harness/src/modules/schema.test.ts new file mode 100644 index 0000000000..e06750e51c --- /dev/null +++ b/packages/agent-harness/src/modules/schema.test.ts @@ -0,0 +1,35 @@ +import { lint, run } from "@poe-code/agent-script"; +import { describe, expect, it } from "vitest"; +import { S } from "toolcraft-schema"; + +import * as api from "../index.js"; +import { makeSchemaModule } from "./schema.js"; + +describe("makeSchemaModule", () => { + it("is re-exported from the package entrypoint", () => { + expect(api.makeSchemaModule).toBe(makeSchemaModule); + }); + + it("round-trips schema builders through agent-script run()", async () => { + const result = await run('import { S } from "schema"; return S.Object({ x: S.Number() });', { + modules: { + schema: makeSchemaModule() + } + }); + + expect(result).toMatchObject({ + ok: true, + returnValue: S.Object({ x: S.Number() }) + }); + }); + + it("registers its export list with agent-script lint()", () => { + expect( + lint('import { S } from "schema"; return S.Object({ x: S.Number() });', { + modules: { + schema: Object.keys(makeSchemaModule()) + } + }) + ).toEqual([]); + }); +}); diff --git a/packages/agent-harness/src/modules/schema.ts b/packages/agent-harness/src/modules/schema.ts new file mode 100644 index 0000000000..e238ce7f57 --- /dev/null +++ b/packages/agent-harness/src/modules/schema.ts @@ -0,0 +1,5 @@ +import { S } from "toolcraft-schema"; + +export function makeSchemaModule(): { S: typeof S } { + return { S }; +} diff --git a/packages/agent-script/src/interp/host-bridge.ts b/packages/agent-script/src/interp/host-bridge.ts index 423f0fbd57..83630af20b 100644 --- a/packages/agent-script/src/interp/host-bridge.ts +++ b/packages/agent-script/src/interp/host-bridge.ts @@ -35,7 +35,7 @@ function wrapCallerInjectedValue( budget: Budget ): SandboxValue { if (typeof value !== "function") { - return deepCopyToSandbox(value); + return copyHostResultToSandbox(value, [], budget); } const bindingName = name === "default" && value.name.length > 0 ? value.name : name; From c10d7640ccbd47a901356b4068cf0dc2a4769694 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 23:48:28 -0500 Subject: [PATCH 051/111] feat(agent-harness): resolve harness file pairs --- docs/plans/agent-harness.md | 6 +- docs/plans/agent-harness.md.lock | 2 +- packages/agent-harness/src/index.ts | 2 + .../agent-harness/src/loader/pair.test.ts | 143 ++++++++++++++++++ packages/agent-harness/src/loader/pair.ts | 80 ++++++++++ 5 files changed, 229 insertions(+), 4 deletions(-) create mode 100644 packages/agent-harness/src/loader/pair.test.ts create mode 100644 packages/agent-harness/src/loader/pair.ts diff --git a/docs/plans/agent-harness.md b/docs/plans/agent-harness.md index e7c37debee..047b432c83 100644 --- a/docs/plans/agent-harness.md +++ b/docs/plans/agent-harness.md @@ -302,7 +302,7 @@ tasks: status: implement: done test: done - commit: open + commit: done - id: agent-harness-pair-resolver title: Resolve .md ↔ .ajs in the same directory @@ -342,8 +342,8 @@ tasks: .ajs, missing .md, wrong extension input, directory passed instead of file. status: - implement: open - test: open + implement: done + test: done commit: open - id: agent-harness-discovery diff --git a/docs/plans/agent-harness.md.lock b/docs/plans/agent-harness.md.lock index 4eb460e2ce..b1ec6f68ba 100644 --- a/docs/plans/agent-harness.md.lock +++ b/docs/plans/agent-harness.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T04:42:11.498Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T04:47:22.782Z"} \ No newline at end of file diff --git a/packages/agent-harness/src/index.ts b/packages/agent-harness/src/index.ts index 559402564b..168896e144 100644 --- a/packages/agent-harness/src/index.ts +++ b/packages/agent-harness/src/index.ts @@ -1 +1,3 @@ export { makeSchemaModule } from "./modules/schema.js"; +export { InvalidPairExtensionError, MissingPairError, resolvePair } from "./loader/pair.js"; +export type { HarnessFs, HarnessPair } from "./loader/pair.js"; diff --git a/packages/agent-harness/src/loader/pair.test.ts b/packages/agent-harness/src/loader/pair.test.ts new file mode 100644 index 0000000000..130cd9b3f9 --- /dev/null +++ b/packages/agent-harness/src/loader/pair.test.ts @@ -0,0 +1,143 @@ +import { isAbsolute, resolve } from "node:path"; +import { createFsFromVolume, Volume } from "memfs"; +import { describe, expect, it } from "vitest"; + +import * as api from "../index.js"; +import { + InvalidPairExtensionError, + MissingPairError, + resolvePair, + type HarnessFs +} from "./pair.js"; + +function memfs(files: Record, cwd = "/"): HarnessFs { + const volume = Volume.fromJSON(files, "/"); + const fs = createFsFromVolume(volume).promises; + + return { + stat(path) { + return fs.stat(isAbsolute(path) ? path : resolve(cwd, path)); + } + }; +} + +describe("resolvePair", () => { + it("is re-exported from the package entrypoint", () => { + expect(api.resolvePair).toBe(resolvePair); + }); + + it("resolves a pair from either side when both files exist", async () => { + const fs = memfs({ + "/repo/harness/review.md": "# Review", + "/repo/harness/review.ajs": "return true;" + }); + + await expect(resolvePair("/repo/harness/review.md", fs)).resolves.toEqual({ + ajsPath: "/repo/harness/review.ajs", + mdPath: "/repo/harness/review.md", + basename: "review" + }); + + await expect(resolvePair("/repo/harness/review.ajs", fs)).resolves.toEqual({ + ajsPath: "/repo/harness/review.ajs", + mdPath: "/repo/harness/review.md", + basename: "review" + }); + }); + + it("preserves dotted basenames and relative directories", async () => { + const fs = memfs( + { + "/repo/harness/review.case.md": "# Review", + "/repo/harness/review.case.ajs": "return true;" + }, + "/repo" + ); + + await expect(resolvePair("harness/review.case.md", fs)).resolves.toEqual({ + ajsPath: "harness/review.case.ajs", + mdPath: "harness/review.case.md", + basename: "review.case" + }); + }); + + it("throws MissingPairError naming ajs when the .ajs sibling is missing", async () => { + const fs = memfs({ + "/repo/harness/review.md": "# Review" + }); + + await expect(resolvePair("/repo/harness/review.md", fs)).rejects.toMatchObject({ + name: "MissingPairError", + side: "ajs", + path: "/repo/harness/review.ajs" + }); + await expect(resolvePair("/repo/harness/review.md", fs)).rejects.toBeInstanceOf( + MissingPairError + ); + }); + + it("throws MissingPairError naming the input side when the input file is missing", async () => { + const fs = memfs({ + "/repo/harness/review.ajs": "return true;" + }); + + await expect(resolvePair("/repo/harness/review.md", fs)).rejects.toMatchObject({ + name: "MissingPairError", + side: "md", + path: "/repo/harness/review.md" + }); + }); + + it("throws MissingPairError naming md when the .md sibling is missing", async () => { + const fs = memfs({ + "/repo/harness/review.ajs": "return true;" + }); + + await expect(resolvePair("/repo/harness/review.ajs", fs)).rejects.toMatchObject({ + name: "MissingPairError", + side: "md", + path: "/repo/harness/review.md" + }); + }); + + it("throws MissingPairError naming ajs when the .ajs input is a directory", async () => { + const fs = memfs({ + "/repo/harness/review.ajs": null, + "/repo/harness/review.md": "# Review" + }); + + await expect(resolvePair("/repo/harness/review.ajs", fs)).rejects.toMatchObject({ + name: "MissingPairError", + side: "ajs", + path: "/repo/harness/review.ajs" + }); + }); + + it("rejects input paths without .md or .ajs extensions", async () => { + const fs = memfs({ + "/repo/harness/review.txt": "wrong" + }); + + await expect(resolvePair("/repo/harness/review.txt", fs)).rejects.toMatchObject({ + name: "InvalidPairExtensionError", + extension: ".txt", + path: "/repo/harness/review.txt" + }); + await expect(resolvePair("/repo/harness/review.txt", fs)).rejects.toBeInstanceOf( + InvalidPairExtensionError + ); + }); + + it("treats directories as missing pair files", async () => { + const fs = memfs({ + "/repo/harness/review.md": null, + "/repo/harness/review.ajs": "return true;" + }); + + await expect(resolvePair("/repo/harness/review.md", fs)).rejects.toMatchObject({ + name: "MissingPairError", + side: "md", + path: "/repo/harness/review.md" + }); + }); +}); diff --git a/packages/agent-harness/src/loader/pair.ts b/packages/agent-harness/src/loader/pair.ts new file mode 100644 index 0000000000..bd63b273a5 --- /dev/null +++ b/packages/agent-harness/src/loader/pair.ts @@ -0,0 +1,80 @@ +import nodeFs from "node:fs/promises"; +import { basename as pathBasename, dirname, extname, join } from "node:path"; + +export type HarnessPair = { + ajsPath: string; + mdPath: string; + basename: string; +}; + +export type HarnessFs = { + stat(path: string): Promise<{ isFile(): boolean }>; +}; + +type HarnessPairSide = "ajs" | "md"; + +export class MissingPairError extends Error { + readonly side: HarnessPairSide; + readonly path: string; + + constructor(side: HarnessPairSide, path: string) { + super(`Missing harness ${side} file: ${path}`); + this.name = "MissingPairError"; + this.side = side; + this.path = path; + } +} + +export class InvalidPairExtensionError extends Error { + readonly extension: string; + readonly path: string; + + constructor(path: string, extension: string) { + super(`Harness pair input must be a .md or .ajs file: ${path}`); + this.name = "InvalidPairExtensionError"; + this.extension = extension; + this.path = path; + } +} + +export async function resolvePair(inputPath: string, fs: HarnessFs = nodeFs): Promise { + const extension = extname(inputPath); + + if (extension !== ".md" && extension !== ".ajs") { + throw new InvalidPairExtensionError(inputPath, extension); + } + + const pairBasename = pathBasename(inputPath, extension); + const pairDir = dirname(inputPath); + const pair: HarnessPair = { + ajsPath: join(pairDir, `${pairBasename}.ajs`), + mdPath: join(pairDir, `${pairBasename}.md`), + basename: pairBasename + }; + + const checks: Array<{ side: HarnessPairSide; path: string }> = + extension === ".md" + ? [ + { side: "md", path: pair.mdPath }, + { side: "ajs", path: pair.ajsPath } + ] + : [ + { side: "ajs", path: pair.ajsPath }, + { side: "md", path: pair.mdPath } + ]; + + for (const check of checks) { + let stat: { isFile(): boolean }; + try { + stat = await fs.stat(check.path); + } catch { + throw new MissingPairError(check.side, check.path); + } + + if (!stat.isFile()) { + throw new MissingPairError(check.side, check.path); + } + } + + return pair; +} From a3760fd35f58365517bfcfef74c76a5cabc0af71 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Sun, 3 May 2026 23:52:35 -0500 Subject: [PATCH 052/111] feat(agent-harness): discover harness pairs --- docs/plans/agent-harness.md | 8 +- docs/plans/agent-harness.md.lock | 2 +- .../src/discovery/discover.test.ts | 130 ++++++++++++++++++ .../agent-harness/src/discovery/discover.ts | 61 ++++++++ packages/agent-harness/src/index.ts | 1 + packages/agent-harness/src/loader/pair.ts | 6 +- 6 files changed, 202 insertions(+), 6 deletions(-) create mode 100644 packages/agent-harness/src/discovery/discover.test.ts create mode 100644 packages/agent-harness/src/discovery/discover.ts diff --git a/docs/plans/agent-harness.md b/docs/plans/agent-harness.md index 047b432c83..0b7d1a3631 100644 --- a/docs/plans/agent-harness.md +++ b/docs/plans/agent-harness.md @@ -344,7 +344,7 @@ tasks: status: implement: done test: done - commit: open + commit: done - id: agent-harness-discovery title: Discover harness pairs in .poe-code/harnesses/ @@ -380,9 +380,9 @@ tasks: half-valid subdir (just .md), unrelated files mixed in, missing root. status: - implement: open - test: open - commit: open + implement: done + test: done + commit: done - id: agent-harness-extract-schema title: Extract `export const schema` initializer from .ajs diff --git a/docs/plans/agent-harness.md.lock b/docs/plans/agent-harness.md.lock index b1ec6f68ba..ca0e6502ec 100644 --- a/docs/plans/agent-harness.md.lock +++ b/docs/plans/agent-harness.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T04:47:22.782Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T04:51:32.887Z"} \ No newline at end of file diff --git a/packages/agent-harness/src/discovery/discover.test.ts b/packages/agent-harness/src/discovery/discover.test.ts new file mode 100644 index 0000000000..b9fa893780 --- /dev/null +++ b/packages/agent-harness/src/discovery/discover.test.ts @@ -0,0 +1,130 @@ +import { isAbsolute, resolve } from "node:path"; +import { createFsFromVolume, Volume } from "memfs"; +import { describe, expect, it } from "vitest"; + +import * as api from "../index.js"; +import { discoverHarnesses } from "./discover.js"; +import type { HarnessFs } from "../loader/pair.js"; + +function memfs(files: Record, cwd = "/"): HarnessFs { + const volume = Volume.fromJSON(files, "/"); + const fs = createFsFromVolume(volume).promises; + + return { + readdir(path, options) { + return fs.readdir(isAbsolute(path) ? path : resolve(cwd, path), options); + }, + stat(path) { + return fs.stat(isAbsolute(path) ? path : resolve(cwd, path)); + } + }; +} + +describe("discoverHarnesses", () => { + it("is re-exported from the package entrypoint", () => { + expect(api.discoverHarnesses).toBe(discoverHarnesses); + }); + + it("returns an empty list for an empty root", async () => { + const fs = memfs({ + "/repo/.poe-code/harnesses": null + }); + + await expect(discoverHarnesses("/repo/.poe-code/harnesses", fs)).resolves.toEqual([]); + }); + + it("discovers one valid pair in a first-level subdirectory", async () => { + const fs = memfs({ + "/repo/.poe-code/harnesses/review/review.md": "# Review", + "/repo/.poe-code/harnesses/review/review.ajs": "export default async () => true;" + }); + + await expect(discoverHarnesses("/repo/.poe-code/harnesses", fs)).resolves.toEqual([ + { + ajsPath: "/repo/.poe-code/harnesses/review/review.ajs", + mdPath: "/repo/.poe-code/harnesses/review/review.md", + basename: "review" + } + ]); + }); + + it("discovers multiple valid pairs sorted alphabetically by basename", async () => { + const fs = memfs({ + "/repo/.poe-code/harnesses/zebra/zebra.md": "# Zebra", + "/repo/.poe-code/harnesses/zebra/zebra.ajs": "export default async () => true;", + "/repo/.poe-code/harnesses/alpha/alpha.md": "# Alpha", + "/repo/.poe-code/harnesses/alpha/alpha.ajs": "export default async () => true;" + }); + + await expect(discoverHarnesses("/repo/.poe-code/harnesses", fs)).resolves.toEqual([ + { + ajsPath: "/repo/.poe-code/harnesses/alpha/alpha.ajs", + mdPath: "/repo/.poe-code/harnesses/alpha/alpha.md", + basename: "alpha" + }, + { + ajsPath: "/repo/.poe-code/harnesses/zebra/zebra.ajs", + mdPath: "/repo/.poe-code/harnesses/zebra/zebra.md", + basename: "zebra" + } + ]); + }); + + it("skips half-valid subdirectories", async () => { + const fs = memfs({ + "/repo/.poe-code/harnesses/review/review.md": "# Review", + "/repo/.poe-code/harnesses/build/build.md": "# Build", + "/repo/.poe-code/harnesses/build/build.ajs": "export default async () => true;" + }); + + await expect(discoverHarnesses("/repo/.poe-code/harnesses", fs)).resolves.toEqual([ + { + ajsPath: "/repo/.poe-code/harnesses/build/build.ajs", + mdPath: "/repo/.poe-code/harnesses/build/build.md", + basename: "build" + } + ]); + }); + + it("skips pairs that do not match their containing directory name", async () => { + const fs = memfs({ + "/repo/.poe-code/harnesses/review/other.md": "# Other", + "/repo/.poe-code/harnesses/review/other.ajs": "export default async () => true;", + "/repo/.poe-code/harnesses/build/build.md": "# Build", + "/repo/.poe-code/harnesses/build/build.ajs": "export default async () => true;" + }); + + await expect(discoverHarnesses("/repo/.poe-code/harnesses", fs)).resolves.toEqual([ + { + ajsPath: "/repo/.poe-code/harnesses/build/build.ajs", + mdPath: "/repo/.poe-code/harnesses/build/build.md", + basename: "build" + } + ]); + }); + + it("ignores unrelated files and nested harness-like pairs", async () => { + const fs = memfs({ + "/repo/.poe-code/harnesses/README.md": "# Harnesses", + "/repo/.poe-code/harnesses/review/notes.txt": "notes", + "/repo/.poe-code/harnesses/review/review.md": "# Review", + "/repo/.poe-code/harnesses/review/review.ajs": "export default async () => true;", + "/repo/.poe-code/harnesses/nested/child/child.md": "# Child", + "/repo/.poe-code/harnesses/nested/child/child.ajs": "export default async () => true;" + }); + + await expect(discoverHarnesses("/repo/.poe-code/harnesses", fs)).resolves.toEqual([ + { + ajsPath: "/repo/.poe-code/harnesses/review/review.ajs", + mdPath: "/repo/.poe-code/harnesses/review/review.md", + basename: "review" + } + ]); + }); + + it("returns an empty list for a missing root", async () => { + const fs = memfs({}); + + await expect(discoverHarnesses("/repo/.poe-code/harnesses", fs)).resolves.toEqual([]); + }); +}); diff --git a/packages/agent-harness/src/discovery/discover.ts b/packages/agent-harness/src/discovery/discover.ts new file mode 100644 index 0000000000..53645531c0 --- /dev/null +++ b/packages/agent-harness/src/discovery/discover.ts @@ -0,0 +1,61 @@ +import nodeFs from "node:fs/promises"; +import { join } from "node:path"; + +import { MissingPairError, resolvePair, type HarnessFs, type HarnessPair } from "../loader/pair.js"; + +type DirectoryEntry = string | { name: string; isDirectory(): boolean }; + +function isMissingDirectory(error: unknown): boolean { + return ( + !!error && + typeof error === "object" && + "code" in error && + ((error as { code?: unknown }).code === "ENOENT" || + (error as { code?: unknown }).code === "ENOTDIR") + ); +} + +export async function discoverHarnesses( + rootDir: string, + fs: HarnessFs = nodeFs +): Promise { + if (!fs.readdir) { + throw new Error("discoverHarnesses requires a filesystem with readdir support"); + } + + let entries: DirectoryEntry[]; + try { + entries = await fs.readdir(rootDir, { withFileTypes: true }); + } catch (error) { + if (isMissingDirectory(error)) { + return []; + } + throw error; + } + + const pairs: HarnessPair[] = []; + for (const entry of entries) { + const name = typeof entry === "string" ? entry : entry.name; + if (typeof entry !== "string" && !entry.isDirectory()) { + continue; + } + + if (typeof entry === "string") { + const stat = await fs.stat(join(rootDir, entry)); + if (!stat.isDirectory?.()) { + continue; + } + } + + try { + pairs.push(await resolvePair(join(rootDir, name, `${name}.md`), fs)); + } catch (error) { + if (error instanceof MissingPairError) { + continue; + } + throw error; + } + } + + return pairs.sort((left, right) => left.basename.localeCompare(right.basename)); +} diff --git a/packages/agent-harness/src/index.ts b/packages/agent-harness/src/index.ts index 168896e144..4a7753cdd5 100644 --- a/packages/agent-harness/src/index.ts +++ b/packages/agent-harness/src/index.ts @@ -1,3 +1,4 @@ export { makeSchemaModule } from "./modules/schema.js"; +export { discoverHarnesses } from "./discovery/discover.js"; export { InvalidPairExtensionError, MissingPairError, resolvePair } from "./loader/pair.js"; export type { HarnessFs, HarnessPair } from "./loader/pair.js"; diff --git a/packages/agent-harness/src/loader/pair.ts b/packages/agent-harness/src/loader/pair.ts index bd63b273a5..192c767922 100644 --- a/packages/agent-harness/src/loader/pair.ts +++ b/packages/agent-harness/src/loader/pair.ts @@ -8,7 +8,11 @@ export type HarnessPair = { }; export type HarnessFs = { - stat(path: string): Promise<{ isFile(): boolean }>; + readdir?( + path: string, + options?: { withFileTypes?: boolean } + ): Promise>; + stat(path: string): Promise<{ isFile(): boolean; isDirectory?(): boolean }>; }; type HarnessPairSide = "ajs" | "md"; From acf9f0e0b2c18172566b347f73a05b0d1d424680 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 00:02:01 -0500 Subject: [PATCH 053/111] feat(agent-harness): extract script schemas --- docs/plans/agent-harness.md | 4 +- docs/plans/agent-harness.md.lock | 2 +- packages/agent-harness/src/index.ts | 1 + .../src/loader/extract-schema.test.ts | 112 ++++++++++++++++++ .../src/loader/extract-schema.ts | 80 +++++++++++++ packages/agent-script/src/index.test.ts | 10 +- packages/agent-script/src/index.ts | 8 +- .../agent-script/src/interp/host-bridge.ts | 33 +++++- packages/agent-script/src/run.ts | 10 +- 9 files changed, 242 insertions(+), 18 deletions(-) create mode 100644 packages/agent-harness/src/loader/extract-schema.test.ts create mode 100644 packages/agent-harness/src/loader/extract-schema.ts diff --git a/docs/plans/agent-harness.md b/docs/plans/agent-harness.md index 0b7d1a3631..7d0d76f505 100644 --- a/docs/plans/agent-harness.md +++ b/docs/plans/agent-harness.md @@ -429,8 +429,8 @@ tasks: from "agent"`. - Tight budget rejects non-terminating initializers. status: - implement: open - test: open + implement: done + test: done commit: open - id: agent-harness-validate-frontmatter diff --git a/docs/plans/agent-harness.md.lock b/docs/plans/agent-harness.md.lock index ca0e6502ec..3349f68f72 100644 --- a/docs/plans/agent-harness.md.lock +++ b/docs/plans/agent-harness.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T04:51:32.887Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T05:00:36.569Z"} \ No newline at end of file diff --git a/packages/agent-harness/src/index.ts b/packages/agent-harness/src/index.ts index 4a7753cdd5..dd6fb125d8 100644 --- a/packages/agent-harness/src/index.ts +++ b/packages/agent-harness/src/index.ts @@ -1,4 +1,5 @@ export { makeSchemaModule } from "./modules/schema.js"; export { discoverHarnesses } from "./discovery/discover.js"; +export { extractSchema } from "./loader/extract-schema.js"; export { InvalidPairExtensionError, MissingPairError, resolvePair } from "./loader/pair.js"; export type { HarnessFs, HarnessPair } from "./loader/pair.js"; diff --git a/packages/agent-harness/src/loader/extract-schema.test.ts b/packages/agent-harness/src/loader/extract-schema.test.ts new file mode 100644 index 0000000000..5e3884b286 --- /dev/null +++ b/packages/agent-harness/src/loader/extract-schema.test.ts @@ -0,0 +1,112 @@ +import { describe, expect, it } from "vitest"; +import { S } from "toolcraft-schema"; + +import * as api from "../index.js"; +import { extractSchema } from "./extract-schema.js"; + +describe("extractSchema", () => { + it("is re-exported from the package entrypoint", () => { + expect(api.extractSchema).toBe(extractSchema); + }); + + it("returns undefined when the script has no exported schema const", async () => { + await expect( + extractSchema('export default async () => "ok";', "/tmp/no-schema.ajs") + ).resolves.toBeUndefined(); + }); + + it("returns the descriptor for a simple object schema", async () => { + await expect( + extractSchema( + "export const schema = S.Object({ name: S.String(), retries: S.Number() });", + "/tmp/simple.ajs" + ) + ).resolves.toEqual( + S.Object({ + name: S.String(), + retries: S.Number() + }) + ); + }); + + it("returns the descriptor for nested optional enum array schemas", async () => { + await expect( + extractSchema( + [ + "export const schema = S.Object({", + ' mode: S.Enum(["fast", "safe"]),', + " tags: S.Optional(S.Array(S.String())),", + " retries: S.Array(S.Optional(S.Number()))", + "});" + ].join("\n"), + "/tmp/nested.ajs" + ) + ).resolves.toEqual( + S.Object({ + mode: S.Enum(["fast", "safe"]), + tags: S.Optional(S.Array(S.String())), + retries: S.Array(S.Optional(S.Number())) + }) + ); + }); + + it("returns the awaited descriptor when the initializer produces a promise", async () => { + await expect( + extractSchema( + "export const schema = Promise.resolve(S.Object({ name: S.String() }));", + "/tmp/promise.ajs" + ) + ).resolves.toEqual( + S.Object({ + name: S.String() + }) + ); + }); + + it("does not evaluate unrelated top-level script code", async () => { + await expect( + extractSchema( + [ + "const external = missingIdentifier;", + "export const schema = S.Object({ name: S.String() });" + ].join("\n"), + "/tmp/top-level.ajs" + ) + ).resolves.toEqual( + S.Object({ + name: S.String() + }) + ); + }); + + it("throws a clear error when the initializer references a non-schema identifier", async () => { + await expect( + extractSchema( + "const external = S.String(); export const schema = external;", + "/tmp/external.ajs" + ) + ).rejects.toThrow( + /Failed to evaluate schema initializer in \/tmp\/external\.ajs: schema initializer must be pure/ + ); + }); + + it("throws a clear error when the initializer depends on an agent import", async () => { + await expect( + extractSchema( + 'import { taskSchema } from "agent"; export const schema = taskSchema;', + "/tmp/agent-import.ajs" + ) + ).rejects.toThrow( + /Failed to evaluate schema initializer in \/tmp\/agent-import\.ajs: schema initializer must be pure/ + ); + }); + + it("rejects non-terminating initializers with a tight budget", async () => { + await expect( + extractSchema( + "export const schema = ((loop) => loop(loop))((loop) => loop(loop));", + "/tmp/infinite.ajs" + ) + ).rejects.toThrow(/Sandbox budget exceeded/); + }); +}); diff --git a/packages/agent-harness/src/loader/extract-schema.ts b/packages/agent-harness/src/loader/extract-schema.ts new file mode 100644 index 0000000000..352d32dc0d --- /dev/null +++ b/packages/agent-harness/src/loader/extract-schema.ts @@ -0,0 +1,80 @@ +import { + Budget, + deepCopyFromSandbox, + findExportedConstInitializer, + parseModule, + run +} from "@poe-code/agent-script"; +import type { AnySchema as SchemaDescriptor } from "toolcraft-schema"; + +import { makeSchemaModule } from "../modules/schema.js"; + +const SCHEMA_EXTRACTION_BUDGET = { + arrayLength: 1_000, + maxCallDepth: 20, + maxSteps: 200, + stringLength: 100_000 +} as const; + +export async function extractSchema( + ajsSource: string, + ajsPath: string +): Promise { + const module = parseModule(ajsSource, ajsPath); + const initializer = findExportedConstInitializer(module, "schema"); + + if (initializer === undefined) { + return undefined; + } + + const initializerSource = ajsSource.slice( + initializer.span.start.offset, + initializer.span.end.offset + ); + const result = await evaluateSchemaInitializer(initializerSource, ajsPath); + + if (!result.ok) { + throwSchemaInitializerError(ajsPath, result.error.message); + } + + return (await deepCopyFromSandbox(result.returnValue)) as SchemaDescriptor; +} + +async function evaluateSchemaInitializer(initializerSource: string, ajsPath: string) { + try { + return await run(`import { S } from "schema"; return ${initializerSource};`, { + budget: new Budget(SCHEMA_EXTRACTION_BUDGET), + filename: ajsPath, + modules: { + schema: makeSchemaModule() + } + }); + } catch (error) { + throwSchemaInitializerError(ajsPath, error); + } +} + +function throwSchemaInitializerError(ajsPath: string, cause: unknown): never { + const detail = readErrorMessage(cause); + throw new Error( + `Failed to evaluate schema initializer in ${ajsPath}: schema initializer must be pure; only "schema" module imports allowed. ${detail}`, + { cause } + ); +} + +function readErrorMessage(error: unknown): string { + if (error instanceof Error) { + return error.message; + } + + if ( + typeof error === "object" && + error !== null && + "message" in error && + typeof error.message === "string" + ) { + return error.message; + } + + return String(error); +} diff --git a/packages/agent-script/src/index.test.ts b/packages/agent-script/src/index.test.ts index e8885eafab..baaf2a0987 100644 --- a/packages/agent-script/src/index.test.ts +++ b/packages/agent-script/src/index.test.ts @@ -5,6 +5,7 @@ import { dump } from "./dump.js"; import { extractBlock } from "./loader/extract-block.js"; import { splitFrontmatter } from "./loader/frontmatter.js"; import { formatInterpreterError } from "./error/format.js"; +import { Budget, SandboxError } from "./interp/budget.js"; import { deepCopyFromSandbox, deepCopyToSandbox } from "./interp/values.js"; import { lint } from "./lint.js"; import { lint as lintFromIndex } from "./lint/index.js"; @@ -18,6 +19,7 @@ import { makeMetricModule } from "./modules/metric.js"; import { makeMcpModule } from "./modules/mcp.js"; import { makeTimeModule } from "./modules/time.js"; import { parse } from "./parse.js"; +import { parseModule } from "./parse/parser.js"; import { findExportedConstInitializer } from "./loader/find-exported.js"; import { hashSource } from "./parse/hash.js"; import { restore } from "./restore.js"; @@ -25,8 +27,11 @@ import { run } from "./run.js"; import { runHarness } from "./runner/run-harness.js"; describe("@poe-code/agent-script public exports", () => { - it("re-exports the placeholder entrypoints", () => { + it("re-exports the public entrypoints", () => { + expect(api.Budget).toBe(Budget); + expect(api.SandboxError).toBe(SandboxError); expect(api.parse).toBe(parse); + expect(api.parseModule).toBe(parseModule); expect(api.lint).toBe(lint); expect(lint).toBe(lintFromIndex); expect(api.run).toBe(run); @@ -49,6 +54,8 @@ describe("@poe-code/agent-script public exports", () => { expect(api.makeMcpModule).toBe(makeMcpModule); expect(api.makeTimeModule).toBe(makeTimeModule); expect(Object.keys(api).sort()).toEqual([ + "Budget", + "SandboxError", "deepCopyFromSandbox", "deepCopyToSandbox", "dump", @@ -66,6 +73,7 @@ describe("@poe-code/agent-script public exports", () => { "makeMetricModule", "makeTimeModule", "parse", + "parseModule", "restore", "run", "runHarness", diff --git a/packages/agent-script/src/index.ts b/packages/agent-script/src/index.ts index c01f8a8254..8efe76b753 100644 --- a/packages/agent-script/src/index.ts +++ b/packages/agent-script/src/index.ts @@ -1,19 +1,17 @@ export { parse } from "./parse.js"; +export { parseModule } from "./parse/parser.js"; export { lint, type Diagnostic, type LintOptions } from "./lint.js"; export { run } from "./run.js"; export { dump } from "./dump.js"; export { restore } from "./restore.js"; +export { Budget, SandboxError } from "./interp/budget.js"; export { formatInterpreterError, type InterpreterDiagnostic } from "./error/format.js"; export { deepCopyFromSandbox, deepCopyToSandbox } from "./interp/values.js"; export { runHarness } from "./runner/run-harness.js"; export { extractBlock } from "./loader/extract-block.js"; export { findExportedConstInitializer } from "./loader/find-exported.js"; export { splitFrontmatter } from "./loader/frontmatter.js"; -export type { - ExportDefaultDeclaration, - ExportNamedDeclaration, - MetaProperty -} from "./parse.js"; +export type { ExportDefaultDeclaration, ExportNamedDeclaration, MetaProperty } from "./parse.js"; export { makeAgentModule } from "./modules/agent.js"; export { makeEnvModule } from "./modules/env.js"; export { makeFailModule } from "./modules/fail.js"; diff --git a/packages/agent-script/src/interp/host-bridge.ts b/packages/agent-script/src/interp/host-bridge.ts index 83630af20b..1f06180849 100644 --- a/packages/agent-script/src/interp/host-bridge.ts +++ b/packages/agent-script/src/interp/host-bridge.ts @@ -15,7 +15,17 @@ import { const AsyncFunction = (async () => undefined).constructor; -export type CallerInjectedBinding = SandboxValue | ((...args: readonly unknown[]) => unknown); +type CallerInjectedFunction = { + bivarianceHack(...args: readonly unknown[]): unknown; +}["bivarianceHack"]; + +export type CallerInjectedBinding = + | SandboxValue + | CallerInjectedFunction + | readonly CallerInjectedBinding[] + | { + readonly [key: string]: CallerInjectedBinding; + }; export function wrapCallerInjectedBindings( bindings: Record, @@ -39,9 +49,10 @@ function wrapCallerInjectedValue( } const bindingName = name === "default" && value.name.length > 0 ? value.name : name; + const callable = value as (...args: readonly unknown[]) => unknown; return createSandboxClosure({ - ...(isAsyncFunction(value) ? { async: true as const } : {}), + ...(isAsyncFunction(callable) ? { async: true as const } : {}), call: (args, context) => { try { const stackFrames = context?.stack ?? []; @@ -52,7 +63,7 @@ function wrapCallerInjectedValue( ); return copyHostResultToSandbox( - Reflect.apply(value, undefined, hostArgs), + Reflect.apply(callable, undefined, hostArgs), stackFrames, budget ); @@ -278,14 +289,22 @@ function copyHostValueToSandbox( } if ("get" in descriptor || "set" in descriptor) { - throw new TypeError(`Unsupported sandbox value at ${joinPath(path, key)}: accessor property`); + throw new TypeError( + `Unsupported sandbox value at ${joinPath(path, key)}: accessor property` + ); } Object.defineProperty(copy, key, { enumerable: true, configurable: true, writable: true, - value: copyHostValueToSandbox(descriptor.value, stackFrames, budget, state, joinPath(path, key)) + value: copyHostValueToSandbox( + descriptor.value, + stackFrames, + budget, + state, + joinPath(path, key) + ) }); } @@ -305,7 +324,9 @@ function isPlainObject(value: unknown): value is Record { } function joinPath(path: string, key: string): string { - return /^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(key) ? `${path}.${key}` : `${path}[${JSON.stringify(key)}]`; + return /^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(key) + ? `${path}.${key}` + : `${path}[${JSON.stringify(key)}]`; } function readPathName(path: string): string { diff --git a/packages/agent-script/src/run.ts b/packages/agent-script/src/run.ts index 04f3936a56..de87e6e94a 100644 --- a/packages/agent-script/src/run.ts +++ b/packages/agent-script/src/run.ts @@ -47,9 +47,13 @@ export type RunSnapshot = AgentScriptSnapshot & { }; }; -export type RunResult = Omit & { - snapshot: RunSnapshot; -}; +type WithRunSnapshot = TResult extends unknown + ? Omit & { + snapshot: RunSnapshot; + } + : never; + +export type RunResult = WithRunSnapshot; export function run(source: string, options: RunOptions = {}): Promise { const dumpController = createDumpController(); From 368b509570be36287f6f603f1c984f173aef5217 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 00:06:39 -0500 Subject: [PATCH 054/111] feat(agent-harness): validate frontmatter --- docs/plans/agent-harness.md | 6 +- docs/plans/agent-harness.md.lock | 2 +- packages/agent-harness/src/index.ts | 1 + .../agent-harness/src/loader/validate.test.ts | 143 ++++++++++++++++++ packages/agent-harness/src/loader/validate.ts | 34 +++++ 5 files changed, 182 insertions(+), 4 deletions(-) create mode 100644 packages/agent-harness/src/loader/validate.test.ts create mode 100644 packages/agent-harness/src/loader/validate.ts diff --git a/docs/plans/agent-harness.md b/docs/plans/agent-harness.md index 7d0d76f505..f5dbbcb7fe 100644 --- a/docs/plans/agent-harness.md +++ b/docs/plans/agent-harness.md @@ -431,7 +431,7 @@ tasks: status: implement: done test: done - commit: open + commit: done - id: agent-harness-validate-frontmatter title: Validate .md frontmatter against a SchemaDescriptor @@ -468,8 +468,8 @@ tasks: required fields. memfs only if you read the .md; this function itself takes a parsed object, no fs needed. status: - implement: open - test: open + implement: done + test: done commit: open - id: agent-harness-run diff --git a/docs/plans/agent-harness.md.lock b/docs/plans/agent-harness.md.lock index 3349f68f72..903cc01160 100644 --- a/docs/plans/agent-harness.md.lock +++ b/docs/plans/agent-harness.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T05:00:36.569Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T05:05:25.017Z"} \ No newline at end of file diff --git a/packages/agent-harness/src/index.ts b/packages/agent-harness/src/index.ts index dd6fb125d8..a6101e2309 100644 --- a/packages/agent-harness/src/index.ts +++ b/packages/agent-harness/src/index.ts @@ -1,5 +1,6 @@ export { makeSchemaModule } from "./modules/schema.js"; export { discoverHarnesses } from "./discovery/discover.js"; export { extractSchema } from "./loader/extract-schema.js"; +export { FrontmatterValidationError, validateFrontmatter } from "./loader/validate.js"; export { InvalidPairExtensionError, MissingPairError, resolvePair } from "./loader/pair.js"; export type { HarnessFs, HarnessPair } from "./loader/pair.js"; diff --git a/packages/agent-harness/src/loader/validate.test.ts b/packages/agent-harness/src/loader/validate.test.ts new file mode 100644 index 0000000000..4afddf9ae7 --- /dev/null +++ b/packages/agent-harness/src/loader/validate.test.ts @@ -0,0 +1,143 @@ +import { describe, expect, expectTypeOf, it } from "vitest"; +import { S } from "toolcraft-schema"; + +import * as api from "../index.js"; +import { FrontmatterValidationError, validateFrontmatter } from "./validate.js"; + +describe("validateFrontmatter", () => { + it("is re-exported from the package entrypoint", () => { + expect(api.validateFrontmatter).toBe(validateFrontmatter); + expect(api.FrontmatterValidationError).toBe(FrontmatterValidationError); + }); + + it("returns validated frontmatter with defaults applied", () => { + const schema = S.Object({ + title: S.String(), + retries: S.Optional(S.Number({ default: 2 })) + }); + + const result = validateFrontmatter(schema, { title: "Build" }, "docs/plans/build.md"); + + expect(result).toEqual({ + title: "Build", + retries: 2 + }); + expectTypeOf(result).toEqualTypeOf<{ + title: string; + retries?: number; + }>(); + }); + + it("throws a formatted error for a single issue", () => { + const schema = S.Object({ + title: S.String() + }); + + expect(() => + validateFrontmatter(schema, { title: 123 }, "docs/plans/build.md") + ).toThrow( + new FrontmatterValidationError( + "docs/plans/build.md: title: Expected string at title", + [ + { + path: ["title"], + expected: "string", + received: "integer", + message: "Expected string at title" + } + ] + ) + ); + }); + + it("throws a formatted error with one line per issue", () => { + const schema = S.Object({ + title: S.String(), + retries: S.Number({ minimum: 1 }) + }); + + expect(() => + validateFrontmatter( + schema, + { + title: 123, + retries: 0 + }, + "docs/plans/build.md" + ) + ).toThrow( + [ + "docs/plans/build.md: title: Expected string at title", + "docs/plans/build.md: retries: Expected number greater than or equal to 1 at retries" + ].join("\n") + ); + }); + + it("formats nested and array issue paths as dotted paths", () => { + const schema = S.Object({ + jobs: S.Array( + S.Object({ + title: S.String() + }) + ) + }); + + expect(() => + validateFrontmatter(schema, { jobs: [{ title: "Build" }, { title: 123 }] }, "jobs.md") + ).toThrow("jobs.md: jobs.1.title: Expected string at jobs.1.title"); + }); + + it("formats an empty issue path as frontmatter", () => { + const schema = S.Object({ + title: S.String() + }); + + expect(() => + validateFrontmatter(schema, [] as unknown as Record, "jobs.md") + ).toThrow("jobs.md: frontmatter: Expected object at value"); + }); + + it("exposes the original issues on the error", () => { + const schema = S.Object({ + title: S.String(), + retries: S.Number({ minimum: 1 }) + }); + + try { + validateFrontmatter(schema, { title: 123, retries: 0 }, "docs/plans/build.md"); + } catch (error) { + expect(error).toBeInstanceOf(FrontmatterValidationError); + expect((error as FrontmatterValidationError).issues).toEqual([ + { + path: ["title"], + expected: "string", + received: "integer", + message: "Expected string at title" + }, + { + path: ["retries"], + expected: "number greater than or equal to 1", + received: "0", + message: "Expected number greater than or equal to 1 at retries" + } + ]); + return; + } + + throw new Error("Expected validateFrontmatter to throw."); + }); + + it("rejects empty frontmatter when required fields are missing", () => { + const schema = S.Object({ + title: S.String(), + owner: S.String() + }); + + expect(() => validateFrontmatter(schema, {}, "docs/plans/build.md")).toThrow( + [ + "docs/plans/build.md: title: Expected string at title", + "docs/plans/build.md: owner: Expected string at owner" + ].join("\n") + ); + }); +}); diff --git a/packages/agent-harness/src/loader/validate.ts b/packages/agent-harness/src/loader/validate.ts new file mode 100644 index 0000000000..efe37b7516 --- /dev/null +++ b/packages/agent-harness/src/loader/validate.ts @@ -0,0 +1,34 @@ +import { validate } from "toolcraft-schema"; +import type { AnySchema as SchemaDescriptor, Static, ValidationIssue } from "toolcraft-schema"; + +export class FrontmatterValidationError extends Error { + readonly issues: readonly ValidationIssue[]; + + constructor(message: string, issues: readonly ValidationIssue[]) { + super(message); + this.name = "FrontmatterValidationError"; + this.issues = issues; + } +} + +export function validateFrontmatter( + schema: S, + frontmatter: Record, + mdPath: string +): Static { + const result = validate(schema, frontmatter); + + if (result.ok) { + return result.value; + } + + throw new FrontmatterValidationError(formatIssues(mdPath, result.issues), result.issues); +} + +function formatIssues(mdPath: string, issues: readonly ValidationIssue[]): string { + return issues.map((issue) => `${mdPath}: ${formatPath(issue.path)}: ${issue.message}`).join("\n"); +} + +function formatPath(path: readonly string[]): string { + return path.join(".") || "frontmatter"; +} From 4eeb767b1ead26501f556489fa8e81a28f4c7fcd Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 00:16:04 -0500 Subject: [PATCH 055/111] feat(agent-harness): run harness pairs --- docs/plans/agent-harness.md | 8 +- docs/plans/agent-harness.md.lock | 2 +- packages/agent-harness/src/index.ts | 2 + packages/agent-harness/src/loader/run.test.ts | 338 +++++++++++++++ packages/agent-harness/src/loader/run.ts | 407 ++++++++++++++++++ 5 files changed, 752 insertions(+), 5 deletions(-) create mode 100644 packages/agent-harness/src/loader/run.test.ts create mode 100644 packages/agent-harness/src/loader/run.ts diff --git a/docs/plans/agent-harness.md b/docs/plans/agent-harness.md index f5dbbcb7fe..ff78bd5f45 100644 --- a/docs/plans/agent-harness.md +++ b/docs/plans/agent-harness.md @@ -470,7 +470,7 @@ tasks: status: implement: done test: done - commit: open + commit: done - id: agent-harness-run title: Implement runHarnessPair end-to-end @@ -549,9 +549,9 @@ tasks: - concurrent run: second invocation against same .md while the first holds the lock errors with EEXIST. status: - implement: open - test: open - commit: open + implement: done + test: done + commit: done - id: agent-harness-templates title: Ship four demo template pairs diff --git a/docs/plans/agent-harness.md.lock b/docs/plans/agent-harness.md.lock index 903cc01160..49a29dd296 100644 --- a/docs/plans/agent-harness.md.lock +++ b/docs/plans/agent-harness.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T05:05:25.017Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T05:14:54.735Z"} \ No newline at end of file diff --git a/packages/agent-harness/src/index.ts b/packages/agent-harness/src/index.ts index a6101e2309..65285d0ed9 100644 --- a/packages/agent-harness/src/index.ts +++ b/packages/agent-harness/src/index.ts @@ -1,6 +1,8 @@ export { makeSchemaModule } from "./modules/schema.js"; export { discoverHarnesses } from "./discovery/discover.js"; export { extractSchema } from "./loader/extract-schema.js"; +export { runHarnessPair } from "./loader/run.js"; export { FrontmatterValidationError, validateFrontmatter } from "./loader/validate.js"; export { InvalidPairExtensionError, MissingPairError, resolvePair } from "./loader/pair.js"; +export type { HarnessImportMeta, RunHarnessPairOptions } from "./loader/run.js"; export type { HarnessFs, HarnessPair } from "./loader/pair.js"; diff --git a/packages/agent-harness/src/loader/run.test.ts b/packages/agent-harness/src/loader/run.test.ts new file mode 100644 index 0000000000..4ad00106bf --- /dev/null +++ b/packages/agent-harness/src/loader/run.test.ts @@ -0,0 +1,338 @@ +import { dirname } from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { vol } from "memfs"; + +vi.mock("node:fs/promises", async () => { + const { fs } = await import("memfs"); + return { + ...fs.promises, + default: fs.promises + }; +}); + +const { runHarnessPair } = await import("./run.js"); +const api = await import("../index.js"); + +describe("runHarnessPair", () => { + beforeEach(() => { + vol.reset(); + }); + + afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); + }); + + it("is re-exported from the package entrypoint", () => { + expect(api.runHarnessPair).toBe(runHarnessPair); + }); + + it("validates frontmatter, invokes the default export with the validated value, and returns its result", async () => { + const mdPath = "/repo/harness/review.md"; + vol.fromJSON({ + [mdPath]: ["---", "kind: review", "version: 1", "title: Build", "---", "", "# Review"].join("\n"), + "/repo/harness/review.ajs": [ + 'import { check } from "test";', + 'import { S } from "schema";', + "export const schema = S.Object({", + " kind: S.String(),", + " version: S.Number(),", + " title: S.String(),", + " retries: S.Optional(S.Number({ default: 2 }))", + "});", + "export default async (frontmatter) => check(frontmatter, import.meta);" + ].join("\n") + }); + + const check = vi.fn((frontmatter, meta) => ({ + body: meta.body, + dirname: meta.dirname, + filename: meta.filename, + frontmatter, + kind: meta.kind, + version: meta.version + })); + const modulesFor = vi.fn(() => ({ + test: { + check + } + })); + + const result = await runHarnessPair(mdPath, { modulesFor }); + + expect(modulesFor).toHaveBeenCalledWith( + { + kind: "review", + retries: 2, + title: "Build", + version: 1 + }, + { + body: "\n# Review", + dirname: dirname(mdPath), + filename: mdPath, + kind: "review", + version: 1 + } + ); + expect(result).toMatchObject({ + ok: true, + returnValue: { + body: "\n# Review", + dirname: dirname(mdPath), + filename: mdPath, + frontmatter: { + kind: "review", + retries: 2, + title: "Build", + version: 1 + }, + kind: "review", + version: 1 + } + }); + }); + + it("passes raw frontmatter through when the script does not export a schema", async () => { + const mdPath = "/repo/harness/raw.md"; + vol.fromJSON({ + [mdPath]: ["---", "kind: raw", "version: 1", "title: 123", "---", "", "# Raw"].join("\n"), + "/repo/harness/raw.ajs": "export default (frontmatter) => frontmatter;" + }); + + await expect(runHarnessPair(mdPath, { modulesFor: () => ({}) })).resolves.toMatchObject({ + ok: true, + returnValue: { + kind: "raw", + title: 123, + version: 1 + } + }); + }); + + it("throws validation errors with the md path and field path, releases the lock, and leaves snapshots untouched", async () => { + const mdPath = "/repo/harness/invalid.md"; + const snapshotPath = "/snapshots/invalid.json"; + vol.fromJSON({ + [mdPath]: ["---", "kind: review", "version: 1", "title: 123", "---", "", "# Invalid"].join("\n"), + "/repo/harness/invalid.ajs": [ + 'import { S } from "schema";', + "export const schema = S.Object({ title: S.String() });", + "export default (frontmatter) => frontmatter;" + ].join("\n") + }); + + await expect( + runHarnessPair(mdPath, { + modulesFor: () => ({}), + snapshotPath + }) + ).rejects.toThrow(`${mdPath}: title: Expected string at title`); + + expect(vol.existsSync(`${mdPath}.lock`)).toBe(false); + expect(vol.existsSync(snapshotPath)).toBe(false); + }); + + it("throws a lint error when the .ajs is missing a default export", async () => { + const mdPath = "/repo/harness/no-default.md"; + vol.fromJSON({ + [mdPath]: "---\nkind: review\nversion: 1\n---\n", + "/repo/harness/no-default.ajs": [ + 'import { S } from "schema";', + "export const schema = S.Object({ kind: S.String(), version: S.Number() });" + ].join("\n") + }); + + await expect(runHarnessPair(mdPath, { modulesFor: () => ({}) })).rejects.toMatchObject({ + name: "LintError", + diagnostics: [expect.objectContaining({ code: "AS-EXPORT-DEFAULT-MISSING" })] + }); + }); + + it("allows a top-level return warning in .ajs and still succeeds", async () => { + const mdPath = "/repo/harness/top-return.md"; + vol.fromJSON({ + [mdPath]: "---\nkind: review\nversion: 1\n---\n", + "/repo/harness/top-return.ajs": "export default () => 'ok';\nreturn 'ignored';" + }); + + await expect(runHarnessPair(mdPath, { modulesFor: () => ({}) })).resolves.toMatchObject({ + ok: true, + returnValue: "ok" + }); + }); + + it("resumes from an existing snapshotPath at the next host call", async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date("2026-05-04T00:00:00.000Z")); + + const mdPath = "/repo/harness/resume.md"; + const snapshotPath = "/snapshots/resume.json"; + vol.fromJSON({ + [mdPath]: "---\nkind: resume\nversion: 1\n---\n", + "/repo/harness/resume.ajs": [ + 'import { step } from "host";', + "export default async () => {", + " const first = await step('first');", + " const second = await step('second');", + " return first.concat('|').concat(second);", + "};" + ].join("\n") + }); + + const first = createDeferred(); + const second = createDeferred(); + const firstController = new AbortController(); + const firstCalls: string[] = []; + const firstRun = runHarnessPair(mdPath, { + modulesFor: () => ({ + host: { + async step(name: string) { + firstCalls.push(name); + return name === "first" ? first.promise : second.promise; + } + } + }), + signal: firstController.signal, + snapshotPath + }); + + await vi.advanceTimersByTimeAsync(0); + expect(firstCalls).toEqual(["first"]); + + await vi.advanceTimersByTimeAsync(30_000); + first.resolve("alpha"); + await flushMicrotasks(); + await vi.advanceTimersByTimeAsync(0); + + expect(firstCalls).toEqual(["first", "second"]); + expect(vol.existsSync(snapshotPath)).toBe(true); + + firstController.abort(); + second.reject(new Error("aborted")); + await expect(firstRun).rejects.toMatchObject({ + name: "SandboxError" + }); + + const secondCalls: string[] = []; + const resumed = await runHarnessPair(mdPath, { + modulesFor: () => ({ + host: { + async step(name: string) { + secondCalls.push(name); + return "beta"; + } + } + }), + snapshotPath + }); + + expect(secondCalls).toEqual(["second"]); + expect(resumed).toMatchObject({ + ok: true, + returnValue: "alpha|beta" + }); + }); + + it("does not replay stale host calls after a successful run with the same snapshotPath", async () => { + const mdPath = "/repo/harness/fresh.md"; + const snapshotPath = "/snapshots/fresh.json"; + vol.fromJSON({ + [mdPath]: "---\nkind: fresh\nversion: 1\n---\n", + "/repo/harness/fresh.ajs": [ + 'import { read } from "host";', + "export default async () => read();" + ].join("\n") + }); + + const firstRead = vi.fn(() => "first"); + await expect( + runHarnessPair(mdPath, { + modulesFor: () => ({ + host: { + read: firstRead + } + }), + snapshotPath + }) + ).resolves.toMatchObject({ + ok: true, + returnValue: "first" + }); + expect(firstRead).toHaveBeenCalledTimes(1); + + const secondRead = vi.fn(() => "second"); + await expect( + runHarnessPair(mdPath, { + modulesFor: () => ({ + host: { + read: secondRead + } + }), + snapshotPath + }) + ).resolves.toMatchObject({ + ok: true, + returnValue: "second" + }); + expect(secondRead).toHaveBeenCalledTimes(1); + }); + + it("rejects a concurrent run against the same .md while the first run holds the lock", async () => { + const mdPath = "/repo/harness/concurrent.md"; + vol.fromJSON({ + [mdPath]: "---\nkind: concurrent\nversion: 1\n---\n", + "/repo/harness/concurrent.ajs": [ + 'import { wait } from "host";', + "export default async () => {", + " await wait();", + " return 'done';", + "};" + ].join("\n") + }); + + const releaseFirst = createDeferred(); + const firstRun = runHarnessPair(mdPath, { + modulesFor: () => ({ + host: { + async wait() { + return releaseFirst.promise; + } + } + }) + }); + await flushMicrotasks(); + await flushMicrotasks(); + + await expect(runHarnessPair(mdPath, { modulesFor: () => ({}) })).rejects.toMatchObject({ + code: "EEXIST" + }); + + releaseFirst.resolve(); + await expect(firstRun).resolves.toMatchObject({ + ok: true, + returnValue: "done" + }); + }); +}); + +function createDeferred() { + let resolve!: (value: TValue) => void; + let reject!: (reason?: unknown) => void; + const promise = new Promise((innerResolve, innerReject) => { + resolve = innerResolve; + reject = innerReject; + }); + + return { + promise, + reject, + resolve + }; +} + +async function flushMicrotasks(): Promise { + await Promise.resolve(); + await Promise.resolve(); + await Promise.resolve(); +} diff --git a/packages/agent-harness/src/loader/run.ts b/packages/agent-harness/src/loader/run.ts new file mode 100644 index 0000000000..6391c52fa2 --- /dev/null +++ b/packages/agent-harness/src/loader/run.ts @@ -0,0 +1,407 @@ +import { mkdir, readFile, unlink, writeFile } from "node:fs/promises"; +import os from "node:os"; +import { dirname, join } from "node:path"; + +import { lockWorkflow, resolveRunLogDir } from "@poe-code/agent-harness-tools"; +import { + lint, + parseModule, + run, + splitFrontmatter, + type Diagnostic +} from "@poe-code/agent-script"; + +import { makeSchemaModule } from "../modules/schema.js"; +import { extractSchema } from "./extract-schema.js"; +import { resolvePair } from "./pair.js"; +import { validateFrontmatter } from "./validate.js"; + +type RunOptions = NonNullable[1]>; +type LintOptions = NonNullable[1]>; +export type RunResult = Awaited>; +export type ModuleExports = ReadonlyMap | Record; +export type ModuleRegistry = ReadonlyMap | Record; + +export type HarnessImportMeta = { + kind: string | undefined; + version: number | undefined; + filename: string; + dirname: string; + body: string; +}; + +export type RunHarnessPairOptions = { + modulesFor: ( + frontmatter: Record, + meta: HarnessImportMeta + ) => ModuleRegistry; + signal?: AbortSignal; + snapshotPath?: string; +}; + +export class LintError extends Error { + readonly diagnostics: readonly Diagnostic[]; + + constructor(diagnostics: readonly Diagnostic[]) { + super(formatLintErrorMessage(diagnostics)); + this.name = "LintError"; + this.diagnostics = diagnostics; + } +} + +export async function runHarnessPair( + mdPath: string, + options: RunHarnessPairOptions +): Promise { + const pair = await resolvePair(mdPath); + const releaseLock = await acquireHarnessLock(pair.mdPath); + + try { + const [ajsSource, mdSource] = await Promise.all([ + readTextFile(pair.ajsPath), + readTextFile(pair.mdPath) + ]); + const { frontmatter, body } = splitFrontmatter(mdSource); + const schema = await extractSchema(ajsSource, pair.ajsPath); + const validated = ( + schema === undefined ? frontmatter : validateFrontmatter(schema, frontmatter, pair.mdPath) + ) as Record; + const meta: HarnessImportMeta = { + kind: readString(validated.kind), + version: readNumber(validated.version), + filename: pair.mdPath, + dirname: dirname(pair.mdPath), + body + }; + const snapshotPath = resolveSnapshotPath(pair.mdPath, options.snapshotPath); + const hostCallReplay = await createHostCallReplay(snapshotPath); + const modules = withSchemaModule(hostCallReplay.wrapModules(options.modulesFor(validated, meta))); + + throwOnLintErrors([ + ...lint(ajsSource, { + allowedExportNames: ["schema"], + filename: pair.ajsPath, + modules: createLintModules(modules) + }), + ...missingDefaultExportDiagnostics(ajsSource, pair.ajsPath) + ]); + + const snapshot = await readSnapshot(snapshotPath); + + let result: RunResult; + try { + result = await run(ajsSource, { + importMeta: meta, + entryPointArgs: [validated], + filename: pair.ajsPath, + modules: modules as RunOptions["modules"], + signal: options.signal, + snapshot, + snapshotPath + }); + } catch (error) { + await hostCallReplay.flush().catch(() => undefined); + throw error; + } + + await hostCallReplay.flush(); + if (result.ok) { + await cleanupCompletedSnapshot(snapshotPath); + } + + return result; + } finally { + await releaseLock(); + } +} + +async function acquireHarnessLock(mdPath: string): Promise<() => Promise> { + try { + return await lockWorkflow(mdPath, { + retries: 0 + }); + } catch (error) { + if (error instanceof Error && error.name === "LockTimeoutError") { + Object.assign(error, { code: "EEXIST" }); + } + + throw error; + } +} + +function throwOnLintErrors(diagnostics: readonly Diagnostic[]): void { + const errors = diagnostics.filter((diagnostic) => diagnostic.severity === "error"); + if (errors.length > 0) { + throw new LintError(errors); + } +} + +function missingDefaultExportDiagnostics(source: string, filename: string): Diagnostic[] { + const module = parseModule(source, filename); + const hasDefaultExport = module.body.some((statement) => statement.type === "ExportDefaultDeclaration"); + if (hasDefaultExport) { + return []; + } + + return [ + { + code: "AS-EXPORT-DEFAULT-MISSING", + severity: "error", + message: "Module must export a default entry point.", + filename, + line: module.span.start.line, + column: module.span.start.column, + span: module.span + } + ]; +} + +function withSchemaModule(modules: ModuleRegistry): ModuleRegistry { + if (modules instanceof Map) { + const merged = new Map(modules); + merged.set("schema", makeSchemaModule() as ModuleExports); + return merged as ModuleRegistry; + } + + return { + ...modules, + schema: makeSchemaModule() + } as ModuleRegistry; +} + +type HostCallRecord = { + key: string; + args: readonly unknown[]; + result: unknown; +}; + +type HostCallReplay = { + flush(): Promise; + wrapModules(modules: ModuleRegistry): ModuleRegistry; +}; + +async function createHostCallReplay(snapshotPath: string): Promise { + const storePath = hostCallStorePath(snapshotPath); + const records = await readHostCallRecords(storePath); + const pendingWrites = new Set>(); + let cursor = 0; + + return { + async flush() { + while (pendingWrites.size > 0) { + await Promise.all([...pendingWrites]); + } + }, + wrapModules(modules) { + if (modules instanceof Map) { + return new Map( + [...modules.entries()].map(([moduleName, moduleExports]) => [ + moduleName, + wrapModuleExports(moduleName, moduleExports) + ]) + ) as ModuleRegistry; + } + + return Object.fromEntries( + Object.entries(modules).map(([moduleName, moduleExports]) => [ + moduleName, + wrapModuleExports(moduleName, moduleExports) + ]) + ) as ModuleRegistry; + } + }; + + function wrapModuleExports(moduleName: string, moduleExports: ModuleExports): ModuleExports { + if (moduleExports instanceof Map) { + return new Map( + [...moduleExports.entries()].map(([exportName, value]) => [ + exportName, + wrapHostBinding(`${moduleName}.${exportName}`, value) + ]) + ) as ModuleExports; + } + + return Object.fromEntries( + Object.entries(moduleExports).map(([exportName, value]) => [ + exportName, + wrapHostBinding(`${moduleName}.${exportName}`, value) + ]) + ) as ModuleExports; + } + + function wrapHostBinding(key: string, value: unknown): unknown { + if (typeof value !== "function") { + return value; + } + + return (...args: readonly unknown[]) => { + const replay = records[cursor]; + if (replay !== undefined && replay.key === key && sameJsonValue(replay.args, args)) { + cursor += 1; + return replay.result; + } + + const result = Reflect.apply(value, undefined, args) as unknown; + if (isPromiseLike(result)) { + return Promise.resolve(result).then(async (resolved) => { + await recordHostCall(key, args, resolved); + return resolved; + }); + } + + void recordHostCall(key, args, result); + return result; + }; + } + + async function recordHostCall( + key: string, + args: readonly unknown[], + result: unknown + ): Promise { + records.push({ + key, + args, + result + }); + cursor = records.length; + const write = writeHostCallRecords(storePath, records); + pendingWrites.add(write); + try { + await write; + } finally { + pendingWrites.delete(write); + } + } +} + +async function readHostCallRecords(storePath: string): Promise { + try { + const parsed = JSON.parse(await readFile(storePath, "utf8")) as unknown; + return Array.isArray(parsed) ? (parsed as HostCallRecord[]) : []; + } catch (error) { + if (hasErrorCode(error, "ENOENT")) { + return []; + } + + throw error; + } +} + +async function writeHostCallRecords( + storePath: string, + records: readonly HostCallRecord[] +): Promise { + let serialized: string; + try { + serialized = JSON.stringify(records, null, 2); + } catch { + return; + } + + await mkdir(dirname(storePath), { recursive: true }); + await writeFile(storePath, serialized); +} + +async function cleanupCompletedSnapshot(snapshotPath: string): Promise { + await Promise.all([ + unlinkIfExists(snapshotPath), + unlinkIfExists(hostCallStorePath(snapshotPath)) + ]); +} + +async function unlinkIfExists(path: string): Promise { + try { + await unlink(path); + } catch (error) { + if (!hasErrorCode(error, "ENOENT")) { + throw error; + } + } +} + +function hostCallStorePath(snapshotPath: string): string { + return `${snapshotPath}.host-calls.json`; +} + +function sameJsonValue(left: unknown, right: unknown): boolean { + try { + return JSON.stringify(left) === JSON.stringify(right); + } catch { + return false; + } +} + +function isPromiseLike(value: unknown): value is PromiseLike { + return typeof value === "object" && value !== null && "then" in value; +} + +function createLintModules(modules: ModuleRegistry): NonNullable { + const entries = modules instanceof Map ? [...modules.entries()] : Object.entries(modules); + + return new Map( + entries.map(([moduleName, moduleExports]) => [moduleName, listModuleExports(moduleExports)] as const) + ); +} + +function listModuleExports(moduleExports: ModuleExports): string[] { + const exportNames = moduleExports instanceof Map ? [...moduleExports.keys()] : Object.keys(moduleExports); + return exportNames.filter((exportName) => exportName.length > 0).sort((left, right) => left.localeCompare(right)); +} + +function resolveSnapshotPath(mdPath: string, snapshotPath: string | undefined): string { + return ( + snapshotPath ?? + join( + resolveRunLogDir({ + planPath: mdPath, + runner: "harness", + homeDir: os.homedir() + }), + "snapshot.json" + ) + ); +} + +async function readSnapshot(snapshotPath: string): Promise { + try { + return JSON.parse(await readFile(snapshotPath, "utf8")) as RunOptions["snapshot"]; + } catch (error) { + if (hasErrorCode(error, "ENOENT")) { + return undefined; + } + + throw error; + } +} + +async function readTextFile(path: string): Promise { + const source = await readFile(path, "utf8"); + return source.startsWith("\uFEFF") ? source.slice(1) : source; +} + +function formatLintErrorMessage(diagnostics: readonly Diagnostic[]): string { + return diagnostics + .map( + (diagnostic) => + `${diagnostic.filename}:${diagnostic.line}:${diagnostic.column} ${diagnostic.code}: ${diagnostic.message}` + ) + .join("\n"); +} + +function readString(value: unknown): string | undefined { + return typeof value === "string" ? value : undefined; +} + +function readNumber(value: unknown): number | undefined { + return typeof value === "number" ? value : undefined; +} + +function hasErrorCode(error: unknown, code: string): boolean { + return ( + typeof error === "object" && + error !== null && + "code" in error && + (error as { code?: unknown }).code === code + ); +} From 8c08da460733bddb7cdb1ff76de77b50c8f4eee1 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 00:24:25 -0500 Subject: [PATCH 056/111] feat(agent-harness): add builtin demo templates --- docs/plans/agent-harness.md | 4 +- docs/plans/agent-harness.md.lock | 2 +- packages/agent-harness/package.json | 2 +- .../agent-harness/scripts/copy-templates.mjs | 33 ++++ packages/agent-harness/src/index.ts | 1 + .../experiment-demo/experiment-demo.ajs | 56 +++++++ .../experiment-demo/experiment-demo.md | 24 +++ .../agent-harness/src/templates/index.test.ts | 141 ++++++++++++++++++ packages/agent-harness/src/templates/index.ts | 24 +++ .../templates/pipeline-demo/pipeline-demo.ajs | 56 +++++++ .../templates/pipeline-demo/pipeline-demo.md | 28 ++++ .../src/templates/ralph-demo/ralph-demo.ajs | 47 ++++++ .../src/templates/ralph-demo/ralph-demo.md | 21 +++ .../superintendent-demo.ajs | 74 +++++++++ .../superintendent-demo.md | 42 ++++++ .../src/lint/rules/AS006-007.test.ts | 11 ++ .../agent-script/src/lint/rules/AS006-007.ts | 17 +++ 17 files changed, 579 insertions(+), 4 deletions(-) create mode 100644 packages/agent-harness/scripts/copy-templates.mjs create mode 100644 packages/agent-harness/src/templates/experiment-demo/experiment-demo.ajs create mode 100644 packages/agent-harness/src/templates/experiment-demo/experiment-demo.md create mode 100644 packages/agent-harness/src/templates/index.test.ts create mode 100644 packages/agent-harness/src/templates/index.ts create mode 100644 packages/agent-harness/src/templates/pipeline-demo/pipeline-demo.ajs create mode 100644 packages/agent-harness/src/templates/pipeline-demo/pipeline-demo.md create mode 100644 packages/agent-harness/src/templates/ralph-demo/ralph-demo.ajs create mode 100644 packages/agent-harness/src/templates/ralph-demo/ralph-demo.md create mode 100644 packages/agent-harness/src/templates/superintendent-demo/superintendent-demo.ajs create mode 100644 packages/agent-harness/src/templates/superintendent-demo/superintendent-demo.md diff --git a/docs/plans/agent-harness.md b/docs/plans/agent-harness.md index ff78bd5f45..850935234a 100644 --- a/docs/plans/agent-harness.md +++ b/docs/plans/agent-harness.md @@ -599,8 +599,8 @@ tasks: - packages/agent-harness/src/index.ts — re-export `listBuiltinTemplates`. status: - implement: open - test: open + implement: done + test: done commit: open - id: agent-harness-codegen diff --git a/docs/plans/agent-harness.md.lock b/docs/plans/agent-harness.md.lock index 49a29dd296..1e7c132e1e 100644 --- a/docs/plans/agent-harness.md.lock +++ b/docs/plans/agent-harness.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T05:14:54.735Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T05:23:19.624Z"} \ No newline at end of file diff --git a/packages/agent-harness/package.json b/packages/agent-harness/package.json index a3a41675ff..aea80566bc 100644 --- a/packages/agent-harness/package.json +++ b/packages/agent-harness/package.json @@ -12,7 +12,7 @@ } }, "scripts": { - "build": "tsc", + "build": "tsc && node scripts/copy-templates.mjs", "test": "cd ../.. && vitest run packages/agent-harness/src", "test:unit": "cd ../.. && vitest run packages/agent-harness/src" }, diff --git a/packages/agent-harness/scripts/copy-templates.mjs b/packages/agent-harness/scripts/copy-templates.mjs new file mode 100644 index 0000000000..2c81dd04d0 --- /dev/null +++ b/packages/agent-harness/scripts/copy-templates.mjs @@ -0,0 +1,33 @@ +import { cpSync, mkdirSync, readdirSync } from "node:fs"; +import path from "node:path"; + +const sourceDir = "src/templates"; +const outputDir = "dist/templates"; + +mkdirSync(outputDir, { recursive: true }); + +for (const entry of readdirSync(sourceDir, { withFileTypes: true })) { + if (!entry.isDirectory()) { + continue; + } + + const sourceTemplateDir = path.join(sourceDir, entry.name); + const outputTemplateDir = path.join(outputDir, entry.name); + mkdirSync(outputTemplateDir, { recursive: true }); + + for (const templateFile of readdirSync(sourceTemplateDir, { withFileTypes: true })) { + if (!templateFile.isFile()) { + continue; + } + + const extension = path.extname(templateFile.name); + if (extension !== ".ajs" && extension !== ".md") { + continue; + } + + cpSync( + path.join(sourceTemplateDir, templateFile.name), + path.join(outputTemplateDir, templateFile.name) + ); + } +} diff --git a/packages/agent-harness/src/index.ts b/packages/agent-harness/src/index.ts index 65285d0ed9..7c1be87453 100644 --- a/packages/agent-harness/src/index.ts +++ b/packages/agent-harness/src/index.ts @@ -2,6 +2,7 @@ export { makeSchemaModule } from "./modules/schema.js"; export { discoverHarnesses } from "./discovery/discover.js"; export { extractSchema } from "./loader/extract-schema.js"; export { runHarnessPair } from "./loader/run.js"; +export { listBuiltinTemplates } from "./templates/index.js"; export { FrontmatterValidationError, validateFrontmatter } from "./loader/validate.js"; export { InvalidPairExtensionError, MissingPairError, resolvePair } from "./loader/pair.js"; export type { HarnessImportMeta, RunHarnessPairOptions } from "./loader/run.js"; diff --git a/packages/agent-harness/src/templates/experiment-demo/experiment-demo.ajs b/packages/agent-harness/src/templates/experiment-demo/experiment-demo.ajs new file mode 100644 index 0000000000..a6628c140d --- /dev/null +++ b/packages/agent-harness/src/templates/experiment-demo/experiment-demo.ajs @@ -0,0 +1,56 @@ +import { S } from "schema"; +import { spawn } from "agent"; +import { event } from "log"; + +export const schema = S.Object({ + "$schema": S.Enum(["https://poe-platform.github.io/poe-code/schemas/harnesses/experiment-demo.schema.json"]), + kind: S.Enum(["experiment-demo"]), + version: S.Number(), + agents: S.Object({ + experimenter: S.Object({ + agent: S.String(), + mode: S.Optional(S.Enum(["read", "edit", "yolo"])), + prompt: S.Optional(S.String()) + }) + }), + metric: S.Object({ + name: S.String(), + direction: S.Enum(["maximize", "minimize"]) + }), + attempts: S.Array( + S.Object({ + id: S.String(), + prompt: S.String() + }), + { minItems: 1 } + ) +}); + +export default async (frontmatter) => { + const meta = import.meta; + const attempts = await frontmatter.attempts.reduce(async (previousAttempts, attempt) => { + const attemptsSoFar = await previousAttempts; + const result = await spawn(frontmatter.agents.experimenter, { + prompt: attempt.prompt.concat("\n\nMetric: ", frontmatter.metric.name, "\n\n", meta.body) + }); + event("attempt.kept", { + attempt: attempt.id, + direction: frontmatter.metric.direction, + summary: result.summary + }); + return attemptsSoFar.concat({ + event: "kept", + attempt: attempt.id, + summary: result.summary + }); + }, Promise.resolve([])); + + return { + kind: meta.kind, + filename: meta.filename, + dirname: meta.dirname, + metric: frontmatter.metric.name, + kept: attempts.length, + attempts + }; +}; diff --git a/packages/agent-harness/src/templates/experiment-demo/experiment-demo.md b/packages/agent-harness/src/templates/experiment-demo/experiment-demo.md new file mode 100644 index 0000000000..7af5d40555 --- /dev/null +++ b/packages/agent-harness/src/templates/experiment-demo/experiment-demo.md @@ -0,0 +1,24 @@ +--- +$schema: https://poe-platform.github.io/poe-code/schemas/harnesses/experiment-demo.schema.json +kind: experiment-demo +version: 1 +agents: + experimenter: + agent: claude-code + mode: edit + prompt: | + Make one focused attempt to improve the target metric. +metric: + name: tests + direction: maximize +attempts: + - id: baseline + prompt: Make a conservative improvement attempt. + - id: follow-up + prompt: Try one follow-up based on the previous attempt shape. +--- + +# Experiment Demo + +Try a small improvement, keep it when it moves the target metric in the right +direction, then carry the useful context into the next attempt. diff --git a/packages/agent-harness/src/templates/index.test.ts b/packages/agent-harness/src/templates/index.test.ts new file mode 100644 index 0000000000..dc7ef26c83 --- /dev/null +++ b/packages/agent-harness/src/templates/index.test.ts @@ -0,0 +1,141 @@ +import { readFile } from "node:fs/promises"; +import { dirname } from "node:path"; + +import { lint, run, splitFrontmatter } from "@poe-code/agent-script"; +import { describe, expect, it, vi } from "vitest"; + +import * as api from "../index.js"; +import { extractSchema } from "../loader/extract-schema.js"; +import { validateFrontmatter } from "../loader/validate.js"; +import { makeSchemaModule } from "../modules/schema.js"; +import { listBuiltinTemplates } from "./index.js"; + +const lintModules = { + agent: ["spawn"], + log: ["event"], + schema: ["S"] +}; + +describe("builtin harness templates", () => { + it("is re-exported from the package entrypoint", () => { + expect(api.listBuiltinTemplates).toBe(listBuiltinTemplates); + }); + + it("lists the four demo template pairs", () => { + expect(listBuiltinTemplates().map((template) => template.kind)).toEqual([ + "ralph-demo", + "experiment-demo", + "pipeline-demo", + "superintendent-demo" + ]); + }); + + it.each(listBuiltinTemplates())( + "$kind lints, validates its default frontmatter, and runs with a stub agent", + async (template) => { + const [ajsSource, mdSource] = await Promise.all([ + readFile(template.ajsPath, "utf8"), + readFile(template.mdPath, "utf8") + ]); + const { frontmatter, body } = splitFrontmatter(mdSource); + + expect( + lint(ajsSource, { + allowedExportNames: ["schema"], + filename: template.ajsPath, + modules: lintModules + }) + ).toEqual([]); + + const schema = await extractSchema(ajsSource, template.ajsPath); + expect(schema).toBeDefined(); + + const validated = validateFrontmatter(schema!, frontmatter, template.mdPath); + expect(validated).toMatchObject({ + kind: template.kind, + version: 1 + }); + + const flow: string[] = []; + const spawn = vi.fn(async () => ({ + durationMs: 1, + exitCode: 0, + stderr: "", + stdout: "", + summary: `stub summary ${spawn.mock.calls.length}` + })); + const event = vi.fn((name: string, payload: Record) => { + flow.push(`${name}:${String(payload.id ?? payload.attempt ?? payload.iteration ?? payload.round)}`); + }); + spawn.mockImplementation(async (_agent, options: { prompt: string }) => { + flow.push(`spawn:${options.prompt.split("\n", 1)[0]}`); + return { + durationMs: 1, + exitCode: 0, + stderr: "", + stdout: "", + summary: `stub summary ${spawn.mock.calls.length}` + }; + }); + const result = await run(ajsSource, { + entryPointArgs: [validated], + filename: template.ajsPath, + importMeta: { + body, + dirname: dirname(template.mdPath), + filename: template.mdPath, + kind: template.kind, + version: 1 + }, + modules: { + agent: { spawn }, + log: { event }, + schema: makeSchemaModule() + } + }); + + expect(result).toMatchObject({ + ok: true + }); + expect(spawn).toHaveBeenCalled(); + expect(result.ok ? result.returnValue : undefined).toMatchObject({ + kind: template.kind + }); + expect(flow).toEqual(expectedFlow[template.kind]); + } + ); +}); + +const expectedFlow: Record = { + "ralph-demo": [ + "spawn:Improve the current repository state while preserving tests.", + "iteration.completed:inspect", + "spawn:Improve the current repository state while preserving tests.", + "iteration.completed:improve" + ], + "experiment-demo": [ + "spawn:Make a conservative improvement attempt.", + "attempt.kept:baseline", + "spawn:Try one follow-up based on the previous attempt shape.", + "attempt.kept:follow-up" + ], + "pipeline-demo": [ + "task.started:inspect-worktree", + "spawn:inspect-worktree: Inspect worktree", + "spawn:Review inspect-worktree", + "task.completed:inspect-worktree", + "task.started:review-diff", + "spawn:review-diff: Review diff", + "spawn:Review review-diff", + "task.completed:review-diff" + ], + "superintendent-demo": [ + "spawn:Round 1: ", + "spawn:Inspect round 1", + "spawn:Inspect round 1", + "spawn:Inspect round 1", + "spawn:Judge round 1", + "spawn:stub summary 5", + "round.completed:1" + ] +}; diff --git a/packages/agent-harness/src/templates/index.ts b/packages/agent-harness/src/templates/index.ts new file mode 100644 index 0000000000..fa963b24d7 --- /dev/null +++ b/packages/agent-harness/src/templates/index.ts @@ -0,0 +1,24 @@ +import { fileURLToPath } from "node:url"; + +export type BuiltinTemplate = { + kind: string; + ajsPath: string; + mdPath: string; +}; + +export function listBuiltinTemplates(): readonly BuiltinTemplate[] { + return [ + template("ralph-demo"), + template("experiment-demo"), + template("pipeline-demo"), + template("superintendent-demo") + ]; +} + +function template(kind: string): BuiltinTemplate { + return { + kind, + ajsPath: fileURLToPath(new URL(`${kind}/${kind}.ajs`, import.meta.url)), + mdPath: fileURLToPath(new URL(`${kind}/${kind}.md`, import.meta.url)) + }; +} diff --git a/packages/agent-harness/src/templates/pipeline-demo/pipeline-demo.ajs b/packages/agent-harness/src/templates/pipeline-demo/pipeline-demo.ajs new file mode 100644 index 0000000000..ec0bb24884 --- /dev/null +++ b/packages/agent-harness/src/templates/pipeline-demo/pipeline-demo.ajs @@ -0,0 +1,56 @@ +import { S } from "schema"; +import { spawn } from "agent"; +import { event } from "log"; + +export const schema = S.Object({ + "$schema": S.Enum(["https://poe-platform.github.io/poe-code/schemas/harnesses/pipeline-demo.schema.json"]), + kind: S.Enum(["pipeline-demo"]), + version: S.Number(), + agents: S.Object({ + builder: S.Object({ + agent: S.String(), + mode: S.Optional(S.Enum(["read", "edit", "yolo"])), + prompt: S.Optional(S.String()) + }), + reviewer: S.Object({ + agent: S.String(), + mode: S.Optional(S.Enum(["read", "edit", "yolo"])), + prompt: S.Optional(S.String()) + }) + }), + tasks: S.Array( + S.Object({ + id: S.String(), + title: S.String(), + prompt: S.String() + }), + { minItems: 1 } + ) +}); + +export default async (frontmatter) => { + const meta = import.meta; + const taskIds = await frontmatter.tasks.reduce(async (previousTaskIds, task) => { + const taskIdsSoFar = await previousTaskIds; + event("task.started", { id: task.id, title: task.title }); + const build = await spawn(frontmatter.agents.builder, { + prompt: task.id.concat(": ", task.title, "\n\n", task.prompt, "\n\n", meta.body) + }); + const review = await spawn(frontmatter.agents.reviewer, { + prompt: "Review ".concat(task.id, "\n\n", build.summary) + }); + event("task.completed", { + id: task.id, + build: build.summary, + review: review.summary + }); + return taskIdsSoFar.concat(task.id); + }, Promise.resolve([])); + + return { + kind: meta.kind, + filename: meta.filename, + dirname: meta.dirname, + taskIds + }; +}; diff --git a/packages/agent-harness/src/templates/pipeline-demo/pipeline-demo.md b/packages/agent-harness/src/templates/pipeline-demo/pipeline-demo.md new file mode 100644 index 0000000000..88c5e4e776 --- /dev/null +++ b/packages/agent-harness/src/templates/pipeline-demo/pipeline-demo.md @@ -0,0 +1,28 @@ +--- +$schema: https://poe-platform.github.io/poe-code/schemas/harnesses/pipeline-demo.schema.json +kind: pipeline-demo +version: 1 +agents: + builder: + agent: claude-code + mode: edit + prompt: | + Implement the task with tests first. + reviewer: + agent: claude-code + mode: read + prompt: | + Review the diff for correctness and coverage. +tasks: + - id: inspect-worktree + title: Inspect worktree + prompt: Summarize the current repository state before making changes. + - id: review-diff + title: Review diff + prompt: Review the resulting diff and call out follow-up work. +--- + +# Pipeline Demo + +Run the tasks in order. For each task, let the builder produce the change or +analysis, then let the reviewer inspect the result. diff --git a/packages/agent-harness/src/templates/ralph-demo/ralph-demo.ajs b/packages/agent-harness/src/templates/ralph-demo/ralph-demo.ajs new file mode 100644 index 0000000000..8f14c7a42d --- /dev/null +++ b/packages/agent-harness/src/templates/ralph-demo/ralph-demo.ajs @@ -0,0 +1,47 @@ +import { S } from "schema"; +import { spawn } from "agent"; +import { event } from "log"; + +export const schema = S.Object({ + "$schema": S.Enum(["https://poe-platform.github.io/poe-code/schemas/harnesses/ralph-demo.schema.json"]), + kind: S.Enum(["ralph-demo"]), + version: S.Number(), + agent: S.Object({ + agent: S.String(), + mode: S.Optional(S.Enum(["read", "edit", "yolo"])), + prompt: S.Optional(S.String()) + }), + steps: S.Array( + S.Object({ + id: S.String(), + prompt: S.String() + }), + { minItems: 1 } + ), + goal: S.String() +}); + +export default async (frontmatter) => { + const meta = import.meta; + const summaries = await frontmatter.steps.reduce(async (previousSummaries, step) => { + const summariesSoFar = await previousSummaries; + const result = await spawn(frontmatter.agent, { + prompt: frontmatter.goal.concat("\n\n", step.prompt, "\n\n", meta.body) + }); + event("iteration.completed", { + kind: meta.kind, + file: meta.filename, + iteration: step.id, + summary: result.summary + }); + return summariesSoFar.concat(result.summary); + }, Promise.resolve([])); + + return { + kind: meta.kind, + filename: meta.filename, + dirname: meta.dirname, + iterations: summaries.length, + summaries + }; +}; diff --git a/packages/agent-harness/src/templates/ralph-demo/ralph-demo.md b/packages/agent-harness/src/templates/ralph-demo/ralph-demo.md new file mode 100644 index 0000000000..66bd146a52 --- /dev/null +++ b/packages/agent-harness/src/templates/ralph-demo/ralph-demo.md @@ -0,0 +1,21 @@ +--- +$schema: https://poe-platform.github.io/poe-code/schemas/harnesses/ralph-demo.schema.json +kind: ralph-demo +version: 1 +agent: + agent: claude-code + mode: edit + prompt: | + Work through the plan one focused iteration at a time. +steps: + - id: inspect + prompt: Inspect the plan and repository state. + - id: improve + prompt: Make one focused improvement and summarize the result. +goal: Improve the current repository state while preserving tests. +--- + +# Ralph Demo + +Review the repository, make one focused improvement, then summarize what changed +and what should happen next. diff --git a/packages/agent-harness/src/templates/superintendent-demo/superintendent-demo.ajs b/packages/agent-harness/src/templates/superintendent-demo/superintendent-demo.ajs new file mode 100644 index 0000000000..e1752a7f71 --- /dev/null +++ b/packages/agent-harness/src/templates/superintendent-demo/superintendent-demo.ajs @@ -0,0 +1,74 @@ +import { S } from "schema"; +import { spawn } from "agent"; +import { event } from "log"; + +export const schema = S.Object({ + "$schema": S.Enum(["https://poe-platform.github.io/poe-code/schemas/harnesses/superintendent-demo.schema.json"]), + kind: S.Enum(["superintendent-demo"]), + version: S.Number(), + agents: S.Object({ + builder: S.Object({ + agent: S.String(), + mode: S.Optional(S.Enum(["read", "edit", "yolo"])), + prompt: S.Optional(S.String()) + }), + security: S.Object({ + agent: S.String(), + mode: S.Optional(S.Enum(["read", "edit", "yolo"])), + prompt: S.Optional(S.String()) + }), + perf: S.Object({ + agent: S.String(), + mode: S.Optional(S.Enum(["read", "edit", "yolo"])), + prompt: S.Optional(S.String()) + }), + tests: S.Object({ + agent: S.String(), + mode: S.Optional(S.Enum(["read", "edit", "yolo"])), + prompt: S.Optional(S.String()) + }), + judge: S.Object({ + agent: S.String(), + mode: S.Optional(S.Enum(["read", "edit", "yolo"])), + prompt: S.Optional(S.String()) + }), + owner: S.Object({ + agent: S.String(), + mode: S.Optional(S.Enum(["read", "edit", "yolo"])), + prompt: S.Optional(S.String()) + }) + }), + max_rounds: S.Number({ minimum: 1 }) +}); + +export default async (frontmatter) => { + const meta = import.meta; + const inspectors = [frontmatter.agents.security, frontmatter.agents.perf, frontmatter.agents.tests]; + const builder = await spawn(frontmatter.agents.builder, { + prompt: "Round 1: ".concat(meta.body) + }); + const reports = await Promise.all( + inspectors.map(async (inspector) => + await spawn(inspector, { + prompt: "Inspect round 1\n\n".concat(builder.summary) + }) + ) + ); + const verdict = await spawn(frontmatter.agents.judge, { + prompt: "Judge round 1\n\n".concat(reports.map((report) => report.summary).join("\n")) + }); + const owner = await spawn(frontmatter.agents.owner, { prompt: verdict.summary }); + event("round.completed", { + round: 1, + owner: owner.summary + }); + + return { + kind: meta.kind, + filename: meta.filename, + dirname: meta.dirname, + rounds: 1, + maxRounds: frontmatter.max_rounds, + inspectors: reports.length + }; +}; diff --git a/packages/agent-harness/src/templates/superintendent-demo/superintendent-demo.md b/packages/agent-harness/src/templates/superintendent-demo/superintendent-demo.md new file mode 100644 index 0000000000..9480c4d780 --- /dev/null +++ b/packages/agent-harness/src/templates/superintendent-demo/superintendent-demo.md @@ -0,0 +1,42 @@ +--- +$schema: https://poe-platform.github.io/poe-code/schemas/harnesses/superintendent-demo.schema.json +kind: superintendent-demo +version: 1 +agents: + builder: + agent: claude-code + mode: edit + prompt: | + Build the requested change set. + security: + agent: claude-code + mode: read + prompt: | + Review for auth, validation, and secret handling issues. + perf: + agent: claude-code + mode: read + prompt: | + Review for regressions and obvious inefficiencies. + tests: + agent: claude-code + mode: read + prompt: | + Review the test plan and likely gaps. + judge: + agent: claude-code + mode: read + prompt: | + Decide whether the builder output is ready for owner review. + owner: + agent: claude-code + mode: read + prompt: | + Final approval gate. +max_rounds: 3 +--- + +# Superintendent Demo + +Run one builder round, collect specialist reviews, ask the judge for a readiness +decision, and pass that decision to the owner gate. diff --git a/packages/agent-script/src/lint/rules/AS006-007.test.ts b/packages/agent-script/src/lint/rules/AS006-007.test.ts index ffde669ab5..5a4c956b8f 100644 --- a/packages/agent-script/src/lint/rules/AS006-007.test.ts +++ b/packages/agent-script/src/lint/rules/AS006-007.test.ts @@ -28,6 +28,17 @@ describe("AS006_007", () => { ]); }); + it("counts reads inside named and default export declarations", () => { + const source = [ + 'import { S } from "schema";', + 'import { run } from "agent";', + "export const schema = S.Object({ name: S.String() });", + "export default (input) => run(input.name);" + ].join("\n"); + + expect(AS006_007(source, { filename: "rule.js" })).toEqual([]); + }); + it("reports unread const and let bindings as AS007 warnings but ignores writes and underscore-prefixed names", () => { const source = [ "const used = 1;", diff --git a/packages/agent-script/src/lint/rules/AS006-007.ts b/packages/agent-script/src/lint/rules/AS006-007.ts index 432cdb0c94..5b7a528f38 100644 --- a/packages/agent-script/src/lint/rules/AS006-007.ts +++ b/packages/agent-script/src/lint/rules/AS006-007.ts @@ -98,6 +98,12 @@ class AS006007Scanner { private visitStatement(node: Statement): void { switch (node.type) { + case "ExportNamedDeclaration": + this.visitVariableDeclaration(node.declaration); + return; + case "ExportDefaultDeclaration": + this.visitExpression(node.declaration); + return; case "BlockStatement": this.visitBlock(node); return; @@ -540,6 +546,10 @@ class AS006007Scanner { } if (statement.type === "VariableDeclaration") { bindings.push(...this.collectDeclarationBindings(statement)); + continue; + } + if (statement.type === "ExportNamedDeclaration") { + bindings.push(...this.collectExportDeclarationBindings(statement.declaration)); } } @@ -578,6 +588,13 @@ class AS006007Scanner { return bindings; } + private collectExportDeclarationBindings(node: VariableDeclaration): Binding[] { + return this.collectDeclarationBindings(node).map((binding) => ({ + ...binding, + code: undefined + })); + } + private collectCatchBindings(node: CatchClause): Binding[] { const bindings: Binding[] = []; From 70202eb5ff8b18cf0edb12864b075a5cb0ee01ff Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 00:31:34 -0500 Subject: [PATCH 057/111] feat: generate harness schemas --- docs/plans/agent-harness.md | 6 +- docs/plans/agent-harness.md.lock | 2 +- docs/schemas/harnesses/.gitkeep | 1 + .../harnesses/experiment-demo.schema.json | 98 ++++++++++ .../harnesses/pipeline-demo.schema.json | 105 +++++++++++ docs/schemas/harnesses/ralph-demo.schema.json | 74 ++++++++ .../harnesses/superintendent-demo.schema.json | 178 ++++++++++++++++++ package.json | 3 +- .../src/codegen/emit-schemas.test.ts | 70 +++++++ .../agent-harness/src/codegen/emit-schemas.ts | 154 +++++++++++++++ packages/agent-harness/src/index.ts | 1 + scripts/generate-harness-schemas.ts | 1 + 12 files changed, 688 insertions(+), 5 deletions(-) create mode 100644 docs/schemas/harnesses/.gitkeep create mode 100644 docs/schemas/harnesses/experiment-demo.schema.json create mode 100644 docs/schemas/harnesses/pipeline-demo.schema.json create mode 100644 docs/schemas/harnesses/ralph-demo.schema.json create mode 100644 docs/schemas/harnesses/superintendent-demo.schema.json create mode 100644 packages/agent-harness/src/codegen/emit-schemas.test.ts create mode 100644 packages/agent-harness/src/codegen/emit-schemas.ts create mode 100644 scripts/generate-harness-schemas.ts diff --git a/docs/plans/agent-harness.md b/docs/plans/agent-harness.md index 850935234a..7cf2e24ba8 100644 --- a/docs/plans/agent-harness.md +++ b/docs/plans/agent-harness.md @@ -601,7 +601,7 @@ tasks: status: implement: done test: done - commit: open + commit: done - id: agent-harness-codegen title: Codegen *.schema.json from agent-harness templates @@ -646,8 +646,8 @@ tasks: with the expected $id and a stable key order. Do not write to the real filesystem. status: - implement: open - test: open + implement: done + test: done commit: open - id: agent-harness-cli diff --git a/docs/plans/agent-harness.md.lock b/docs/plans/agent-harness.md.lock index 1e7c132e1e..f1cd1391c0 100644 --- a/docs/plans/agent-harness.md.lock +++ b/docs/plans/agent-harness.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T05:23:19.624Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T05:30:34.305Z"} \ No newline at end of file diff --git a/docs/schemas/harnesses/.gitkeep b/docs/schemas/harnesses/.gitkeep new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/docs/schemas/harnesses/.gitkeep @@ -0,0 +1 @@ + diff --git a/docs/schemas/harnesses/experiment-demo.schema.json b/docs/schemas/harnesses/experiment-demo.schema.json new file mode 100644 index 0000000000..aed4ef375e --- /dev/null +++ b/docs/schemas/harnesses/experiment-demo.schema.json @@ -0,0 +1,98 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://poe-platform.github.io/poe-code/schemas/harnesses/experiment-demo.schema.json", + "type": "object", + "properties": { + "$schema": { + "type": "string", + "enum": [ + "https://poe-platform.github.io/poe-code/schemas/harnesses/experiment-demo.schema.json" + ] + }, + "agents": { + "type": "object", + "properties": { + "experimenter": { + "type": "object", + "properties": { + "agent": { + "type": "string" + }, + "mode": { + "type": "string", + "enum": [ + "read", + "edit", + "yolo" + ] + }, + "prompt": { + "type": "string" + } + }, + "required": [ + "agent" + ] + } + }, + "required": [ + "experimenter" + ] + }, + "attempts": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "prompt": { + "type": "string" + } + }, + "required": [ + "id", + "prompt" + ] + } + }, + "kind": { + "type": "string", + "enum": [ + "experiment-demo" + ] + }, + "metric": { + "type": "object", + "properties": { + "direction": { + "type": "string", + "enum": [ + "maximize", + "minimize" + ] + }, + "name": { + "type": "string" + } + }, + "required": [ + "name", + "direction" + ] + }, + "version": { + "type": "number" + } + }, + "required": [ + "$schema", + "kind", + "version", + "agents", + "metric", + "attempts" + ] +} diff --git a/docs/schemas/harnesses/pipeline-demo.schema.json b/docs/schemas/harnesses/pipeline-demo.schema.json new file mode 100644 index 0000000000..4388ce6c90 --- /dev/null +++ b/docs/schemas/harnesses/pipeline-demo.schema.json @@ -0,0 +1,105 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://poe-platform.github.io/poe-code/schemas/harnesses/pipeline-demo.schema.json", + "type": "object", + "properties": { + "$schema": { + "type": "string", + "enum": [ + "https://poe-platform.github.io/poe-code/schemas/harnesses/pipeline-demo.schema.json" + ] + }, + "agents": { + "type": "object", + "properties": { + "builder": { + "type": "object", + "properties": { + "agent": { + "type": "string" + }, + "mode": { + "type": "string", + "enum": [ + "read", + "edit", + "yolo" + ] + }, + "prompt": { + "type": "string" + } + }, + "required": [ + "agent" + ] + }, + "reviewer": { + "type": "object", + "properties": { + "agent": { + "type": "string" + }, + "mode": { + "type": "string", + "enum": [ + "read", + "edit", + "yolo" + ] + }, + "prompt": { + "type": "string" + } + }, + "required": [ + "agent" + ] + } + }, + "required": [ + "builder", + "reviewer" + ] + }, + "kind": { + "type": "string", + "enum": [ + "pipeline-demo" + ] + }, + "tasks": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "properties": { + "title": { + "type": "string" + }, + "id": { + "type": "string" + }, + "prompt": { + "type": "string" + } + }, + "required": [ + "id", + "title", + "prompt" + ] + } + }, + "version": { + "type": "number" + } + }, + "required": [ + "$schema", + "kind", + "version", + "agents", + "tasks" + ] +} diff --git a/docs/schemas/harnesses/ralph-demo.schema.json b/docs/schemas/harnesses/ralph-demo.schema.json new file mode 100644 index 0000000000..719d690d57 --- /dev/null +++ b/docs/schemas/harnesses/ralph-demo.schema.json @@ -0,0 +1,74 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://poe-platform.github.io/poe-code/schemas/harnesses/ralph-demo.schema.json", + "type": "object", + "properties": { + "$schema": { + "type": "string", + "enum": [ + "https://poe-platform.github.io/poe-code/schemas/harnesses/ralph-demo.schema.json" + ] + }, + "agent": { + "type": "object", + "properties": { + "agent": { + "type": "string" + }, + "mode": { + "type": "string", + "enum": [ + "read", + "edit", + "yolo" + ] + }, + "prompt": { + "type": "string" + } + }, + "required": [ + "agent" + ] + }, + "goal": { + "type": "string" + }, + "kind": { + "type": "string", + "enum": [ + "ralph-demo" + ] + }, + "steps": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "prompt": { + "type": "string" + } + }, + "required": [ + "id", + "prompt" + ] + } + }, + "version": { + "type": "number" + } + }, + "required": [ + "$schema", + "kind", + "version", + "agent", + "steps", + "goal" + ] +} diff --git a/docs/schemas/harnesses/superintendent-demo.schema.json b/docs/schemas/harnesses/superintendent-demo.schema.json new file mode 100644 index 0000000000..a8d7e1fa7a --- /dev/null +++ b/docs/schemas/harnesses/superintendent-demo.schema.json @@ -0,0 +1,178 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://poe-platform.github.io/poe-code/schemas/harnesses/superintendent-demo.schema.json", + "type": "object", + "properties": { + "$schema": { + "type": "string", + "enum": [ + "https://poe-platform.github.io/poe-code/schemas/harnesses/superintendent-demo.schema.json" + ] + }, + "agents": { + "type": "object", + "properties": { + "builder": { + "type": "object", + "properties": { + "agent": { + "type": "string" + }, + "mode": { + "type": "string", + "enum": [ + "read", + "edit", + "yolo" + ] + }, + "prompt": { + "type": "string" + } + }, + "required": [ + "agent" + ] + }, + "judge": { + "type": "object", + "properties": { + "agent": { + "type": "string" + }, + "mode": { + "type": "string", + "enum": [ + "read", + "edit", + "yolo" + ] + }, + "prompt": { + "type": "string" + } + }, + "required": [ + "agent" + ] + }, + "owner": { + "type": "object", + "properties": { + "agent": { + "type": "string" + }, + "mode": { + "type": "string", + "enum": [ + "read", + "edit", + "yolo" + ] + }, + "prompt": { + "type": "string" + } + }, + "required": [ + "agent" + ] + }, + "perf": { + "type": "object", + "properties": { + "agent": { + "type": "string" + }, + "mode": { + "type": "string", + "enum": [ + "read", + "edit", + "yolo" + ] + }, + "prompt": { + "type": "string" + } + }, + "required": [ + "agent" + ] + }, + "security": { + "type": "object", + "properties": { + "agent": { + "type": "string" + }, + "mode": { + "type": "string", + "enum": [ + "read", + "edit", + "yolo" + ] + }, + "prompt": { + "type": "string" + } + }, + "required": [ + "agent" + ] + }, + "tests": { + "type": "object", + "properties": { + "agent": { + "type": "string" + }, + "mode": { + "type": "string", + "enum": [ + "read", + "edit", + "yolo" + ] + }, + "prompt": { + "type": "string" + } + }, + "required": [ + "agent" + ] + } + }, + "required": [ + "builder", + "security", + "perf", + "tests", + "judge", + "owner" + ] + }, + "kind": { + "type": "string", + "enum": [ + "superintendent-demo" + ] + }, + "max_rounds": { + "type": "number", + "minimum": 1 + }, + "version": { + "type": "number" + } + }, + "required": [ + "$schema", + "kind", + "version", + "agents", + "max_rounds" + ] +} diff --git a/package.json b/package.json index b7f4911556..0d25ec4bf1 100644 --- a/package.json +++ b/package.json @@ -19,7 +19,7 @@ "packages/*" ], "scripts": { - "build": "turbo run build && npm run codegen:plan-schemas && tsc -p tsconfig.build.json && node scripts/generate-bin-wrappers.mjs && node scripts/bundle.mjs", + "build": "turbo run build && npm run codegen:plan-schemas && npm run codegen:harness-schemas && tsc -p tsconfig.build.json && node scripts/generate-bin-wrappers.mjs && node scripts/bundle.mjs", "build:deps": "node scripts/list-workspace-deps.mjs", "codegen:python-types": "tsx scripts/generate-agent-spawn-py-types.ts", "codegen:check:python-types": "tsx scripts/generate-agent-spawn-py-types.ts --check", @@ -72,6 +72,7 @@ "demo:dashboard": "tsx packages/design-system/src/dashboard/demo.ts", "replay": "tsx packages/agent-spawn/src/acp/replay-cli.ts", "codegen:plan-schemas": "tsx scripts/generate-plan-schemas.ts", + "codegen:harness-schemas": "tsx scripts/generate-harness-schemas.ts", "smoke:toolcraft-standalone": "node scripts/verify-toolcraft-standalone.mjs", "sync-skills": "tsx scripts/sync-skills.ts" }, diff --git a/packages/agent-harness/src/codegen/emit-schemas.test.ts b/packages/agent-harness/src/codegen/emit-schemas.test.ts new file mode 100644 index 0000000000..9a5389e8e2 --- /dev/null +++ b/packages/agent-harness/src/codegen/emit-schemas.test.ts @@ -0,0 +1,70 @@ +import { Volume, createFsFromVolume } from "memfs"; +import { describe, expect, it } from "vitest"; + +import { runHarnessCodegen } from "./emit-schemas.js"; + +describe("harness schema codegen", () => { + it("writes all built-in harness schema files into docs/schemas/harnesses", async () => { + const volume = new Volume(); + const fs = createFsFromVolume(volume).promises; + + await runHarnessCodegen({ + fs, + repoRoot: "/repo" + }); + + await expect( + fs.readdir("/repo/docs/schemas/harnesses").then((entries) => [...entries].sort()) + ).resolves.toEqual([ + "experiment-demo.schema.json", + "pipeline-demo.schema.json", + "ralph-demo.schema.json", + "superintendent-demo.schema.json" + ]); + + for (const kind of [ + "experiment-demo", + "pipeline-demo", + "ralph-demo", + "superintendent-demo" + ]) { + const raw = await fs.readFile(`/repo/docs/schemas/harnesses/${kind}.schema.json`, "utf8"); + const schema = JSON.parse(raw.toString()) as { + $id?: string; + $schema?: string; + properties?: Record; + }; + + expect(schema.$schema).toBe("https://json-schema.org/draft/2020-12/schema"); + expect(schema.$id).toBe( + `https://poe-platform.github.io/poe-code/schemas/harnesses/${kind}.schema.json` + ); + expect(schema.properties).toHaveProperty("$schema"); + } + }); + + it("serializes schema keys in a stable order", async () => { + const volume = new Volume(); + const fs = createFsFromVolume(volume).promises; + + await runHarnessCodegen({ + fs, + repoRoot: "/repo" + }); + + const raw = await fs.readFile("/repo/docs/schemas/harnesses/ralph-demo.schema.json", "utf8"); + const lines = raw.toString().split("\n"); + + expect(lines.slice(0, 4)).toEqual([ + "{", + ' "$schema": "https://json-schema.org/draft/2020-12/schema",', + ' "$id": "https://poe-platform.github.io/poe-code/schemas/harnesses/ralph-demo.schema.json",', + ' "type": "object",' + ]); + expect(raw.toString()).toContain(` "properties": { + "$schema": { + "type": "string", + "enum": [ + "https://poe-platform.github.io/poe-code/schemas/harnesses/ralph-demo.schema.json"`); + }); +}); diff --git a/packages/agent-harness/src/codegen/emit-schemas.ts b/packages/agent-harness/src/codegen/emit-schemas.ts new file mode 100644 index 0000000000..699b42895f --- /dev/null +++ b/packages/agent-harness/src/codegen/emit-schemas.ts @@ -0,0 +1,154 @@ +import * as nodeFs from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +import { toJsonSchema } from "toolcraft-schema"; + +import { extractSchema } from "../loader/extract-schema.js"; + +interface HarnessSchemaFileSystem { + mkdir(path: string, options?: { recursive?: boolean }): Promise; + writeFile( + filePath: string, + data: string, + options?: BufferEncoding | { encoding?: BufferEncoding } + ): Promise; +} + +interface RunHarnessCodegenOptions { + fs?: HarnessSchemaFileSystem; + repoRoot?: string; +} + +type JsonValue = + | null + | boolean + | number + | string + | JsonValue[] + | { [key: string]: JsonValue | undefined }; + +const draft202012SchemaId = "https://json-schema.org/draft/2020-12/schema"; +const publicHarnessSchemaBaseUrl = "https://poe-platform.github.io/poe-code/schemas/harnesses"; + +export async function runHarnessCodegen( + options: RunHarnessCodegenOptions = {} +): Promise { + const fs = options.fs ?? nodeFs; + const repoRoot = options.repoRoot ?? resolveRepoRoot(); + const outputDirectory = path.join(repoRoot, "docs", "schemas", "harnesses"); + + await fs.mkdir(outputDirectory, { recursive: true }); + + for (const template of await listBuiltinTemplateSchemaSources()) { + const ajsSource = await nodeFs.readFile(template.ajsPath, "utf8"); + const schema = await extractSchema(ajsSource, template.ajsPath); + + if (schema === undefined) { + throw new Error(`Built-in harness template ${template.kind} does not export a schema.`); + } + + const fileName = `${template.kind}.schema.json`; + const document = { + $schema: draft202012SchemaId, + $id: `${publicHarnessSchemaBaseUrl}/${fileName}`, + ...toJsonSchema(schema) + }; + + await fs.writeFile( + path.join(outputDirectory, fileName), + serializeJsonDocument(document), + "utf8" + ); + } +} + +function resolveRepoRoot(): string { + return path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../../.."); +} + +async function listBuiltinTemplateSchemaSources(): Promise> { + const templateDirectory = fileURLToPath(new URL("../templates/", import.meta.url)); + const entries = await nodeFs.readdir(templateDirectory, { withFileTypes: true }); + + return entries + .filter((entry) => entry.isDirectory()) + .map((entry) => ({ + kind: entry.name, + ajsPath: path.join(templateDirectory, entry.name, `${entry.name}.ajs`) + })) + .sort((left, right) => left.kind.localeCompare(right.kind)); +} + +function serializeJsonDocument(value: unknown): string { + return `${JSON.stringify(sortJsonValue(value), null, 2)}\n`; +} + +function sortJsonValue(value: unknown): JsonValue { + if (Array.isArray(value)) { + return value.map((item) => sortJsonValue(item)); + } + + if (isRecord(value)) { + return Object.fromEntries( + Object.entries(value) + .sort(compareJsonKeys) + .map(([key, nestedValue]) => [key, sortJsonValue(nestedValue)]) + ); + } + + if ( + value === null || + typeof value === "boolean" || + typeof value === "number" || + typeof value === "string" + ) { + return value; + } + + return JSON.parse(JSON.stringify(value)) as JsonValue; +} + +const jsonKeyOrder = [ + "$schema", + "$id", + "title", + "description", + "type", + "const", + "default", + "enum", + "minimum", + "exclusiveMinimum", + "minLength", + "minItems", + "items", + "properties", + "required", + "additionalProperties", + "anyOf", + "oneOf" +] as const; + +function compareJsonKeys([left]: [string, unknown], [right]: [string, unknown]): number { + const leftIndex = jsonKeyOrder.indexOf(left as (typeof jsonKeyOrder)[number]); + const rightIndex = jsonKeyOrder.indexOf(right as (typeof jsonKeyOrder)[number]); + + if (leftIndex !== -1 || rightIndex !== -1) { + if (leftIndex === -1) { + return 1; + } + + if (rightIndex === -1) { + return -1; + } + + return leftIndex - rightIndex; + } + + return left.localeCompare(right); +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null; +} diff --git a/packages/agent-harness/src/index.ts b/packages/agent-harness/src/index.ts index 7c1be87453..4a4e2cc4b2 100644 --- a/packages/agent-harness/src/index.ts +++ b/packages/agent-harness/src/index.ts @@ -1,4 +1,5 @@ export { makeSchemaModule } from "./modules/schema.js"; +export { runHarnessCodegen } from "./codegen/emit-schemas.js"; export { discoverHarnesses } from "./discovery/discover.js"; export { extractSchema } from "./loader/extract-schema.js"; export { runHarnessPair } from "./loader/run.js"; diff --git a/scripts/generate-harness-schemas.ts b/scripts/generate-harness-schemas.ts new file mode 100644 index 0000000000..bef68e3d03 --- /dev/null +++ b/scripts/generate-harness-schemas.ts @@ -0,0 +1 @@ +import { runHarnessCodegen } from "../packages/agent-harness/src/index.js"; await runHarnessCodegen(); From cf8a2ba9c3b5595e66af692614de75ce24d27419 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 00:40:17 -0500 Subject: [PATCH 058/111] feat(cli): add harness command --- docs/plans/agent-harness.md | 6 +- docs/plans/agent-harness.md.lock | 2 +- src/cli/commands/harness-command.test.ts | 271 +++++++++++++++++ src/cli/commands/harness.ts | 372 +++++++++++++++++++++++ src/cli/program.ts | 5 + 5 files changed, 652 insertions(+), 4 deletions(-) create mode 100644 src/cli/commands/harness-command.test.ts create mode 100644 src/cli/commands/harness.ts diff --git a/docs/plans/agent-harness.md b/docs/plans/agent-harness.md index 7cf2e24ba8..8acaaaf3d9 100644 --- a/docs/plans/agent-harness.md +++ b/docs/plans/agent-harness.md @@ -648,7 +648,7 @@ tasks: status: implement: done test: done - commit: open + commit: done - id: agent-harness-cli title: Add `poe-code harness {run,new,list}` CLI command @@ -695,8 +695,8 @@ tasks: Do not commit screenshot tests; screenshots are for ad-hoc validation only. status: - implement: open - test: open + implement: done + test: done commit: open --- diff --git a/docs/plans/agent-harness.md.lock b/docs/plans/agent-harness.md.lock index f1cd1391c0..b804e5f207 100644 --- a/docs/plans/agent-harness.md.lock +++ b/docs/plans/agent-harness.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T05:30:34.305Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T05:39:19.841Z"} \ No newline at end of file diff --git a/src/cli/commands/harness-command.test.ts b/src/cli/commands/harness-command.test.ts new file mode 100644 index 0000000000..8b33665865 --- /dev/null +++ b/src/cli/commands/harness-command.test.ts @@ -0,0 +1,271 @@ +import path from "node:path"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { vol, fs as memfs } from "memfs"; +import { Command } from "commander"; +import { createCliContainer } from "../container.js"; +import type { FileSystem } from "../../utils/file-system.js"; + +const harnessMocks = vi.hoisted(() => ({ + runHarnessPairMock: vi.fn(), + listBuiltinTemplatesMock: vi.fn(), + selectMock: vi.fn(), + promptTextMock: vi.fn(), + spawnMock: vi.fn() +})); + +vi.mock("node:fs/promises", async () => { + const { fs } = await import("memfs"); + return { + ...fs.promises, + default: fs.promises + }; +}); + +vi.mock("@poe-code/agent-harness", async () => { + const actual = + await vi.importActual("@poe-code/agent-harness"); + return { + ...actual, + runHarnessPair: harnessMocks.runHarnessPairMock, + listBuiltinTemplates: harnessMocks.listBuiltinTemplatesMock + }; +}); + +vi.mock("@poe-code/design-system", async () => { + const actual = + await vi.importActual("@poe-code/design-system"); + return { + ...actual, + select: harnessMocks.selectMock, + promptText: harnessMocks.promptTextMock, + withSpinner: async (options: { fn: () => Promise }) => options.fn() + }; +}); + +vi.mock("../../sdk/spawn.js", () => ({ + spawn: harnessMocks.spawnMock +})); + +vi.mock("../../providers/index.js", () => ({ + getDefaultProviders: () => [] +})); + +const { registerHarnessCommand } = await import("./harness.js"); + +const cwd = "/repo"; +const homeDir = "/home/test"; + +function createBaseProgram(): Command { + const program = new Command(); + program.exitOverride(); + program.name("poe-code").option("-y, --yes").option("--dry-run").option("--verbose"); + return program; +} + +function createContainer(logs: string[] = []): ReturnType { + return createCliContainer({ + fs: memfs.promises as unknown as FileSystem, + prompts: vi.fn().mockResolvedValue({}), + env: { cwd, homeDir }, + logger: (message) => logs.push(message), + commandRunner: vi.fn().mockResolvedValue({ exitCode: 0, stdout: "1\n", stderr: "" }) + }); +} + +async function runHarnessCommand(args: string[], logs: string[] = []): Promise { + const program = createBaseProgram(); + registerHarnessCommand(program, createContainer(logs)); + await program.parseAsync(["node", "cli", ...args]); +} + +function writePair(root: string, basename: string): void { + vol.fromJSON({ + [path.join(root, basename, `${basename}.md`)]: "---\nkind: test\nversion: 1\n---\n", + [path.join(root, basename, `${basename}.ajs`)]: "export default () => true;\n" + }); +} + +describe("harness command", () => { + beforeEach(() => { + vol.reset(); + vol.mkdirSync(cwd, { recursive: true }); + vol.mkdirSync(homeDir, { recursive: true }); + vol.fromJSON({ + "/templates/demo.md": "---\nkind: demo\nversion: 1\n---\n# Demo\n", + "/templates/demo.ajs": "export default () => true;\n" + }); + harnessMocks.runHarnessPairMock.mockReset(); + harnessMocks.runHarnessPairMock.mockResolvedValue({ ok: true, returnValue: "done" }); + harnessMocks.listBuiltinTemplatesMock.mockReset(); + harnessMocks.listBuiltinTemplatesMock.mockReturnValue([ + { kind: "demo", mdPath: "/templates/demo.md", ajsPath: "/templates/demo.ajs" } + ]); + harnessMocks.selectMock.mockReset(); + harnessMocks.promptTextMock.mockReset(); + harnessMocks.spawnMock.mockReset(); + harnessMocks.spawnMock.mockReturnValue({ + events: (async function* () {})(), + result: Promise.resolve({ exitCode: 0, stdout: "spawned", stderr: "" }) + }); + }); + + it("runs an explicit harness path and wires agent spawns through the SDK", async () => { + let agentModule: Map | undefined; + harnessMocks.runHarnessPairMock.mockImplementation(async (_mdPath, options) => { + const modules = options.modulesFor( + { kind: "test", version: 1, agents: { builder: "codex" }, tasks: [] }, + { + kind: "test", + version: 1, + filename: "/repo/harness.md", + dirname: "/repo", + body: "" + } + ); + agentModule = modules.agent; + const spawn = agentModule?.get("spawn") as ( + agentDef: string, + spawnOptions: { prompt: string } + ) => Promise; + await spawn("codex", { prompt: "Build it" }); + return { ok: true, returnValue: "done" }; + }); + + await runHarnessCommand(["harness", "run", "harness.md"]); + + expect(harnessMocks.runHarnessPairMock).toHaveBeenCalledWith( + "/repo/harness.md", + expect.objectContaining({ modulesFor: expect.any(Function) }) + ); + expect(harnessMocks.spawnMock).toHaveBeenCalledWith( + "codex", + expect.objectContaining({ cwd: "/repo", prompt: "Build it" }) + ); + }); + + it("runs the single discovered project harness when no path is provided", async () => { + writePair("/repo/.poe-code/harnesses", "review"); + + await runHarnessCommand(["--yes", "harness", "run"]); + + expect(harnessMocks.runHarnessPairMock).toHaveBeenCalledWith( + "/repo/.poe-code/harnesses/review/review.md", + expect.objectContaining({ modulesFor: expect.any(Function) }) + ); + }); + + it("fails run discovery when no harnesses are found", async () => { + await expect(runHarnessCommand(["harness", "run"])).rejects.toThrow(/no harness pairs found/i); + expect(harnessMocks.runHarnessPairMock).not.toHaveBeenCalled(); + }); + + it("runs the selected discovered harness when multiple harnesses are found interactively", async () => { + writePair("/repo/.poe-code/harnesses", "alpha"); + writePair("/repo/.poe-code/harnesses", "beta"); + harnessMocks.selectMock.mockResolvedValue("/repo/.poe-code/harnesses/beta/beta.md"); + + await runHarnessCommand(["harness", "run"]); + + expect(harnessMocks.selectMock).toHaveBeenCalledWith( + expect.objectContaining({ + message: "Select harness", + options: expect.arrayContaining([ + expect.objectContaining({ label: expect.stringContaining("alpha") }), + expect.objectContaining({ label: expect.stringContaining("beta") }) + ]) + }) + ); + expect(harnessMocks.runHarnessPairMock).toHaveBeenCalledWith( + "/repo/.poe-code/harnesses/beta/beta.md", + expect.objectContaining({ modulesFor: expect.any(Function) }) + ); + }); + + it("fails discovery under --yes when multiple harnesses are found", async () => { + writePair("/repo/.poe-code/harnesses", "alpha"); + writePair("/repo/.poe-code/harnesses", "beta"); + + await expect(runHarnessCommand(["--yes", "harness", "run"])).rejects.toThrow( + /ambiguous, pass a path/i + ); + expect(harnessMocks.runHarnessPairMock).not.toHaveBeenCalled(); + }); + + it("fails new when the template kind is missing", async () => { + await expect( + runHarnessCommand(["--yes", "harness", "new", "missing", "example"]) + ).rejects.toThrow(/unknown harness template/i); + }); + + it("scaffolds a new pair from a built-in template", async () => { + const logs: string[] = []; + + await runHarnessCommand(["--yes", "harness", "new", "demo", "example"], logs); + + await expect( + memfs.promises.readFile("/repo/.poe-code/harnesses/example/example.md", "utf8") + ).resolves.toContain("# Demo"); + await expect( + memfs.promises.readFile("/repo/.poe-code/harnesses/example/example.ajs", "utf8") + ).resolves.toContain("export default"); + expect(logs.join("\n")).toContain("Created harness pair"); + }); + + it("scaffolds into an explicit directory without prompting", async () => { + await runHarnessCommand(["harness", "new", "demo", "example", "--dir", "qa/harnesses/demo"]); + + await expect( + memfs.promises.readFile("/repo/qa/harnesses/demo/example.md", "utf8") + ).resolves.toContain("# Demo"); + expect(harnessMocks.promptTextMock).not.toHaveBeenCalled(); + }); + + it("prompts for the scaffold directory when --dir and --yes are omitted", async () => { + harnessMocks.promptTextMock.mockResolvedValue("custom/harness"); + + await runHarnessCommand(["harness", "new", "demo", "example"]); + + await expect( + memfs.promises.readFile("/repo/custom/harness/example.md", "utf8") + ).resolves.toContain("# Demo"); + expect(harnessMocks.promptTextMock).toHaveBeenCalledWith({ + message: "Harness directory", + initialValue: ".poe-code/harnesses/example" + }); + }); + + it("refuses to overwrite an existing scaffold file", async () => { + vol.fromJSON({ + "/repo/.poe-code/harnesses/example/example.md": "# Existing\n" + }); + + await expect(runHarnessCommand(["--yes", "harness", "new", "demo", "example"])).rejects.toThrow( + /refusing to overwrite/i + ); + await expect( + memfs.promises.readFile("/repo/.poe-code/harnesses/example/example.md", "utf8") + ).resolves.toBe("# Existing\n"); + }); + + it("lists empty discovery results", async () => { + const logs: string[] = []; + + await runHarnessCommand(["harness", "list"], logs); + + expect(logs.join("\n")).toContain("No harness pairs found."); + }); + + it("lists multiple discovered harness pairs", async () => { + const logs: string[] = []; + writePair("/repo/.poe-code/harnesses", "alpha"); + writePair("/home/test/.poe-code/harnesses", "beta"); + + await runHarnessCommand(["harness", "list"], logs); + + const output = logs.join("\n"); + expect(output).toContain("alpha"); + expect(output).toContain("beta"); + expect(output).toContain(".poe-code/harnesses/alpha"); + expect(output).toContain("~/.poe-code/harnesses/beta"); + }); +}); diff --git a/src/cli/commands/harness.ts b/src/cli/commands/harness.ts new file mode 100644 index 0000000000..909ec8a2d8 --- /dev/null +++ b/src/cli/commands/harness.ts @@ -0,0 +1,372 @@ +import path from "node:path"; +import { readFile } from "node:fs/promises"; +import type { Command } from "commander"; +import { + discoverHarnesses, + listBuiltinTemplates, + runHarnessPair, + type HarnessImportMeta, + type HarnessPair +} from "@poe-code/agent-harness"; +import { + makeAgentModule, + makeFailModule, + makeGitModule, + makeHarnessModule, + makeLogModule, + makeMetricModule +} from "@poe-code/agent-script"; +import { + cancel, + getTheme, + isCancel, + promptText, + renderTable, + select, + withSpinner +} from "@poe-code/design-system"; +import type { CliContainer } from "../container.js"; +import { ValidationError } from "../errors.js"; +import { createExecutionResources, resolveCommandFlags } from "./shared.js"; +import { spawn as sdkSpawn } from "../../sdk/spawn.js"; + +type HarnessRunOptions = { + yes?: boolean; +}; + +type HarnessNewOptions = { + dir?: string; + yes?: boolean; +}; + +type ModuleExports = ReadonlyMap | Record; +type ModuleRegistry = ReadonlyMap | Record; + +type HarnessPairWithLocation = HarnessPair & { + dir: string; + mdMtimeMs: number; +}; + +export function registerHarnessCommand(program: Command, container: CliContainer): void { + const harness = program.command("harness").description("Run and manage agent harness pairs."); + + harness + .command("run") + .description("Run a harness pair.") + .argument("[md-path]", "Path to the harness .md file") + .option("-y, --yes", "Accept defaults without prompting.") + .action(async (mdPath: string | undefined, options: HarnessRunOptions) => { + await executeHarnessRun(program, container, mdPath, options); + }); + + harness + .command("new") + .description("Scaffold a harness pair from a built-in template.") + .argument("", "Built-in template kind") + .argument("", "New harness basename") + .option("--dir ", "Output directory for the harness pair") + .option("-y, --yes", "Accept defaults without prompting.") + .action(async (kind: string, basename: string, options: HarnessNewOptions) => { + await executeHarnessNew(program, container, kind, basename, options); + }); + + harness + .command("list") + .description("List discovered harness pairs.") + .action(async () => { + await executeHarnessList(program, container); + }); +} + +async function executeHarnessRun( + program: Command, + container: CliContainer, + mdPath: string | undefined, + options: HarnessRunOptions +): Promise { + const flags = resolveHarnessFlags(program, options.yes); + const resources = createExecutionResources(container, flags, "harness:run"); + const selectedPath = mdPath + ? path.resolve(container.env.cwd, mdPath) + : (await resolveDiscoveredHarness(container, flags.assumeYes)).mdPath; + + resources.logger.intro("harness run"); + + const result = await withSpinner({ + message: `Running ${formatDisplayPath(container, selectedPath)}`, + fn: () => + runHarnessPair(selectedPath, { + modulesFor: (frontmatter, meta) => createHarnessModules(container, frontmatter, meta) + }), + stopMessage: () => `Ran ${formatDisplayPath(container, selectedPath)}` + }); + + resources.logger.info(JSON.stringify(result, null, 2)); +} + +async function executeHarnessNew( + program: Command, + container: CliContainer, + kind: string, + basename: string, + options: HarnessNewOptions +): Promise { + const flags = resolveHarnessFlags(program, options.yes); + const resources = createExecutionResources(container, flags, "harness:new"); + const template = listBuiltinTemplates().find((entry) => entry.kind === kind); + + resources.logger.intro("harness new"); + + if (!template) { + throw new ValidationError(`Unknown harness template "${kind}".`); + } + + const defaultDir = path.join(".poe-code", "harnesses", basename); + const outputDir = options.dir ?? (await resolveOutputDir(defaultDir, flags.assumeYes)); + const resolvedDir = path.resolve(container.env.cwd, outputDir); + const mdPath = path.join(resolvedDir, `${basename}.md`); + const ajsPath = path.join(resolvedDir, `${basename}.ajs`); + + await assertFilesDoNotExist(container, [mdPath, ajsPath]); + + if (flags.dryRun) { + resources.logger.dryRun(`Would create ${formatDisplayPath(container, mdPath)}`); + resources.logger.dryRun(`Would create ${formatDisplayPath(container, ajsPath)}`); + return; + } + + const [mdSource, ajsSource] = await Promise.all([ + readFile(template.mdPath, "utf8"), + readFile(template.ajsPath, "utf8") + ]); + + await container.fs.mkdir(resolvedDir, { recursive: true }); + await Promise.all([ + container.fs.writeFile(mdPath, mdSource, { encoding: "utf8" }), + container.fs.writeFile(ajsPath, ajsSource, { encoding: "utf8" }) + ]); + + resources.context.complete({ + success: `Created harness pair at ${formatDisplayPath(container, resolvedDir)}`, + dry: `Would create harness pair at ${formatDisplayPath(container, resolvedDir)}` + }); + resources.context.finalize(); +} + +async function executeHarnessList(program: Command, container: CliContainer): Promise { + const flags = resolveCommandFlags(program); + const resources = createExecutionResources(container, flags, "harness:list"); + + resources.logger.intro("harness list"); + + const pairs = await discoverProjectThenUserHarnesses(container); + if (pairs.length === 0) { + resources.logger.info("No harness pairs found."); + return; + } + + const theme = getTheme(); + const rows = pairs.map((pair) => ({ + Basename: theme.accent(pair.basename), + Dir: formatDisplayPath(container, pair.dir), + "MD mtime": new Date(pair.mdMtimeMs).toISOString() + })); + + resources.logger.info( + renderTable({ + theme, + columns: [ + { name: "Basename", title: "Basename", alignment: "left", maxLen: 28 }, + { name: "Dir", title: "Dir", alignment: "left", maxLen: 64 }, + { name: "MD mtime", title: ".md mtime", alignment: "left", maxLen: 24 } + ], + rows + }) + ); +} + +function resolveHarnessFlags( + program: Command, + commandYes: boolean | undefined +): ReturnType { + const flags = resolveCommandFlags(program); + return { + ...flags, + assumeYes: flags.assumeYes || Boolean(commandYes) + }; +} + +async function resolveDiscoveredHarness( + container: CliContainer, + assumeYes: boolean +): Promise { + const pairs = await discoverProjectThenUserHarnesses(container); + + if (pairs.length === 0) { + throw new ValidationError("No harness pairs found."); + } + + if (pairs.length === 1) { + return pairs[0]!; + } + + if (assumeYes) { + throw new ValidationError("Multiple harness pairs found; ambiguous, pass a path."); + } + + const selected = await select({ + message: "Select harness", + options: pairs.map((pair) => ({ + label: `${pair.basename} (${formatDisplayPath(container, pair.dir)})`, + value: pair.mdPath + })) + }); + + if (isCancel(selected)) { + cancel("Operation cancelled."); + throw new ValidationError("Operation cancelled."); + } + + const pair = pairs.find((entry) => entry.mdPath === selected); + if (!pair) { + throw new ValidationError("Selected harness was not found."); + } + return pair; +} + +async function discoverProjectThenUserHarnesses( + container: CliContainer +): Promise { + const roots = [ + path.join(container.env.cwd, ".poe-code", "harnesses"), + path.join(container.env.homeDir, ".poe-code", "harnesses") + ]; + const discovered: HarnessPairWithLocation[] = []; + + for (const root of roots) { + const pairs = await discoverHarnesses( + root, + container.fs as Parameters[1] + ); + for (const pair of pairs) { + const stat = await container.fs.stat(pair.mdPath); + discovered.push({ + ...pair, + dir: path.dirname(pair.mdPath), + mdMtimeMs: stat.mtimeMs + }); + } + } + + return discovered; +} + +async function resolveOutputDir(defaultDir: string, assumeYes: boolean): Promise { + if (assumeYes) { + return defaultDir; + } + + const answer = await promptText({ + message: "Harness directory", + initialValue: defaultDir + }); + + if (isCancel(answer)) { + cancel("Operation cancelled."); + throw new ValidationError("Operation cancelled."); + } + + const dir = answer.trim(); + if (dir.length === 0) { + throw new ValidationError("Harness directory is required."); + } + return dir; +} + +async function assertFilesDoNotExist(container: CliContainer, filePaths: string[]): Promise { + for (const filePath of filePaths) { + if (await pathExists(container, filePath)) { + throw new ValidationError( + `Refusing to overwrite existing file: ${formatDisplayPath(container, filePath)}` + ); + } + } +} + +async function pathExists(container: CliContainer, filePath: string): Promise { + try { + await container.fs.stat(filePath); + return true; + } catch (error) { + if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") { + return false; + } + throw error; + } +} + +function createHarnessModules( + container: CliContainer, + frontmatter: Record, + meta: HarnessImportMeta +): ModuleRegistry { + const harnessMeta = { + kind: meta.kind, + version: meta.version, + filepath: meta.filename + }; + const agent = makeAgentModule(async (input) => { + const { result } = sdkSpawn(input.agent, { + prompt: input.prompt, + cwd: input.cwd ?? meta.dirname, + model: input.model, + mode: input.mode, + mcpServers: input.mcp, + signal: undefined + }); + const resolved = await result; + return { + exitCode: resolved.exitCode, + stdout: resolved.stdout, + stderr: resolved.stderr, + summary: resolved.stdout || resolved.stderr, + durationMs: 0 + }; + }); + const fail = makeFailModule().default; + const git = makeGitModule(meta.dirname); + const harness = makeHarnessModule(frontmatter, harnessMeta); + const log = makeLogModule(); + const metric = makeMetricModule(async (scriptName) => { + const result = await container.commandRunner("npm", ["run", scriptName], { + cwd: meta.dirname + }); + if (result.exitCode !== 0) { + throw new Error(`Metric script "${scriptName}" failed with exit code ${result.exitCode}.`); + } + return result.stdout; + }); + + return { + agent: toModuleExports(agent), + fail: toModuleExports(new Map([["default", fail]])), + git: toModuleExports(git), + harness: toModuleExports(harness), + log: toModuleExports(log), + metric: toModuleExports(metric) + }; +} + +function toModuleExports(moduleExports: ModuleExports): ModuleExports { + if (moduleExports instanceof Map) { + return moduleExports; + } + return new Map(Object.entries(moduleExports)); +} + +function formatDisplayPath(container: CliContainer, filePath: string): string { + const relative = path.relative(container.env.cwd, filePath); + return relative.length > 0 && !relative.startsWith("..") && !path.isAbsolute(relative) + ? relative + : filePath.replace(container.env.homeDir, "~"); +} diff --git a/src/cli/program.ts b/src/cli/program.ts index 77647d306a..6f8328831c 100644 --- a/src/cli/program.ts +++ b/src/cli/program.ts @@ -32,6 +32,7 @@ import { registerLaunchCommand } from "./commands/launch.js"; import { registerMemoryCommand } from "./commands/memory.js"; import { registerProviderCommand } from "./commands/provider.js"; import { registerRuntimeCommand } from "./commands/runtime/index.js"; +import { registerHarnessCommand } from "./commands/harness.js"; import packageJson from "../../package.json" with { type: "json" }; import { throwCommandNotFound } from "./command-not-found.js"; import { @@ -97,6 +98,9 @@ const ROOT_HELP_COMMAND_SPECS: readonly RootHelpCommandSpec[] = [ { path: ["runtime", "build"] }, { path: ["runtime", "templates", "ls"] }, { path: ["runtime", "templates", "clear"] }, + { path: ["harness", "run"] }, + { path: ["harness", "new"], args: " " }, + { path: ["harness", "list"] }, { path: ["experiment", "install"] }, { path: ["experiment", "run"] }, { path: ["experiment", "journal"] }, @@ -487,6 +491,7 @@ function bootstrapProgram(container: CliContainer): Command { registerMemoryCommand(program, container); registerProviderCommand(program, container); registerRuntimeCommand(program, container); + registerHarnessCommand(program, container); registerForwardedToolcraftCommand( program, container, From 44f414844e430360fce087547ccf0c6e7465cc7c Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 00:41:03 -0500 Subject: [PATCH 059/111] docs: archive agent harness plan --- docs/plans/agent-harness.md.lock | 2 +- docs/plans/{ => archive}/agent-harness.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename docs/plans/{ => archive}/agent-harness.md (99%) diff --git a/docs/plans/agent-harness.md.lock b/docs/plans/agent-harness.md.lock index b804e5f207..012e967879 100644 --- a/docs/plans/agent-harness.md.lock +++ b/docs/plans/agent-harness.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T05:39:19.841Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T05:40:30.603Z"} \ No newline at end of file diff --git a/docs/plans/agent-harness.md b/docs/plans/archive/agent-harness.md similarity index 99% rename from docs/plans/agent-harness.md rename to docs/plans/archive/agent-harness.md index 8acaaaf3d9..46b0a85d89 100644 --- a/docs/plans/agent-harness.md +++ b/docs/plans/archive/agent-harness.md @@ -697,7 +697,7 @@ tasks: status: implement: done test: done - commit: open + commit: done --- # Context From 6712a33120c8d71b708bcb6e4808c91a90927da7 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 01:35:38 -0500 Subject: [PATCH 060/111] feat: add braintrust integration --- docs/plans/agent-harness.md.lock | 1 - .../{ => archive}/braintrust-integration.md | 41 +- docs/plans/braintrust-integration.md.lock | 1 + docs/plans/qa/braintrust-integration.md | 88 ++++ package-lock.json | 27 + package.json | 1 + packages/braintrust/README.md | 107 ++++ packages/braintrust/package.json | 40 ++ .../src/adapters/experiment.test.ts | 108 ++++ .../braintrust/src/adapters/experiment.ts | 44 ++ .../braintrust/src/adapters/pipeline.test.ts | 102 ++++ packages/braintrust/src/adapters/pipeline.ts | 30 ++ .../braintrust/src/adapters/spawn.test.ts | 107 ++++ packages/braintrust/src/adapters/spawn.ts | 27 + .../src/adapters/superintendent.test.ts | 125 +++++ .../braintrust/src/adapters/superintendent.ts | 82 +++ packages/braintrust/src/bootstrap.test.ts | 181 +++++++ packages/braintrust/src/braintrust-sdk.d.ts | 41 ++ packages/braintrust/src/client.test.ts | 125 +++++ packages/braintrust/src/client.ts | 148 ++++++ packages/braintrust/src/index.ts | 108 ++++ packages/braintrust/src/integration.test.ts | 327 ++++++++++++ packages/braintrust/src/redact.test.ts | 60 +++ packages/braintrust/src/redact.ts | 45 ++ packages/braintrust/src/row-builder.test.ts | 221 ++++++++ packages/braintrust/src/row-builder.ts | 476 ++++++++++++++++++ packages/braintrust/src/span-builder.test.ts | 161 ++++++ packages/braintrust/src/span-builder.ts | 244 +++++++++ packages/braintrust/src/trace-run.test.ts | 106 ++++ packages/braintrust/src/trace-run.ts | 85 ++++ packages/braintrust/tsconfig.json | 11 + packages/poe-code-config/src/index.ts | 13 +- .../src/integrations-loader.test.ts | 28 ++ .../src/integrations-loader.ts | 39 ++ .../src/merge-callbacks.test.ts | 119 +++++ .../poe-code-config/src/merge-callbacks.ts | 103 ++++ .../src/poe-code-config.test.ts | 71 ++- packages/poe-code-config/src/schema.ts | 51 +- packages/poe-code-config/src/types.ts | 12 + .../superintendent/src/commands/run.test.ts | 55 +- packages/superintendent/src/commands/run.ts | 156 ++++-- src/cli/commands/braintrust-command.test.ts | 173 +++++++ src/cli/commands/braintrust.ts | 118 +++++ src/cli/commands/experiment-ralph.test.ts | 65 +++ src/cli/commands/experiment.ts | 78 ++- src/cli/commands/pipeline-command.test.ts | 76 +++ src/cli/commands/pipeline.ts | 135 +++-- src/cli/commands/spawn-command.test.ts | 65 +++ src/cli/commands/spawn.ts | 47 +- src/cli/program.ts | 3 + src/providers/spawn-options.ts | 3 +- src/sdk/spawn.test.ts | 25 + src/sdk/spawn.ts | 10 +- src/sdk/types.ts | 9 +- 54 files changed, 4591 insertions(+), 133 deletions(-) delete mode 100644 docs/plans/agent-harness.md.lock rename docs/plans/{ => archive}/braintrust-integration.md (98%) create mode 100644 docs/plans/braintrust-integration.md.lock create mode 100644 docs/plans/qa/braintrust-integration.md create mode 100644 packages/braintrust/README.md create mode 100644 packages/braintrust/package.json create mode 100644 packages/braintrust/src/adapters/experiment.test.ts create mode 100644 packages/braintrust/src/adapters/experiment.ts create mode 100644 packages/braintrust/src/adapters/pipeline.test.ts create mode 100644 packages/braintrust/src/adapters/pipeline.ts create mode 100644 packages/braintrust/src/adapters/spawn.test.ts create mode 100644 packages/braintrust/src/adapters/spawn.ts create mode 100644 packages/braintrust/src/adapters/superintendent.test.ts create mode 100644 packages/braintrust/src/adapters/superintendent.ts create mode 100644 packages/braintrust/src/bootstrap.test.ts create mode 100644 packages/braintrust/src/braintrust-sdk.d.ts create mode 100644 packages/braintrust/src/client.test.ts create mode 100644 packages/braintrust/src/client.ts create mode 100644 packages/braintrust/src/index.ts create mode 100644 packages/braintrust/src/integration.test.ts create mode 100644 packages/braintrust/src/redact.test.ts create mode 100644 packages/braintrust/src/redact.ts create mode 100644 packages/braintrust/src/row-builder.test.ts create mode 100644 packages/braintrust/src/row-builder.ts create mode 100644 packages/braintrust/src/span-builder.test.ts create mode 100644 packages/braintrust/src/span-builder.ts create mode 100644 packages/braintrust/src/trace-run.test.ts create mode 100644 packages/braintrust/src/trace-run.ts create mode 100644 packages/braintrust/tsconfig.json create mode 100644 packages/poe-code-config/src/integrations-loader.test.ts create mode 100644 packages/poe-code-config/src/integrations-loader.ts create mode 100644 packages/poe-code-config/src/merge-callbacks.test.ts create mode 100644 packages/poe-code-config/src/merge-callbacks.ts create mode 100644 src/cli/commands/braintrust-command.test.ts create mode 100644 src/cli/commands/braintrust.ts diff --git a/docs/plans/agent-harness.md.lock b/docs/plans/agent-harness.md.lock deleted file mode 100644 index 012e967879..0000000000 --- a/docs/plans/agent-harness.md.lock +++ /dev/null @@ -1 +0,0 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T05:40:30.603Z"} \ No newline at end of file diff --git a/docs/plans/braintrust-integration.md b/docs/plans/archive/braintrust-integration.md similarity index 98% rename from docs/plans/braintrust-integration.md rename to docs/plans/archive/braintrust-integration.md index c2688ca849..52366a05e6 100644 --- a/docs/plans/braintrust-integration.md +++ b/docs/plans/archive/braintrust-integration.md @@ -26,7 +26,7 @@ tasks: — that already lives in the config layer. status: - implement: open + implement: done - id: create-braintrust-package title: Create @poe-code/braintrust workspace package skeleton @@ -52,7 +52,7 @@ tasks: Do not write any feature code yet. status: - implement: open + implement: done - id: impl-redact title: Implement redact() @@ -77,7 +77,7 @@ tasks: leaves are preserved. No filesystem touched. status: - implement: open + implement: done - id: impl-client title: Implement BraintrustClient wrapper @@ -119,7 +119,7 @@ tasks: first use, caching, flush timeout, error recording, status output. status: - implement: open + implement: done - id: impl-trace-run title: Implement traceRun() @@ -152,7 +152,7 @@ tasks: span name, type, surface tag, and error fallback path. status: - implement: open + implement: done - id: impl-span-builder title: Implement logSpawnSession() @@ -194,7 +194,7 @@ tasks: land in `metrics` under canonical keys. status: - implement: open + implement: done - id: impl-row-builder title: Implement orchestrator span/row helpers @@ -252,7 +252,7 @@ tasks: span.log for each surface. status: - implement: open + implement: done - id: impl-spawn-adapter title: Implement spawn AcpMiddleware adapter @@ -280,7 +280,7 @@ tasks: then re-throws); SDK throws inside log (swallowed via client). status: - implement: open + implement: done - id: impl-orchestrator-adapters title: Implement pipeline, experiment, and superintendent callback adapters @@ -321,7 +321,7 @@ tasks: callback the surface exposes. status: - implement: open + implement: done - id: impl-merge-callbacks title: Implement mergeCallbacks helpers (CLI side) @@ -357,7 +357,7 @@ tasks: swallowed, asymmetric (only-user / only-added) cases. status: - implement: open + implement: done - id: impl-bootstrap title: Implement @poe-code/braintrust bootstrap() @@ -405,11 +405,12 @@ tasks: with all four callback fields populated. status: - implement: open - test: open + implement: done + test: done - id: wire-cli-integrations - title: Wire loadIntegrations into pipeline / experiment / superintendent / spawn CLI entries + title: Wire loadIntegrations into pipeline / experiment / superintendent / spawn + CLI entries prompt: | In each of these CLI entry points: packages/pipeline/src/run/pipeline.ts (or its CLI wrapper) @@ -457,8 +458,8 @@ tasks: "@poe-code/braintrust"). status: - implement: open - test: open + implement: done + test: done - id: impl-status-subcommand title: Add `poe-code braintrust status` subcommand @@ -487,8 +488,8 @@ tasks: use; mock @poe-code/braintrust where needed. status: - implement: open - test: open + implement: done + test: done - id: integration-test-subagent-tree title: End-to-end subagent tree test against mocked SDK @@ -524,7 +525,7 @@ tasks: if any filesystem reads are required. status: - implement: open + implement: done - id: write-qa-plan title: Write QA markdown plan @@ -567,7 +568,7 @@ tasks: agent. status: - implement: open + implement: done - id: write-package-readme title: Write packages/braintrust/README.md @@ -592,7 +593,7 @@ tasks: Do not edit the root README. status: - implement: open + implement: done --- ## Context diff --git a/docs/plans/braintrust-integration.md.lock b/docs/plans/braintrust-integration.md.lock new file mode 100644 index 0000000000..47cfe31803 --- /dev/null +++ b/docs/plans/braintrust-integration.md.lock @@ -0,0 +1 @@ +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T06:32:27.846Z"} \ No newline at end of file diff --git a/docs/plans/qa/braintrust-integration.md b/docs/plans/qa/braintrust-integration.md new file mode 100644 index 0000000000..9b35a7c437 --- /dev/null +++ b/docs/plans/qa/braintrust-integration.md @@ -0,0 +1,88 @@ +# Braintrust Integration QA + +Execute this checklist against a real Braintrust workspace from a test checkout of `poe-code`. + +1. [ ] Install the Braintrust SDK in the test workspace. + ```sh + npm i braintrust + ``` + +2. [ ] Set a real Braintrust API key in the shell. + ```sh + export BRAINTRUST_API_KEY=... + ``` + +3. [ ] Add this config fragment to `poe-code.config.json`. + ```json + { + "integrations": { + "braintrust": { + "enabled": true, + "apiKey": "${BRAINTRUST_API_KEY}", + "project": "poe-code-qa" + } + } + } + ``` + +4. [ ] Run a spawn command and verify spawn tracing. + ```sh + npm run dev -- spawn --agent claude-code --prompt "say hi" + ``` + Verify a single agent span appears in the Braintrust project's logs view, with tool-call children nested under it. + +5. [ ] Run a pipeline and verify pipeline tracing. + ```sh + npm run dev -- pipeline run + ``` + Verify a root pipeline span appears with one child span per step. Verify each step contains a subagent span and tool calls. Verify token usage appears as numeric metrics in sortable columns, not as text in metadata. + +6. [ ] Run an experiment and verify experiment tracing. + ```sh + npm run dev -- experiment run + ``` + Verify one root span appears per run, with one iteration child span each. Verify the Braintrust experiments view includes a row per iteration, including discarded iterations with `kept=false`. + +7. [ ] Run a superintendent plan and verify superintendent tracing. + ```sh + npm run dev -- superintendent run + ``` + Verify the span hierarchy is root -> round -> role -> agent -> tool. + +8. [ ] Verify enabled-but-unconfigured bootstrap failure. + Unset the API key while leaving `integrations.braintrust.enabled` as `true`. + ```sh + unset BRAINTRUST_API_KEY + npm run dev -- spawn --agent claude-code --prompt "say hi" + ``` + Expect the bootstrap error to include `missing apiKey`. + +9. [ ] Verify missing SDK guidance. + Remove or hide the `braintrust` package while leaving `integrations.braintrust.enabled` as `true`. + ```sh + npm uninstall braintrust + npm run dev -- spawn --agent claude-code --prompt "say hi" + ``` + Expect the error message to include `Run: npm i braintrust`. + +10. [ ] Verify disabled mode emits no Braintrust traffic. + Set `integrations.braintrust.enabled` to `false` and set `apiUrl` to an unreachable host. + ```json + { + "integrations": { + "braintrust": { + "enabled": false, + "apiKey": "${BRAINTRUST_API_KEY}", + "apiUrl": "http://127.0.0.1:9", + "project": "poe-code-qa" + } + } + } + ``` + Run a representative command and verify it completes without attempting Braintrust traffic. + +11. [ ] Verify Braintrust status output in all supported states. + ```sh + poe-code braintrust status + ``` + Run the status command with Braintrust disabled, enabled but unconfigured, and enabled healthy. Verify each state prints the expected status output. diff --git a/package-lock.json b/package-lock.json index 411db9e4f7..9d02d148d4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -54,6 +54,7 @@ "@poe-code/agent-script": "*", "@poe-code/agent-skill-config": "*", "@poe-code/agent-spawn": "*", + "@poe-code/braintrust": "*", "@poe-code/cached-resource": "*", "@poe-code/config-extends": "*", "@poe-code/config-mutations": "*", @@ -1711,6 +1712,10 @@ "resolved": "packages/agent-spawn", "link": true }, + "node_modules/@poe-code/braintrust": { + "resolved": "packages/braintrust", + "link": true + }, "node_modules/@poe-code/cached-resource": { "resolved": "packages/cached-resource", "link": true @@ -7333,6 +7338,28 @@ "packages/auth-store": { "version": "0.0.1" }, + "packages/braintrust": { + "name": "@poe-code/braintrust", + "version": "0.0.1", + "dependencies": { + "@poe-code/agent-spawn": "*", + "@poe-code/experiment-loop": "*", + "@poe-code/pipeline": "*", + "@poe-code/poe-code-config": "*", + "@poe-code/superintendent": "*" + }, + "devDependencies": { + "vitest": "^4.0.18" + }, + "peerDependencies": { + "braintrust": "*" + }, + "peerDependenciesMeta": { + "braintrust": { + "optional": true + } + } + }, "packages/cached-resource": { "name": "@poe-code/cached-resource", "version": "0.0.1", diff --git a/package.json b/package.json index 0d25ec4bf1..49541499e4 100644 --- a/package.json +++ b/package.json @@ -134,6 +134,7 @@ "@poe-code/agent-script": "*", "@poe-code/agent-skill-config": "*", "@poe-code/agent-spawn": "*", + "@poe-code/braintrust": "*", "@poe-code/cached-resource": "*", "@poe-code/config-extends": "*", "@poe-code/config-mutations": "*", diff --git a/packages/braintrust/README.md b/packages/braintrust/README.md new file mode 100644 index 0000000000..93326b97bb --- /dev/null +++ b/packages/braintrust/README.md @@ -0,0 +1,107 @@ +# @poe-code/braintrust + +Optional Braintrust observability for poe-code's agent-running surfaces: standalone spawn, pipeline, superintendent, and experiment-loop. When enabled, it wires Braintrust spans and experiment rows into the existing runtimes without changing run semantics; Braintrust SDK failures are recorded in integration status and the poe-code command keeps running. + +## Setup + +`braintrust` is an optional peer dependency. Install it in the workspace or project that runs poe-code: + +```sh +npm i braintrust +``` + +## Configuration + +Configure the integration under `integrations.braintrust` in poe-code config: + +```json +{ + "integrations": { + "braintrust": { + "enabled": true, + "apiKey": "${BRAINTRUST_API_KEY}", + "project": "poe-code", + "apiUrl": "https://api.braintrust.dev" + } + } +} +``` + +Keys: + +| Key | Type | Meaning | +| --- | --- | --- | +| `enabled` | `boolean` | Enables or disables Braintrust integration. Defaults to `false`. When not `true`, the Braintrust package is not loaded. | +| `apiKey` | `string` | Braintrust API key. Required when `enabled` is `true`; commonly supplied through config interpolation as `${BRAINTRUST_API_KEY}`. | +| `project` | `string` | Braintrust project name used for logs and experiment rows. Required when `enabled` is `true`. | +| `apiUrl` | `string` | Optional Braintrust API URL override for non-default deployments or proxies. | + +## Environment Variables + +| Variable | Meaning | +| --- | --- | +| `BRAINTRUST_API_KEY` | Braintrust API key. This package does not read the environment directly; use config interpolation, for example `"apiKey": "${BRAINTRUST_API_KEY}"`. | + +## What Lands In Braintrust + +All surfaces use `task` spans for orchestrator, step, role, agent, and iteration work. ACP tool calls use `tool` spans. Token usage and durations are logged as numeric metrics where available: `prompt_tokens`, `completion_tokens`, `tokens`, `prompt_cached_tokens`, `prompt_cache_creation_tokens`, and `durationMs`. + +Pipeline runs create one root run span, one child span per pipeline step, and nested agent/tool spans for spawned work: + +```text +pipeline: +├── step:: +│ └── agent:: +│ ├── tool_call: +│ └── tool_call: +└── step:: + └── agent:: + └── tool_call: +``` + +Superintendent runs create a root run span with role spans for each loop participant. Spawned role work appears below the role span: + +```text +superintendent: +├── role:builder +│ └── agent:: +│ └── tool_call: +├── role:inspector +├── role:superintendent +└── role:owner +``` + +Experiment-loop runs create a root run span and Braintrust experiment rows for each iteration: + +```text +experiment: +└── iteration: + └── agent:: + └── tool_call: +``` + +Standalone spawn creates a root spawn trace with the agent span and any ACP tool calls: + +```text +spawn: +└── agent:: + ├── tool_call: + └── tool_call: +``` + +## Failure Modes + +- Missing peer dependency: when `enabled` is `true` but `braintrust` is not installed, bootstrap fails with `Braintrust integration is enabled but the 'braintrust' package is not installed. Run: npm i braintrust`. +- Missing `apiKey`: when `enabled` is `true` and `apiKey` is empty or absent, bootstrap fails with `Braintrust integration is enabled but apiKey is missing`. +- Missing `project`: when `enabled` is `true` and `project` is empty or absent, bootstrap fails with `Braintrust integration is enabled but project is missing`. +- Network or SDK errors: SDK initialization, logging, and flush failures are recorded in integration status and swallowed so the orchestrator can continue. + +## Status + +Use the CLI status command to inspect the resolved integration state: + +```sh +poe-code braintrust status +``` + +It reports disabled configuration, missing fields, missing peer dependency, or the enabled project with the latest recorded Braintrust error count. diff --git a/packages/braintrust/package.json b/packages/braintrust/package.json new file mode 100644 index 0000000000..161739f383 --- /dev/null +++ b/packages/braintrust/package.json @@ -0,0 +1,40 @@ +{ + "name": "@poe-code/braintrust", + "version": "0.0.1", + "private": true, + "type": "module", + "main": "dist/index.js", + "types": "dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.js" + } + }, + "scripts": { + "build": "tsc", + "test": "cd ../.. && vitest run packages/braintrust/src", + "test:unit": "cd ../.. && vitest run packages/braintrust/src" + }, + "files": [ + "dist" + ], + "dependencies": { + "@poe-code/agent-spawn": "*", + "@poe-code/experiment-loop": "*", + "@poe-code/pipeline": "*", + "@poe-code/poe-code-config": "*", + "@poe-code/superintendent": "*" + }, + "peerDependencies": { + "braintrust": "*" + }, + "peerDependenciesMeta": { + "braintrust": { + "optional": true + } + }, + "devDependencies": { + "vitest": "^4.0.18" + } +} diff --git a/packages/braintrust/src/adapters/experiment.test.ts b/packages/braintrust/src/adapters/experiment.test.ts new file mode 100644 index 0000000000..8a8bce3406 --- /dev/null +++ b/packages/braintrust/src/adapters/experiment.test.ts @@ -0,0 +1,108 @@ +import type { EvalResult, ExperimentRunOptions, JournalEntry, MetricDef } from "@poe-code/experiment-loop"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import type { BraintrustClient } from "../client.js"; +import { makeExperimentIterationState } from "../row-builder.js"; +import { createExperimentCallbacks } from "./experiment.js"; + +vi.mock("../row-builder.js", () => ({ + makeExperimentIterationState: vi.fn(), +})); + +const mockMakeExperimentIterationState = vi.mocked(makeExperimentIterationState); + +describe("createExperimentCallbacks", () => { + beforeEach(() => { + mockMakeExperimentIterationState.mockReset(); + }); + + it("creates experiment iteration state with the client and experiment name", () => { + const state = createIterationState(); + const client = createMockClient(); + mockMakeExperimentIterationState.mockReturnValue(state); + + createExperimentCallbacks(client, "adapter-benchmark"); + + expect(mockMakeExperimentIterationState).toHaveBeenCalledWith(client, "adapter-benchmark"); + }); + + it("wires every experiment callback surface into the iteration state", async () => { + const state = createIterationState(); + const client = createMockClient(); + mockMakeExperimentIterationState.mockReturnValue(state); + const callbacks = createExperimentCallbacks(client, "adapter-benchmark"); + const metric = { + name: "tests", + script: "npm test", + direction: "maximize", + } satisfies MetricDef; + const metricResult = { + score: 17, + passed: true, + output: "17 tests passed", + } satisfies EvalResult; + const entry = { + commit: "abc123", + status: "keep", + scores: { + tests: 17, + }, + output: "17 tests passed", + agentOutput: "Implemented callback adapters", + durationMs: 123, + timestamp: "2026-05-04T12:00:00.000Z", + } satisfies JournalEntry; + + callbacks.onExperimentStart(2, "codex"); + callbacks.onBaselineCollected({ tests: 12 }); + callbacks.onMetricResult(metric, metricResult); + callbacks.onCommit("abc123"); + callbacks.onReset("base123"); + callbacks.onExperimentComplete(2, entry); + + await vi.waitFor(() => { + expect(state.complete).toHaveBeenCalledWith(2, entry); + }); + expect(state.start).toHaveBeenCalledWith(2, "codex"); + expect(state.baseline).toHaveBeenCalledWith({ tests: 12 }); + expect(state.metric).toHaveBeenCalledWith("tests", 17); + expect(state.commit).toHaveBeenCalledWith("abc123"); + expect(state.reset).toHaveBeenCalledWith("base123"); + }); +}); + +function createIterationState(): ReturnType { + return { + start: vi.fn(async () => undefined), + baseline: vi.fn(), + metric: vi.fn(), + commit: vi.fn(), + reset: vi.fn(), + complete: vi.fn(async () => undefined), + }; +} + +function createMockClient(): BraintrustClient { + return { + getSdk: vi.fn(), + getRootLogger: vi.fn(), + getExperiment: vi.fn(), + flush: vi.fn(), + recordError: vi.fn(), + status: vi.fn(() => ({ + lastError: null, + errorCount: 0, + project: "project", + })), + }; +} + +type ignoredExperimentCallbackFields = Pick< + ExperimentRunOptions, + | "onExperimentStart" + | "onBaselineCollected" + | "onMetricResult" + | "onCommit" + | "onReset" + | "onExperimentComplete" +>; diff --git a/packages/braintrust/src/adapters/experiment.ts b/packages/braintrust/src/adapters/experiment.ts new file mode 100644 index 0000000000..20a05d9d50 --- /dev/null +++ b/packages/braintrust/src/adapters/experiment.ts @@ -0,0 +1,44 @@ +import type { ExperimentRunOptions } from "@poe-code/experiment-loop"; + +import type { BraintrustClient } from "../client.js"; +import { makeExperimentIterationState } from "../row-builder.js"; + +export type ExperimentCallbackFields = Pick< + ExperimentRunOptions, + | "onExperimentStart" + | "onBaselineCollected" + | "onMetricResult" + | "onCommit" + | "onReset" + | "onExperimentComplete" +>; + +export function createExperimentCallbacks( + client: BraintrustClient, + experimentName: string, +): ExperimentCallbackFields { + const state = makeExperimentIterationState(client, experimentName); + + return { + onExperimentStart(index, agent) { + void state.start(index, agent); + }, + onBaselineCollected(baseline) { + state.baseline(baseline); + }, + onMetricResult(metric, result) { + if (result.score !== null) { + state.metric(metric.name, result.score); + } + }, + onCommit(commitHash) { + state.commit(commitHash); + }, + onReset(targetHash) { + state.reset(targetHash); + }, + onExperimentComplete(index, entry) { + void state.complete(index, entry); + }, + }; +} diff --git a/packages/braintrust/src/adapters/pipeline.test.ts b/packages/braintrust/src/adapters/pipeline.test.ts new file mode 100644 index 0000000000..2b68dde47d --- /dev/null +++ b/packages/braintrust/src/adapters/pipeline.test.ts @@ -0,0 +1,102 @@ +import type { PipelineLockStatus, PipelineRunOptions, PlanSummary, TaskCompletion, TaskProgress } from "@poe-code/pipeline"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import type { BraintrustClient } from "../client.js"; +import { makePipelineRowState } from "../row-builder.js"; +import { createPipelineCallbacks } from "./pipeline.js"; + +vi.mock("../row-builder.js", () => ({ + makePipelineRowState: vi.fn(), +})); + +const mockMakePipelineRowState = vi.mocked(makePipelineRowState); + +describe("createPipelineCallbacks", () => { + beforeEach(() => { + mockMakePipelineRowState.mockReset(); + }); + + it("creates pipeline row state with the client", () => { + const rowState = createRowState(); + const client = createMockClient(); + mockMakePipelineRowState.mockReturnValue(rowState); + + createPipelineCallbacks(client); + + expect(mockMakePipelineRowState).toHaveBeenCalledWith(client); + }); + + it("wires every pipeline callback surface", () => { + const rowState = createRowState(); + const client = createMockClient(); + mockMakePipelineRowState.mockReturnValue(rowState); + const callbacks = createPipelineCallbacks(client); + const summary = { + planPath: "/repo/docs/plans/feature.md", + done: 1, + failed: 0, + open: 2, + total: 3, + } satisfies PlanSummary; + const started = { + taskId: "task-1", + taskTitle: "Build adapter", + stepName: "builder", + taskIndex: 1, + totalTasks: 3, + stepIndex: 0, + totalSteps: 2, + } satisfies TaskProgress; + const completed = { + ...started, + durationMs: 42, + success: true, + } satisfies TaskCompletion; + const lockStatus = { + state: "acquired", + message: "locked", + } satisfies PipelineLockStatus; + + expect(callbacks.onPlanResolved).toBeTypeOf("function"); + expect(callbacks.onTaskStart).toBeTypeOf("function"); + expect(callbacks.onTaskComplete).toBeTypeOf("function"); + expect(callbacks.onLockStatusChange).toBeTypeOf("function"); + + callbacks.onPlanResolved(summary); + callbacks.onTaskStart(started); + callbacks.onTaskComplete(completed); + callbacks.onLockStatusChange(lockStatus); + + expect(rowState.start).toHaveBeenCalledWith(started); + expect(rowState.complete).toHaveBeenCalledWith(completed); + expect(rowState.start).toHaveBeenCalledTimes(1); + expect(rowState.complete).toHaveBeenCalledTimes(1); + }); +}); + +function createRowState(): ReturnType { + return { + start: vi.fn(), + complete: vi.fn(), + }; +} + +function createMockClient(): BraintrustClient { + return { + getSdk: vi.fn(), + getRootLogger: vi.fn(), + getExperiment: vi.fn(), + flush: vi.fn(), + recordError: vi.fn(), + status: vi.fn(() => ({ + lastError: null, + errorCount: 0, + project: "project", + })), + }; +} + +type ignoredPipelineCallbackFields = Pick< + PipelineRunOptions, + "onPlanResolved" | "onTaskStart" | "onTaskComplete" | "onLockStatusChange" +>; diff --git a/packages/braintrust/src/adapters/pipeline.ts b/packages/braintrust/src/adapters/pipeline.ts new file mode 100644 index 0000000000..5d633a4ddf --- /dev/null +++ b/packages/braintrust/src/adapters/pipeline.ts @@ -0,0 +1,30 @@ +import type { PipelineRunOptions } from "@poe-code/pipeline"; + +import type { BraintrustClient } from "../client.js"; +import { makePipelineRowState } from "../row-builder.js"; + +export type PipelineCallbackFields = Pick< + PipelineRunOptions, + "onPlanResolved" | "onTaskStart" | "onTaskComplete" | "onLockStatusChange" +>; + +export function createPipelineCallbacks( + client: BraintrustClient, +): PipelineCallbackFields { + const state = makePipelineRowState(client); + + return { + onPlanResolved(summary) { + void summary; + }, + onTaskStart(progress) { + state.start(progress); + }, + onTaskComplete(progress) { + state.complete(progress); + }, + onLockStatusChange(status) { + void status; + }, + }; +} diff --git a/packages/braintrust/src/adapters/spawn.test.ts b/packages/braintrust/src/adapters/spawn.test.ts new file mode 100644 index 0000000000..e2a23a1ae5 --- /dev/null +++ b/packages/braintrust/src/adapters/spawn.test.ts @@ -0,0 +1,107 @@ +import type { AcpSpawnContext as SpawnContext } from "@poe-code/agent-spawn"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import type { BraintrustClient } from "../client.js"; +import { createSpawnMiddleware } from "./spawn.js"; +import { logSpawnSession } from "../span-builder.js"; + +vi.mock("../span-builder.js", () => ({ + logSpawnSession: vi.fn(), +})); + +const mockLogSpawnSession = vi.mocked(logSpawnSession); + +describe("createSpawnMiddleware", () => { + beforeEach(() => { + mockLogSpawnSession.mockReset(); + }); + + it("runs next before logging the populated spawn context", async () => { + const client = createMockClient(); + const ctx = createSpawnContext(); + const middleware = createSpawnMiddleware(client); + const next = vi.fn(async () => { + ctx.events.push({ event: "agent_message", text: "done" } as never); + ctx.usage.inputTokens = 4; + ctx.sessionResult = { + output: "done", + messages: ["done"], + toolCalls: [], + }; + }); + + await middleware(ctx, next); + + expect(next).toHaveBeenCalledTimes(1); + expect(mockLogSpawnSession).toHaveBeenCalledTimes(1); + expect(mockLogSpawnSession).toHaveBeenCalledWith(client, ctx); + expect(ctx).toMatchObject({ + events: [{ event: "agent_message", text: "done" }], + usage: { inputTokens: 4 }, + sessionResult: { output: "done" }, + }); + }); + + it("logs aborted metadata when next throws and re-throws the original error", async () => { + const client = createMockClient(); + const ctx = createSpawnContext(); + const middleware = createSpawnMiddleware(client); + const error = new Error("spawn failed"); + const next = vi.fn(async () => { + ctx.events.push({ event: "error", message: "failed" } as never); + throw error; + }); + + await expect(middleware(ctx, next)).rejects.toBe(error); + + expect(mockLogSpawnSession).toHaveBeenCalledTimes(1); + expect(mockLogSpawnSession).toHaveBeenCalledWith(client, { + ...ctx, + metadata: { + aborted: true, + }, + }); + }); + + it("does not fail when logSpawnSession swallows SDK errors through the client", async () => { + const client = createMockClient(); + const ctx = createSpawnContext(); + const middleware = createSpawnMiddleware(client); + const sdkError = new Error("sdk unavailable"); + mockLogSpawnSession.mockImplementation(async (targetClient) => { + targetClient.recordError(sdkError, "log spawn session"); + }); + + await expect(middleware(ctx, async () => undefined)).resolves.toBeUndefined(); + + expect(client.recordError).toHaveBeenCalledWith(sdkError, "log spawn session"); + expect(mockLogSpawnSession).toHaveBeenCalledWith(client, ctx); + }); +}); + +function createSpawnContext(): SpawnContext { + return { + sessionId: "session-1", + agent: "codex", + events: [], + usage: { + inputTokens: 0, + outputTokens: 0, + }, + }; +} + +function createMockClient(): BraintrustClient { + return { + getSdk: vi.fn(), + getRootLogger: vi.fn(), + getExperiment: vi.fn(), + flush: vi.fn(), + recordError: vi.fn(), + status: vi.fn(() => ({ + lastError: null, + errorCount: 0, + project: "project", + })), + }; +} diff --git a/packages/braintrust/src/adapters/spawn.ts b/packages/braintrust/src/adapters/spawn.ts new file mode 100644 index 0000000000..4700fa73c2 --- /dev/null +++ b/packages/braintrust/src/adapters/spawn.ts @@ -0,0 +1,27 @@ +import type { AcpMiddleware, AcpSpawnContext as SpawnContext } from "@poe-code/agent-spawn"; + +import type { BraintrustClient } from "../client.js"; +import { logSpawnSession } from "../span-builder.js"; + +type SpawnContextWithMetadata = SpawnContext & { + metadata?: Record; +}; + +export function createSpawnMiddleware( + client: BraintrustClient, +): AcpMiddleware { + return async (ctx, next) => { + try { + await next(); + } catch (err) { + const metadataCtx = ctx as SpawnContextWithMetadata; + metadataCtx.metadata = { + ...metadataCtx.metadata, + aborted: true, + }; + throw err; + } finally { + await logSpawnSession(client, ctx); + } + }; +} diff --git a/packages/braintrust/src/adapters/superintendent.test.ts b/packages/braintrust/src/adapters/superintendent.test.ts new file mode 100644 index 0000000000..3d4b7e8169 --- /dev/null +++ b/packages/braintrust/src/adapters/superintendent.test.ts @@ -0,0 +1,125 @@ +import type { LoopCallbacks } from "@poe-code/superintendent"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import type { BraintrustClient } from "../client.js"; +import { logSuperintendentRole } from "../row-builder.js"; +import { createSuperintendentCallbacks } from "./superintendent.js"; + +const mockBraintrust = vi.hoisted(() => ({ + currentSpan: vi.fn(), +})); + +vi.mock("braintrust", () => ({ + currentSpan: mockBraintrust.currentSpan, +})); + +vi.mock("../row-builder.js", () => ({ + logSuperintendentRole: vi.fn(), +})); + +const mockLogSuperintendentRole = vi.mocked(logSuperintendentRole); + +describe("createSuperintendentCallbacks", () => { + beforeEach(() => { + mockBraintrust.currentSpan.mockReset(); + mockLogSuperintendentRole.mockReset(); + }); + + it("wires every complete callback to log the matching superintendent role", async () => { + const client = createMockClient(); + const callbacks = createSuperintendentCallbacks(client); + const builderResult = { output: "built" }; + const inspectorResult = { output: "inspected" }; + const superintendentResult = { output: "coordinated" }; + const ownerResult = { output: "approved" }; + + callbacks.onBuilderComplete(builderResult as never); + callbacks.onInspectorComplete(inspectorResult as never); + callbacks.onSuperintendentComplete?.(superintendentResult as never); + callbacks.onOwnerComplete?.(ownerResult as never); + + await vi.waitFor(() => { + expect(mockLogSuperintendentRole).toHaveBeenCalledTimes(4); + }); + expect(mockLogSuperintendentRole).toHaveBeenNthCalledWith(1, client, "builder", builderResult); + expect(mockLogSuperintendentRole).toHaveBeenNthCalledWith(2, client, "inspector", inspectorResult); + expect(mockLogSuperintendentRole).toHaveBeenNthCalledWith(3, client, "superintendent", superintendentResult); + expect(mockLogSuperintendentRole).toHaveBeenNthCalledWith(4, client, "owner", ownerResult); + }); + + it("logs builder failures as failed Braintrust spans", async () => { + const failureSpan = createMockSpan(); + mockBraintrust.currentSpan.mockReturnValue({ + startSpan: vi.fn(() => failureSpan), + }); + const client = createMockClient(); + const callbacks = createSuperintendentCallbacks(client); + const error = new Error("builder failed"); + + callbacks.onBuilderFailed(error); + + await vi.waitFor(() => { + expect(failureSpan.log).toHaveBeenCalledWith({ + metadata: { + role: "builder", + error: "builder failed", + }, + scores: { + passed: 0, + }, + }); + }); + expect(failureSpan.end).toHaveBeenCalledTimes(1); + }); + + it("logs inspector failures as failed Braintrust spans with the inspector name", async () => { + const failureSpan = createMockSpan(); + mockBraintrust.currentSpan.mockReturnValue({ + startSpan: vi.fn(() => failureSpan), + }); + const client = createMockClient(); + const callbacks = createSuperintendentCallbacks(client); + const error = new Error("inspector failed"); + + callbacks.onInspectorFailed("docs", error); + + await vi.waitFor(() => { + expect(failureSpan.log).toHaveBeenCalledWith({ + metadata: { + role: "inspector", + name: "docs", + error: "inspector failed", + }, + scores: { + passed: 0, + }, + }); + }); + expect(failureSpan.end).toHaveBeenCalledTimes(1); + }); +}); + +function createMockSpan() { + return { + startSpan: vi.fn(), + log: vi.fn(), + end: vi.fn(), + }; +} + +function createMockClient(): BraintrustClient { + return { + getSdk: vi.fn(), + getRootLogger: vi.fn(), + getExperiment: vi.fn(), + flush: vi.fn(), + recordError: vi.fn(), + status: vi.fn(() => ({ + lastError: null, + errorCount: 0, + project: "project", + })), + }; +} + +type ignoredLoopCallbacks = LoopCallbacks; diff --git a/packages/braintrust/src/adapters/superintendent.ts b/packages/braintrust/src/adapters/superintendent.ts new file mode 100644 index 0000000000..e461c938e8 --- /dev/null +++ b/packages/braintrust/src/adapters/superintendent.ts @@ -0,0 +1,82 @@ +import type { LoopCallbacks } from "@poe-code/superintendent"; + +import type { BraintrustClient } from "../client.js"; +import { logSuperintendentRole } from "../row-builder.js"; + +type BraintrustSpan = { + log(event: { + metadata?: Record; + scores?: Record; + }): void; + end(): void; +}; + +type BraintrustSpanParent = { + startSpan(args: { name: string; type: "task" | "tool" }): BraintrustSpan; +}; + +export function createSuperintendentCallbacks( + client: BraintrustClient, +): LoopCallbacks { + return { + onBuilderComplete(result) { + void logSuperintendentRole(client, "builder", result); + }, + onBuilderFailed(error) { + void logFailedRole(client, "builder", error); + }, + onInspectorComplete(result) { + void logSuperintendentRole(client, "inspector", result); + }, + onInspectorFailed(name, error) { + void logFailedRole(client, "inspector", error, name); + }, + onSuperintendentComplete(result) { + void logSuperintendentRole(client, "superintendent", result); + }, + onOwnerComplete(result) { + void logSuperintendentRole(client, "owner", result); + }, + }; +} + +async function logFailedRole( + client: BraintrustClient, + role: "builder" | "inspector", + error: Error, + name?: string, +): Promise { + try { + const { currentSpan } = await import("braintrust"); + const span = asSpanParent(currentSpan()).startSpan({ + name: name === undefined ? `role:${role}:failed` : `role:${role}:${name}:failed`, + type: "task", + }); + + try { + span.log({ + metadata: { + role, + ...(name === undefined ? {} : { name }), + error: error.message, + }, + scores: { + passed: 0, + }, + }); + } finally { + span.end(); + } + } catch (err) { + client.recordError(err, `superintendent ${role} failed`); + } +} + +function asSpanParent(value: unknown): BraintrustSpanParent { + const span = value as Partial | undefined; + if (span === undefined || typeof span.startSpan !== "function") { + throw new Error("Braintrust current span unavailable"); + } + + return span as BraintrustSpanParent; +} diff --git a/packages/braintrust/src/bootstrap.test.ts b/packages/braintrust/src/bootstrap.test.ts new file mode 100644 index 0000000000..af055370ed --- /dev/null +++ b/packages/braintrust/src/bootstrap.test.ts @@ -0,0 +1,181 @@ +import type { + BraintrustIntegrationConfig, + ConfigDocument, +} from "@poe-code/poe-code-config"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const mockBraintrust = vi.hoisted(() => ({ + importCount: 0, + mode: "healthy" as "healthy" | "missing", + initLogger: vi.fn(), + initExperiment: vi.fn(), + flush: vi.fn(), + traced: vi.fn(), + currentSpan: vi.fn(), +})); + +vi.mock("braintrust", () => { + mockBraintrust.importCount += 1; + + if (mockBraintrust.mode === "missing") { + const err = new Error("Cannot find package 'braintrust'") as Error & { + code: string; + }; + err.code = "ERR_MODULE_NOT_FOUND"; + throw err; + } + + return { + initLogger: mockBraintrust.initLogger, + initExperiment: mockBraintrust.initExperiment, + flush: mockBraintrust.flush, + traced: mockBraintrust.traced, + currentSpan: mockBraintrust.currentSpan, + }; +}); + +describe("bootstrap", () => { + beforeEach(() => { + vi.resetModules(); + mockBraintrust.importCount = 0; + mockBraintrust.mode = "healthy"; + mockBraintrust.initLogger.mockReset(); + mockBraintrust.initExperiment.mockReset(); + mockBraintrust.flush.mockReset(); + mockBraintrust.traced.mockReset(); + mockBraintrust.currentSpan.mockReset(); + }); + + it("returns null without importing Braintrust when integration is disabled", async () => { + const { bootstrap } = await import("./index.js"); + + await expect(bootstrap(config())).resolves.toBeNull(); + + expect(mockBraintrust.importCount).toBe(0); + }); + + it("throws a one-line apiKey message before importing Braintrust", async () => { + const { bootstrap } = await import("./index.js"); + + await expect( + bootstrap(config({ enabled: true, project: "project" })), + ).rejects.toThrow("Braintrust integration is enabled but apiKey is missing"); + expect(mockBraintrust.importCount).toBe(0); + }); + + it("throws a one-line apiKey message for empty strings before importing Braintrust", async () => { + const { bootstrap } = await import("./index.js"); + + await expect( + bootstrap(config({ enabled: true, apiKey: " ", project: "project" })), + ).rejects.toThrow("Braintrust integration is enabled but apiKey is missing"); + expect(mockBraintrust.importCount).toBe(0); + }); + + it("throws a one-line project message before importing Braintrust", async () => { + const { bootstrap } = await import("./index.js"); + + await expect( + bootstrap(config({ enabled: true, apiKey: "key" })), + ).rejects.toThrow("Braintrust integration is enabled but project is missing"); + expect(mockBraintrust.importCount).toBe(0); + }); + + it("throws a one-line project message for empty strings before importing Braintrust", async () => { + const { bootstrap } = await import("./index.js"); + + await expect( + bootstrap(config({ enabled: true, apiKey: "key", project: "" })), + ).rejects.toThrow("Braintrust integration is enabled but project is missing"); + expect(mockBraintrust.importCount).toBe(0); + }); + + it("throws the peer install message when Braintrust is missing", async () => { + mockBraintrust.mode = "missing"; + const { bootstrap } = await import("./index.js"); + + await expect( + bootstrap(config({ + enabled: true, + apiKey: "key", + project: "project", + })), + ).rejects.toThrow( + "Braintrust integration is enabled but the 'braintrust' package is not installed. Run: npm i braintrust", + ); + }); + + it("returns integrations with all callback fields populated when enabled and valid", async () => { + const { bootstrap } = await import("./index.js"); + + const integrations = await bootstrap(config({ + enabled: true, + apiKey: "key", + project: "project", + })); + + expect(integrations).not.toBeNull(); + expect(integrations?.spawnMiddleware).toEqual(expect.any(Function)); + expect(integrations?.pipelineCallbacks).toMatchObject({ + onPlanResolved: expect.any(Function), + onTaskStart: expect.any(Function), + onTaskComplete: expect.any(Function), + onLockStatusChange: expect.any(Function), + }); + expect(integrations?.experimentCallbacks).toMatchObject({ + onExperimentStart: expect.any(Function), + onBaselineCollected: expect.any(Function), + onMetricResult: expect.any(Function), + onCommit: expect.any(Function), + onReset: expect.any(Function), + onExperimentComplete: expect.any(Function), + }); + expect(integrations?.superintendentCallbacks).toMatchObject({ + onBuilderComplete: expect.any(Function), + onBuilderFailed: expect.any(Function), + onInspectorComplete: expect.any(Function), + onInspectorFailed: expect.any(Function), + onSuperintendentComplete: expect.any(Function), + onOwnerComplete: expect.any(Function), + }); + expect(integrations?.traceRun).toEqual(expect.any(Function)); + expect(integrations?.shutdown).toEqual(expect.any(Function)); + expect(mockBraintrust.importCount).toBe(1); + }); + + it("flushes the shared Braintrust client on shutdown", async () => { + const logger = {}; + mockBraintrust.initLogger.mockReturnValue(logger); + mockBraintrust.traced.mockImplementation( + async (fn: () => Promise) => fn(), + ); + mockBraintrust.flush.mockResolvedValue(undefined); + const { bootstrap } = await import("./index.js"); + + const integrations = await bootstrap(config({ + enabled: true, + apiKey: "key", + project: "project", + })); + + await integrations?.traceRun("pipeline", "smoke", async () => "ok"); + await integrations?.shutdown(); + + expect(mockBraintrust.initLogger).toHaveBeenCalledWith({ + apiKey: "key", + apiUrl: undefined, + projectName: "project", + }); + expect(mockBraintrust.flush).toHaveBeenCalledWith(logger); + }); +}); + +function config( + braintrust?: Partial, +): ConfigDocument { + return { + integrations: { + braintrust, + }, + } as ConfigDocument; +} diff --git a/packages/braintrust/src/braintrust-sdk.d.ts b/packages/braintrust/src/braintrust-sdk.d.ts new file mode 100644 index 0000000000..550b2b47c4 --- /dev/null +++ b/packages/braintrust/src/braintrust-sdk.d.ts @@ -0,0 +1,41 @@ +declare module "braintrust" { + export function initLogger(options: { + projectName: string; + apiKey: string; + apiUrl?: string; + }): unknown; + + export function initExperiment(options: { + projectName: string; + experimentName: string; + apiKey: string; + apiUrl?: string; + }): unknown; + + export function flush(target: unknown): Promise; + + export interface Span { + startSpan(args: { name: string; type: "task" | "tool" }): Span; + log(event: { + input?: unknown; + output?: unknown; + metadata?: Record; + metrics?: Record; + tags?: string[]; + }): void; + end(): void; + } + + export function currentSpan(): Span; + + export function traced( + fn: () => Promise, + args: { + name: string; + type: "task"; + event?: { + tags?: string[]; + }; + }, + ): Promise; +} diff --git a/packages/braintrust/src/client.test.ts b/packages/braintrust/src/client.test.ts new file mode 100644 index 0000000000..5f34733fb9 --- /dev/null +++ b/packages/braintrust/src/client.test.ts @@ -0,0 +1,125 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import { createClient } from "./client.js"; + +const mockBraintrust = vi.hoisted(() => ({ + importCount: 0, + initLogger: vi.fn(), + initExperiment: vi.fn(), + flush: vi.fn(), +})); + +vi.mock("braintrust", () => { + mockBraintrust.importCount += 1; + + return { + initLogger: mockBraintrust.initLogger, + initExperiment: mockBraintrust.initExperiment, + flush: mockBraintrust.flush, + }; +}); + +describe("createClient", () => { + beforeEach(() => { + vi.useRealTimers(); + mockBraintrust.importCount = 0; + mockBraintrust.initLogger.mockReset(); + mockBraintrust.initExperiment.mockReset(); + mockBraintrust.flush.mockReset(); + }); + + it("loads the Braintrust SDK lazily on first use", async () => { + mockBraintrust.initLogger.mockReturnValue({ id: "logger" }); + const client = createClient({ apiKey: "key", project: "project" }); + + expect(mockBraintrust.importCount).toBe(0); + + await client.getRootLogger(); + + expect(mockBraintrust.importCount).toBe(1); + expect(mockBraintrust.initLogger).toHaveBeenCalledTimes(1); + }); + + it("caches the root logger and experiments by name", async () => { + const logger = { id: "logger" }; + const experimentA = { id: "experiment-a" }; + const experimentB = { id: "experiment-b" }; + mockBraintrust.initLogger.mockReturnValue(logger); + mockBraintrust.initExperiment + .mockReturnValueOnce(experimentA) + .mockReturnValueOnce(experimentB); + const client = createClient({ + apiKey: "key", + apiUrl: "https://api.example.com", + project: "project", + }); + + await expect(client.getRootLogger()).resolves.toBe(logger); + await expect(client.getRootLogger()).resolves.toBe(logger); + await expect(client.getExperiment("a")).resolves.toBe(experimentA); + await expect(client.getExperiment("a")).resolves.toBe(experimentA); + await expect(client.getExperiment("b")).resolves.toBe(experimentB); + + expect(mockBraintrust.initLogger).toHaveBeenCalledTimes(1); + expect(mockBraintrust.initLogger).toHaveBeenCalledWith({ + projectName: "project", + apiKey: "key", + apiUrl: "https://api.example.com", + }); + expect(mockBraintrust.initExperiment).toHaveBeenCalledTimes(2); + expect(mockBraintrust.initExperiment).toHaveBeenNthCalledWith(1, { + projectName: "project", + experimentName: "a", + apiKey: "key", + apiUrl: "https://api.example.com", + }); + expect(mockBraintrust.initExperiment).toHaveBeenNthCalledWith(2, { + projectName: "project", + experimentName: "b", + apiKey: "key", + apiUrl: "https://api.example.com", + }); + }); + + it("flushes the root logger and cached experiments but resolves on timeout", async () => { + vi.useFakeTimers(); + const logger = { id: "logger" }; + const experimentA = { id: "experiment-a" }; + const experimentB = { id: "experiment-b" }; + mockBraintrust.initLogger.mockReturnValue(logger); + mockBraintrust.initExperiment + .mockReturnValueOnce(experimentA) + .mockReturnValueOnce(experimentB); + mockBraintrust.flush.mockReturnValue(new Promise(() => undefined)); + const client = createClient({ apiKey: "key", project: "project" }); + + await client.getRootLogger(); + await client.getExperiment("a"); + await client.getExperiment("b"); + + const flushed = client.flush(50); + await vi.advanceTimersByTimeAsync(50); + + await expect(flushed).resolves.toBeUndefined(); + expect(mockBraintrust.flush).toHaveBeenCalledTimes(3); + expect(mockBraintrust.flush).toHaveBeenNthCalledWith(1, logger); + expect(mockBraintrust.flush).toHaveBeenNthCalledWith(2, experimentA); + expect(mockBraintrust.flush).toHaveBeenNthCalledWith(3, experimentB); + }); + + it("records errors without throwing and exposes status", async () => { + mockBraintrust.initLogger.mockImplementation(() => { + throw new Error("sdk failed"); + }); + const client = createClient({ apiKey: "key", project: "project" }); + + await expect(client.getRootLogger()).resolves.toBeUndefined(); + client.recordError("plain failure", "manual"); + + expect(client.status()).toEqual({ + lastError: "manual: plain failure", + errorCount: 2, + project: "project", + }); + }); +}); diff --git a/packages/braintrust/src/client.ts b/packages/braintrust/src/client.ts new file mode 100644 index 0000000000..4712ef8316 --- /dev/null +++ b/packages/braintrust/src/client.ts @@ -0,0 +1,148 @@ +import type * as BraintrustSdk from "braintrust"; + +export interface BraintrustClient { + getSdk(): Promise; + getRootLogger(): Promise; + getExperiment(name: string): Promise; + flush(timeoutMs: number): Promise; + recordError(err: unknown, ctx: string): void; + status(): { + lastError: string | null; + errorCount: number; + project: string; + }; +} + +export function createClient(opts: { + apiKey: string; + apiUrl?: string; + project: string; +}): BraintrustClient { + let sdkPromise: Promise | undefined; + let rootLoggerPromise: Promise | undefined; + const experiments = new Map>(); + let lastError: string | null = null; + let errorCount = 0; + + const recordError = (err: unknown, ctx: string): void => { + try { + errorCount += 1; + lastError = `${ctx}: ${formatError(err)}`; + } catch { + errorCount += 1; + lastError = `${ctx}: unknown error`; + } + }; + + const loadSdk = async (): Promise => { + sdkPromise ??= import("braintrust").catch((err: unknown) => { + recordError(err, "load sdk"); + return undefined; + }); + + return sdkPromise; + }; + + const sdkOptions = () => ({ + projectName: opts.project, + apiKey: opts.apiKey, + apiUrl: opts.apiUrl, + }); + + const client: BraintrustClient = { + getSdk: loadSdk, + + async getRootLogger(): Promise { + rootLoggerPromise ??= (async () => { + try { + const sdk = await loadSdk(); + return sdk?.initLogger(sdkOptions()); + } catch (err) { + recordError(err, "init logger"); + return undefined; + } + })(); + + return rootLoggerPromise; + }, + + async getExperiment(name: string): Promise { + if (!experiments.has(name)) { + experiments.set(name, (async () => { + try { + const sdk = await loadSdk(); + return sdk?.initExperiment({ + ...sdkOptions(), + experimentName: name, + }); + } catch (err) { + recordError(err, `init experiment ${name}`); + return undefined; + } + })()); + } + + return experiments.get(name); + }, + + async flush(timeoutMs: number): Promise { + const flushAll = (async () => { + const sdk = await sdkPromise; + if (sdk === undefined) { + return; + } + + const targets = [ + await rootLoggerPromise, + ...await Promise.all(experiments.values()), + ].filter((target) => target !== undefined); + + const flushTargets = Promise.all( + targets.map((target) => sdk.flush(target)), + ).then(() => undefined); + await flushTargets; + })().catch((err: unknown) => { + recordError(err, "flush"); + }); + + try { + await Promise.race([ + flushAll, + new Promise((resolve) => { + setTimeout(resolve, timeoutMs); + }), + ]); + } catch (err) { + recordError(err, "flush"); + } + }, + + recordError, + + status() { + return { + lastError, + errorCount, + project: opts.project, + }; + }, + }; + + return client; +} + +function formatError(err: unknown): string { + if (err instanceof Error) { + return err.message; + } + + if (typeof err === "string") { + return err; + } + + try { + return JSON.stringify(err); + } catch { + return String(err); + } +} diff --git a/packages/braintrust/src/index.ts b/packages/braintrust/src/index.ts new file mode 100644 index 0000000000..3feda90a2f --- /dev/null +++ b/packages/braintrust/src/index.ts @@ -0,0 +1,108 @@ +import type { AcpMiddleware } from "@poe-code/agent-spawn"; +import type { + BraintrustIntegrationConfig, + ConfigDocument as PoeCodeConfig, +} from "@poe-code/poe-code-config"; +import type { LoopCallbacks } from "@poe-code/superintendent"; + +import { createClient } from "./client.js"; +import { + createExperimentCallbacks, + type ExperimentCallbackFields, +} from "./adapters/experiment.js"; +import { + createPipelineCallbacks, + type PipelineCallbackFields, +} from "./adapters/pipeline.js"; +import { createSpawnMiddleware } from "./adapters/spawn.js"; +import { createSuperintendentCallbacks } from "./adapters/superintendent.js"; +import { makeTraceRun, type TraceSurface } from "./trace-run.js"; + +export interface Integrations { + spawnMiddleware?: AcpMiddleware; + pipelineCallbacks?: PipelineCallbackFields; + experimentCallbacks?: ExperimentCallbackFields; + superintendentCallbacks?: LoopCallbacks; + status(): { + lastError: string | null; + errorCount: number; + project: string; + }; + traceRun( + surface: TraceSurface, + name: string, + fn: () => Promise, + ): Promise; + shutdown(): Promise; +} + +export async function bootstrap( + config: PoeCodeConfig, +): Promise { + const braintrust = config.integrations?.braintrust; + if (braintrust?.enabled !== true) { + return null; + } + + validateBraintrustConfig(braintrust); + + try { + await import("braintrust"); + } catch (err) { + if (isModuleNotFound(err)) { + throw new Error( + "Braintrust integration is enabled but the 'braintrust' package is not installed. Run: npm i braintrust", + ); + } + + throw err; + } + + const client = createClient(braintrust); + + return { + spawnMiddleware: createSpawnMiddleware(client), + pipelineCallbacks: createPipelineCallbacks(client), + experimentCallbacks: createExperimentCallbacks(client, braintrust.project), + superintendentCallbacks: createSuperintendentCallbacks(client), + status: () => client.status(), + traceRun: makeTraceRun(client), + shutdown() { + return client.flush(5000); + }, + }; +} + +function validateBraintrustConfig( + braintrust: BraintrustIntegrationConfig, +): asserts braintrust is BraintrustIntegrationConfig & { + apiKey: string; + project: string; +} { + requiredString(braintrust.apiKey, "apiKey"); + requiredString(braintrust.project, "project"); +} + +function requiredString(value: unknown, field: "apiKey" | "project"): void { + if (typeof value === "string" && value.trim() !== "") { + return; + } + + throw new Error(`Braintrust integration is enabled but ${field} is missing`); +} + +function isModuleNotFound(err: unknown): boolean { + if (typeof err !== "object" || err === null) { + return false; + } + + if ("code" in err && err.code === "ERR_MODULE_NOT_FOUND") { + return true; + } + + if ("cause" in err) { + return isModuleNotFound(err.cause); + } + + return false; +} diff --git a/packages/braintrust/src/integration.test.ts b/packages/braintrust/src/integration.test.ts new file mode 100644 index 0000000000..f32f4e51d0 --- /dev/null +++ b/packages/braintrust/src/integration.test.ts @@ -0,0 +1,327 @@ +import type { + AcpEvent, + AcpSpawnContext as SpawnContext, +} from "@poe-code/agent-spawn"; +import type { ConfigDocument } from "@poe-code/poe-code-config"; +import { mergePipelineCallbacks } from "@poe-code/poe-code-config"; +import type { TaskCompletion, TaskProgress } from "@poe-code/pipeline"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +interface SpanRecord { + id: number; + parentId: number | undefined; + name: string; + type: "task" | "tool"; + event?: unknown; + logs: unknown[]; + ended: boolean; +} + +const mockBraintrust = vi.hoisted(() => { + type SpanType = "task" | "tool"; + type RecordShape = { + id: number; + parentId: number | undefined; + name: string; + type: SpanType; + event?: unknown; + logs: unknown[]; + ended: boolean; + }; + type StubShape = { + record: RecordShape; + startSpan(args: { + name: string; + type: SpanType; + event?: unknown; + }): StubShape; + log(event: unknown): void; + end(): void; + }; + + const records: RecordShape[] = []; + const spans = new Map(); + let nextId = 1; + let current: StubShape | undefined; + + function createSpan(args: { + name: string; + type: SpanType; + event?: unknown; + parentId?: number; + }): StubShape { + const record: RecordShape = { + id: nextId, + parentId: args.parentId, + name: args.name, + type: args.type, + event: args.event, + logs: [], + ended: false, + }; + nextId += 1; + records.push(record); + + const span: StubShape = { + record, + startSpan(childArgs) { + const child = createSpan({ + ...childArgs, + parentId: record.id, + }); + current = child; + return child; + }, + log(event) { + record.logs.push(event); + }, + end() { + record.ended = true; + if (current?.record.id === record.id) { + current = record.parentId === undefined + ? undefined + : spans.get(record.parentId); + } + }, + }; + + spans.set(record.id, span); + return span; + } + + return { + records, + initLogger: vi.fn(), + initExperiment: vi.fn(), + flush: vi.fn(), + traced: vi.fn(), + currentSpan: vi.fn(() => current), + reset() { + records.length = 0; + spans.clear(); + nextId = 1; + current = undefined; + this.initLogger.mockReset(); + this.initExperiment.mockReset(); + this.flush.mockReset(); + this.currentSpan.mockClear(); + this.traced.mockReset(); + this.initLogger.mockReturnValue({ logger: "root" }); + this.traced.mockImplementation( + async ( + fn: () => Promise, + args: { name: string; type: SpanType; event?: unknown }, + ) => { + const previous = current; + const root = createSpan(args); + current = root; + + try { + return await fn(); + } finally { + root.end(); + current = previous; + } + }, + ); + }, + }; +}); + +vi.mock("braintrust", () => ({ + initLogger: mockBraintrust.initLogger, + initExperiment: mockBraintrust.initExperiment, + flush: mockBraintrust.flush, + traced: mockBraintrust.traced, + currentSpan: mockBraintrust.currentSpan, +})); + +describe("Braintrust integration", () => { + beforeEach(() => { + vi.resetModules(); + mockBraintrust.reset(); + }); + + it("traces a pipeline run through bootstrap, pipeline callbacks, and spawn middleware", async () => { + const { bootstrap } = await import("./index.js"); + const integrations = await bootstrap({ + integrations: { + braintrust: { + enabled: true, + apiKey: "key", + project: "project", + }, + }, + } as ConfigDocument); + expect(integrations).not.toBeNull(); + + const spawnRuns: Promise[] = []; + const callbacks = mergePipelineCallbacks(integrations?.pipelineCallbacks, { + onTaskStart(progress) { + spawnRuns.push((async () => { + await nextTick(); + await integrations?.spawnMiddleware?.( + createSpawnContext(progress, progress.taskIndex === 0 + ? ["read", "execute"] + : ["search"]), + async () => undefined, + ); + })()); + }, + }); + + await integrations?.traceRun("pipeline", "demo", async () => { + const first = createTaskProgress(0); + callbacks?.onTaskStart?.(first); + await drain(spawnRuns); + callbacks?.onTaskComplete?.(createTaskCompletion(first)); + await nextTick(); + + const second = createTaskProgress(1); + callbacks?.onTaskStart?.(second); + await drain(spawnRuns); + callbacks?.onTaskComplete?.(createTaskCompletion(second)); + await nextTick(); + }); + + const spans = mockBraintrust.records as SpanRecord[]; + expectTree(spans); + + const firstAgent = findSpan(spans, "agent:codex:gpt-5"); + expect(firstAgent.logs).toContainEqual(expect.objectContaining({ + metrics: { + prompt_tokens: 11, + completion_tokens: 7, + tokens: 18, + prompt_cached_tokens: 3, + }, + })); + }); +}); + +function expectTree(spans: SpanRecord[]): void { + const root = findSpan(spans, "pipeline:demo"); + expect(root).toMatchObject({ + parentId: undefined, + type: "task", + event: { + tags: ["surface:pipeline"], + }, + }); + + const firstStep = findSpan(spans, "step:build:0"); + const secondStep = findSpan(spans, "step:build:1"); + expect(firstStep).toMatchObject({ parentId: root.id, type: "task" }); + expect(secondStep).toMatchObject({ parentId: root.id, type: "task" }); + + const firstAgent = childSpans(spans, firstStep, "agent:codex:gpt-5")[0]; + const secondAgent = childSpans(spans, secondStep, "agent:codex:gpt-5")[0]; + expect(firstAgent).toMatchObject({ type: "task" }); + expect(secondAgent).toMatchObject({ type: "task" }); + + expect(childSpans(spans, firstAgent).map((span) => ({ + name: span.name, + type: span.type, + }))).toEqual([ + { name: "tool_call:read", type: "tool" }, + { name: "tool_call:execute", type: "tool" }, + ]); + expect(childSpans(spans, secondAgent).map((span) => ({ + name: span.name, + type: span.type, + }))).toEqual([ + { name: "tool_call:search", type: "tool" }, + ]); +} + +function findSpan(spans: SpanRecord[], name: string): SpanRecord { + const span = spans.find((candidate) => candidate.name === name); + expect(span).toBeDefined(); + return span as SpanRecord; +} + +function childSpans( + spans: SpanRecord[], + parent: SpanRecord, + name?: string, +): SpanRecord[] { + return spans.filter((span) => + span.parentId === parent.id && (name === undefined || span.name === name) + ); +} + +function createTaskProgress(taskIndex: number): TaskProgress { + return { + taskId: `task-${taskIndex}`, + taskTitle: `Task ${taskIndex}`, + stepName: "build", + taskIndex, + totalTasks: 2, + stepIndex: taskIndex, + totalSteps: 2, + }; +} + +function createTaskCompletion(progress: TaskProgress): TaskCompletion { + return { + ...progress, + durationMs: 25, + success: true, + usage: { + inputTokens: 2, + outputTokens: 3, + }, + }; +} + +function createSpawnContext( + progress: TaskProgress, + toolKinds: string[], +): SpawnContext { + return { + sessionId: `session-${progress.taskIndex}`, + agent: "codex", + model: "gpt-5", + prompt: progress.taskTitle, + mode: "edit", + cwd: "/repo", + threadId: `thread-${progress.taskIndex}`, + events: createToolEvents(toolKinds), + usage: { + inputTokens: 11, + outputTokens: 7, + cachedTokens: 3, + }, + }; +} + +function createToolEvents(toolKinds: string[]): AcpEvent[] { + return toolKinds.flatMap((kind, index) => { + const toolCallId = `${kind}-${index}`; + return [ + { + sessionUpdate: "tool_call", + toolCallId, + title: kind, + kind, + input: { value: index }, + }, + { + sessionUpdate: "tool_call_update", + toolCallId, + status: "completed", + content: [{ type: "text", text: `${kind} output` }], + }, + ] as unknown as AcpEvent[]; + }); +} + +async function drain(promises: Promise[]): Promise { + await Promise.all(promises.splice(0)); +} + +function nextTick(): Promise { + return new Promise((resolve) => { + setImmediate(resolve); + }); +} diff --git a/packages/braintrust/src/redact.test.ts b/packages/braintrust/src/redact.test.ts new file mode 100644 index 0000000000..dadfd07352 --- /dev/null +++ b/packages/braintrust/src/redact.test.ts @@ -0,0 +1,60 @@ +import { describe, expect, it } from "vitest"; + +import { redact } from "./redact.js"; + +describe("redact", () => { + it("truncates strings whose UTF-8 byte length exceeds 65536", () => { + expect(redact("a".repeat(65_537))).toBe("[truncated:65537]"); + }); + + it("redacts buffers with a null byte in the first 1024 bytes", () => { + const value = Buffer.from([1, 2, 0, 3]); + + expect(redact(value)).toBe("[binary:4]"); + }); + + it("redacts Uint8Arrays with a null byte in the first 1024 bytes", () => { + const value = new Uint8Array([1, 2, 0, 3]); + + expect(redact(value)).toBe("[binary:4]"); + }); + + it("does not redact binary values with a null byte after the first 1024 bytes", () => { + const value = Buffer.alloc(1_026, 1); + value[1_025] = 0; + + expect(redact(value)).toBe(value); + }); + + it("truncates the whole value when its JSON-serialized size exceeds 262144 bytes", () => { + const value = { payload: "a".repeat(262_145) }; + const originalBytes = Buffer.byteLength(JSON.stringify(value), "utf8"); + + expect(redact(value)).toBe(`[truncated:${originalBytes}]`); + }); + + it("recurses into nested structures and preserves unaffected leaves", () => { + const input = { + id: 123, + name: "run", + events: [ + { output: "ok", data: Buffer.from([1, 0, 2]) }, + { output: "é".repeat(32_769), data: new Uint8Array([1, 2, 3]) }, + ], + enabled: true, + missing: null, + }; + + expect(redact(input)).toEqual({ + id: 123, + name: "run", + events: [ + { output: "ok", data: "[binary:3]" }, + { output: "[truncated:65538]", data: input.events[1].data }, + ], + enabled: true, + missing: null, + }); + expect(redact(input)).not.toBe(input); + }); +}); diff --git a/packages/braintrust/src/redact.ts b/packages/braintrust/src/redact.ts new file mode 100644 index 0000000000..c2e03c6169 --- /dev/null +++ b/packages/braintrust/src/redact.ts @@ -0,0 +1,45 @@ +const MAX_STRING_BYTES = 65_536; +const MAX_JSON_BYTES = 262_144; +const BINARY_SCAN_BYTES = 1_024; + +export function redact(value: unknown): unknown { + const serialized = JSON.stringify(value); + if (serialized !== undefined) { + const originalBytes = Buffer.byteLength(serialized, "utf8"); + if (originalBytes > MAX_JSON_BYTES) { + return `[truncated:${originalBytes}]`; + } + } + + return redactLeaf(value); +} + +function redactLeaf(value: unknown): unknown { + if (typeof value === "string") { + const bytes = Buffer.byteLength(value, "utf8"); + return bytes > MAX_STRING_BYTES ? `[truncated:${bytes}]` : value; + } + + if (value instanceof Uint8Array) { + const scanLength = Math.min(value.byteLength, BINARY_SCAN_BYTES); + for (let index = 0; index < scanLength; index += 1) { + if (value[index] === 0x00) { + return `[binary:${value.byteLength}]`; + } + } + + return value; + } + + if (Array.isArray(value)) { + return value.map((item) => redactLeaf(item)); + } + + if (value !== null && typeof value === "object") { + return Object.fromEntries( + Object.entries(value).map(([key, item]) => [key, redactLeaf(item)]), + ); + } + + return value; +} diff --git a/packages/braintrust/src/row-builder.test.ts b/packages/braintrust/src/row-builder.test.ts new file mode 100644 index 0000000000..132ca5dbad --- /dev/null +++ b/packages/braintrust/src/row-builder.test.ts @@ -0,0 +1,221 @@ +import type { JournalEntry } from "@poe-code/experiment-loop"; +import type { TaskCompletion, TaskProgress } from "@poe-code/pipeline"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import type { BraintrustClient } from "./client.js"; +import { + logSuperintendentRole, + makeExperimentIterationState, + makePipelineRowState, +} from "./row-builder.js"; + +const mockBraintrust = vi.hoisted(() => ({ + currentSpan: vi.fn(), +})); + +vi.mock("braintrust", () => ({ + currentSpan: mockBraintrust.currentSpan, +})); + +describe("makePipelineRowState", () => { + beforeEach(() => { + mockBraintrust.currentSpan.mockReset(); + }); + + it("opens a task span on start and logs the completed step payload", async () => { + const stepSpan = createMockSpan(); + const parentSpan = { + startSpan: vi.fn(() => stepSpan), + }; + mockBraintrust.currentSpan.mockReturnValue(parentSpan); + const client = createMockClient(); + const state = makePipelineRowState(client); + const started = { + taskId: "task-1", + taskTitle: "Implement telemetry", + stepName: "builder", + taskIndex: 2, + totalTasks: 5, + stepIndex: 1, + totalSteps: 2, + step_prompt: "Build the row helper", + plan_section: "## Telemetry", + } satisfies TaskProgress & Record; + const completed = { + ...started, + durationMs: 1234, + success: true, + usage: { + inputTokens: 11, + outputTokens: 7, + cachedTokens: 3, + }, + result_summary: "Helper implemented", + files_changed: ["packages/braintrust/src/row-builder.ts"], + } satisfies TaskCompletion & Record; + + state.start(started); + state.complete(completed); + + await vi.waitFor(() => { + expect(stepSpan.log).toHaveBeenCalledWith({ + input: { + step_name: "builder", + step_prompt: "Build the row helper", + plan_section: "## Telemetry", + }, + output: { + result_summary: "Helper implemented", + files_changed: ["packages/braintrust/src/row-builder.ts"], + success: true, + }, + scores: { + passed: 1, + }, + metrics: { + prompt_tokens: 11, + completion_tokens: 7, + tokens: 18, + prompt_cached_tokens: 3, + durationMs: 1234, + }, + }); + }); + expect(parentSpan.startSpan).toHaveBeenCalledWith({ + name: "step:builder:1", + type: "task", + }); + expect(stepSpan.end).toHaveBeenCalledTimes(1); + expect(client.recordError).not.toHaveBeenCalled(); + }); +}); + +describe("logSuperintendentRole", () => { + beforeEach(() => { + mockBraintrust.currentSpan.mockReset(); + }); + + it("logs inspector payloads with a satisfied score derived from verdict", async () => { + const roleSpan = createMockSpan(); + const parentSpan = { + startSpan: vi.fn(() => roleSpan), + }; + mockBraintrust.currentSpan.mockReturnValue(parentSpan); + const client = createMockClient(); + + await logSuperintendentRole(client, "inspector", { + input: { + checklist: "Review implementation", + }, + output: { + summary: "Looks correct", + }, + verdict: "satisfied", + }); + + expect(parentSpan.startSpan).toHaveBeenCalledWith({ + name: "role:inspector", + type: "task", + }); + expect(roleSpan.log).toHaveBeenCalledWith({ + input: { + checklist: "Review implementation", + }, + output: { + summary: "Looks correct", + }, + scores: { + satisfied: 1, + }, + }); + expect(roleSpan.end).toHaveBeenCalledTimes(1); + expect(client.recordError).not.toHaveBeenCalled(); + }); +}); + +describe("makeExperimentIterationState", () => { + it("opens an experiment iteration row and logs accumulated callback payload", async () => { + const iterationSpan = createMockSpan(); + const experiment = { + startSpan: vi.fn(() => iterationSpan), + }; + const client = createMockClient({ + experiment, + }); + const state = makeExperimentIterationState(client, "benchmarks"); + const entry = { + commit: "keep-123", + status: "keep", + scores: { + tests: 15, + }, + output: "tests: score=15, passed=true", + agentOutput: "Reduced allocations in parser", + durationMs: 3210, + timestamp: "2026-05-04T12:00:00.000Z", + brief: "Improve parser throughput", + } satisfies JournalEntry & Record; + + state.baseline({ tests: 10 }); + await state.start(3, "codex"); + state.metric("tests", 15); + state.commit("keep-123"); + await state.complete(3, entry); + + expect(client.getExperiment).toHaveBeenCalledWith("benchmarks"); + expect(experiment.startSpan).toHaveBeenCalledWith({ + name: "iteration:3", + type: "task", + }); + expect(iterationSpan.log).toHaveBeenCalledWith({ + input: { + brief: "Improve parser throughput", + baseline: { + tests: 10, + }, + agent: "codex", + iteration: 3, + }, + output: { + diff_summary: "Reduced allocations in parser", + kept: true, + }, + scores: { + tests: 15, + delta: 5, + }, + metrics: { + tests: 15, + durationMs: 3210, + }, + metadata: { + commit: "keep-123", + }, + }); + expect(iterationSpan.end).toHaveBeenCalledTimes(1); + expect(client.recordError).not.toHaveBeenCalled(); + }); +}); + +function createMockSpan() { + return { + startSpan: vi.fn(), + log: vi.fn(), + end: vi.fn(), + }; +} + +function createMockClient(options: { experiment?: unknown } = {}): BraintrustClient { + return { + getSdk: vi.fn(), + getRootLogger: vi.fn(), + getExperiment: vi.fn(async () => options.experiment), + flush: vi.fn(), + recordError: vi.fn(), + status: vi.fn(() => ({ + lastError: null, + errorCount: 0, + project: "project", + })), + }; +} diff --git a/packages/braintrust/src/row-builder.ts b/packages/braintrust/src/row-builder.ts new file mode 100644 index 0000000000..e3416157ed --- /dev/null +++ b/packages/braintrust/src/row-builder.ts @@ -0,0 +1,476 @@ +import type { JournalEntry } from "@poe-code/experiment-loop"; +import type { TaskCompletion, TaskProgress } from "@poe-code/pipeline"; +import type { BuilderResult, InspectorResult } from "@poe-code/superintendent"; + +import type { BraintrustClient } from "./client.js"; +import { redact } from "./redact.js"; + +type SuperintendentRole = "builder" | "inspector" | "superintendent" | "owner"; +type KnownSuperintendentResult = BuilderResult | InspectorResult; +type EventRecord = Record; + +interface BraintrustSpan { + startSpan(args: { name: string; type: "task" | "tool" }): BraintrustSpan; + log(event: BraintrustLogEvent): void; + end(): void; +} + +interface BraintrustSpanParent { + startSpan(args: { name: string; type: "task" | "tool" }): BraintrustSpan; +} + +interface BraintrustLogEvent { + input?: unknown; + output?: unknown; + scores?: Record; + metrics?: Record; + metadata?: Record; +} + +type PipelineRowState = { + span?: Promise; + progress?: TaskProgress; +}; + +type ExperimentIteration = { + span?: BraintrustSpan; + agent: string; + iteration: number; + baseline?: Record; + metrics: Record; + commit?: string; + reset?: string; +}; + +export function makePipelineRowState(client: BraintrustClient): { + start(progress: TaskProgress): void; + complete(progress: TaskCompletion): void; +} { + const rows = new Map(); + + return { + start(progress: TaskProgress): void { + try { + const key = pipelineKey(progress); + const row: PipelineRowState = { + progress, + span: openCurrentChildSpan(client, { + name: `step:${readPipelineStep(progress)}:${readPipelineIndex(progress)}`, + type: "task", + }, "pipeline step start"), + }; + rows.set(key, row); + } catch (err) { + client.recordError(err, "pipeline step start"); + } + }, + + complete(progress: TaskCompletion): void { + try { + const key = pipelineKey(progress); + const row = rows.get(key); + rows.delete(key); + + void (async () => { + try { + const span = row?.span === undefined + ? await openCurrentChildSpan(client, { + name: `step:${readPipelineStep(progress)}:${readPipelineIndex(progress)}`, + type: "task", + }, "pipeline step complete") + : await row.span; + + if (span === undefined) { + return; + } + + try { + span.log(buildPipelineCompletionLog(row?.progress ?? progress, progress)); + } finally { + span.end(); + } + } catch (err) { + client.recordError(err, "pipeline step complete"); + } + })(); + } catch (err) { + client.recordError(err, "pipeline step complete"); + } + }, + }; +} + +export async function logSuperintendentRole( + client: BraintrustClient, + role: SuperintendentRole, + result: unknown, +): Promise { + try { + const span = await openCurrentChildSpan(client, { + name: `role:${role}`, + type: "task", + }, `superintendent ${role}`); + + if (span === undefined) { + return; + } + + try { + span.log(buildSuperintendentLog(role, result)); + } finally { + span.end(); + } + } catch (err) { + client.recordError(err, `superintendent ${role}`); + } +} + +export function makeExperimentIterationState( + client: BraintrustClient, + experimentName: string, +): { + start(index: number, agent: string): Promise; + baseline(b: Record): void; + metric(name: string, value: number): void; + commit(hash: string): void; + reset(hash: string): void; + complete(index: number, entry: JournalEntry): Promise; +} { + const rows = new Map(); + let latestBaseline: Record | undefined; + + return { + async start(index: number, agent: string): Promise { + try { + const experiment = asSpanParent(await client.getExperiment(experimentName)); + rows.set(index, { + span: experiment.startSpan({ + name: `iteration:${index}`, + type: "task", + }), + agent, + iteration: index, + baseline: latestBaseline, + metrics: {}, + }); + } catch (err) { + client.recordError(err, `experiment ${experimentName} iteration start`); + } + }, + + baseline(b: Record): void { + try { + latestBaseline = { ...b }; + for (const row of rows.values()) { + row.baseline = latestBaseline; + } + } catch (err) { + client.recordError(err, `experiment ${experimentName} baseline`); + } + }, + + metric(name: string, value: number): void { + try { + const row = readLatestRow(rows); + if (row !== undefined && Number.isFinite(value)) { + row.metrics[name] = value; + } + } catch (err) { + client.recordError(err, `experiment ${experimentName} metric`); + } + }, + + commit(hash: string): void { + try { + const row = readLatestRow(rows); + if (row !== undefined) { + row.commit = hash; + } + } catch (err) { + client.recordError(err, `experiment ${experimentName} commit`); + } + }, + + reset(hash: string): void { + try { + const row = readLatestRow(rows); + if (row !== undefined) { + row.reset = hash; + } + } catch (err) { + client.recordError(err, `experiment ${experimentName} reset`); + } + }, + + async complete(index: number, entry: JournalEntry): Promise { + const row = rows.get(index); + rows.delete(index); + + try { + if (row?.span === undefined) { + return; + } + + try { + row.span.log(buildExperimentLog(row, entry)); + } finally { + row.span.end(); + } + } catch (err) { + client.recordError(err, `experiment ${experimentName} iteration complete`); + } + }, + }; +} + +async function openCurrentChildSpan( + client: BraintrustClient, + args: { name: string; type: "task" | "tool" }, + ctx: string, +): Promise { + try { + const { currentSpan } = await import("braintrust"); + return asSpanParent(currentSpan()).startSpan(args); + } catch (err) { + client.recordError(err, ctx); + return undefined; + } +} + +function buildPipelineCompletionLog( + started: TaskProgress, + completed: TaskCompletion, +): BraintrustLogEvent { + const startRecord = asRecord(started) ?? {}; + const completeRecord = asRecord(completed) ?? {}; + + return { + input: redact({ + step_name: readPipelineStep(started), + step_prompt: readFirstString(startRecord, ["step_prompt", "stepPrompt", "prompt"]), + plan_section: readFirstString(startRecord, ["plan_section", "planSection", "section"]), + }), + output: redact({ + result_summary: readFirstString(completeRecord, [ + "result_summary", + "resultSummary", + "summary", + ]), + files_changed: readFirstValue(completeRecord, ["files_changed", "filesChanged"]), + success: completed.success, + }), + scores: { + passed: completed.success ? 1 : 0, + }, + metrics: buildPipelineMetrics(completed), + }; +} + +function buildSuperintendentLog( + role: SuperintendentRole, + result: unknown, +): BraintrustLogEvent { + const record = asRecord(result as KnownSuperintendentResult | unknown); + const event: BraintrustLogEvent = { + input: redact(record?.input), + output: redact(record?.output ?? result), + }; + + if (role === "inspector") { + const satisfied = readSatisfiedScore(record); + if (satisfied !== undefined) { + event.scores = { satisfied }; + } + } + + return event; +} + +function buildExperimentLog( + row: ExperimentIteration, + entry: JournalEntry, +): BraintrustLogEvent { + const entryRecord = asRecord(entry) ?? {}; + const scores = buildExperimentScores(row.baseline, entry.scores); + const metrics = { ...row.metrics }; + + if (Number.isFinite(entry.durationMs)) { + metrics.durationMs = entry.durationMs; + } + + return { + input: redact({ + brief: readFirstString(entryRecord, ["brief"]), + baseline: row.baseline, + agent: row.agent, + iteration: row.iteration, + }), + output: redact({ + diff_summary: entry.agentOutput, + kept: entry.status === "keep", + }), + ...(Object.keys(scores).length === 0 ? {} : { scores }), + ...(Object.keys(metrics).length === 0 ? {} : { metrics }), + metadata: { + ...(row.commit !== undefined ? { commit: row.commit } : {}), + ...(row.reset !== undefined ? { reset: row.reset } : {}), + }, + }; +} + +function buildPipelineMetrics(progress: TaskCompletion): Record { + const metrics: Record = {}; + const usage = progress.usage; + + if (usage !== undefined) { + addMetric(metrics, "prompt_tokens", usage.inputTokens); + addMetric(metrics, "completion_tokens", usage.outputTokens); + addMetric(metrics, "tokens", usage.inputTokens + usage.outputTokens); + addMetric(metrics, "prompt_cached_tokens", usage.cachedTokens); + } + + addMetric(metrics, "durationMs", progress.durationMs); + + return metrics; +} + +function buildExperimentScores( + baseline: Record | undefined, + scores: Record | undefined, +): Record { + const result = { ...(scores ?? {}) }; + const delta = sumDelta(baseline, scores); + + if (delta !== undefined) { + result.delta = delta; + } + + return result; +} + +function sumDelta( + baseline: Record | undefined, + scores: Record | undefined, +): number | undefined { + if (baseline === undefined || scores === undefined) { + return undefined; + } + + let delta = 0; + let count = 0; + + for (const [name, value] of Object.entries(scores)) { + const base = baseline[name]; + if (Number.isFinite(value) && Number.isFinite(base)) { + delta += value - base; + count += 1; + } + } + + return count === 0 ? undefined : delta; +} + +function readSatisfiedScore(record: EventRecord | undefined): number | undefined { + const verdict = record?.verdict ?? record?.satisfied; + + if (typeof verdict === "boolean") { + return verdict ? 1 : 0; + } + + if (typeof verdict === "number" && Number.isFinite(verdict)) { + return verdict > 0 ? 1 : 0; + } + + if (typeof verdict !== "string") { + return undefined; + } + + const normalized = verdict.trim().toLowerCase(); + if (["satisfied", "satisfy", "pass", "passed", "approve", "approved", "true", "yes"].includes(normalized)) { + return 1; + } + + if (["unsatisfied", "fail", "failed", "reject", "rejected", "false", "no"].includes(normalized)) { + return 0; + } + + return undefined; +} + +function pipelineKey(progress: TaskProgress): string { + return [ + progress.taskId, + progress.stepName ?? "", + progress.phase ?? "", + String(progress.taskIndex), + String(progress.stepIndex ?? ""), + ].join(":"); +} + +function readPipelineStep(progress: TaskProgress): string { + return progress.stepName ?? progress.phase ?? progress.taskTitle; +} + +function readPipelineIndex(progress: TaskProgress): number { + return progress.stepIndex ?? progress.taskIndex; +} + +function readLatestRow( + rows: Map, +): ExperimentIteration | undefined { + let latest: ExperimentIteration | undefined; + + for (const row of rows.values()) { + if (latest === undefined || row.iteration > latest.iteration) { + latest = row; + } + } + + return latest; +} + +function asSpanParent(value: unknown): BraintrustSpanParent { + const span = value as Partial | undefined; + if (span === undefined || typeof span.startSpan !== "function") { + throw new Error("Braintrust span parent unavailable"); + } + + return span as BraintrustSpanParent; +} + +function asRecord(value: unknown): EventRecord | undefined { + return typeof value === "object" && value !== null + ? value as EventRecord + : undefined; +} + +function readFirstString( + record: EventRecord, + keys: string[], +): string | undefined { + const value = readFirstValue(record, keys); + return typeof value === "string" ? value : undefined; +} + +function readFirstValue( + record: EventRecord, + keys: string[], +): unknown { + for (const key of keys) { + if (Object.hasOwn(record, key)) { + return record[key]; + } + } + + return undefined; +} + +function addMetric( + metrics: Record, + key: string, + value: number | undefined, +): void { + if (value !== undefined && Number.isFinite(value)) { + metrics[key] = value; + } +} diff --git a/packages/braintrust/src/span-builder.test.ts b/packages/braintrust/src/span-builder.test.ts new file mode 100644 index 0000000000..b0ee0ad8e0 --- /dev/null +++ b/packages/braintrust/src/span-builder.test.ts @@ -0,0 +1,161 @@ +import type { AcpEvent, AcpSpawnContext as SpawnContext } from "@poe-code/agent-spawn"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import type { BraintrustClient } from "./client.js"; +import { logSpawnSession } from "./span-builder.js"; + +const mockBraintrust = vi.hoisted(() => ({ + currentSpan: vi.fn(), +})); + +vi.mock("braintrust", () => ({ + currentSpan: mockBraintrust.currentSpan, +})); + +describe("logSpawnSession", () => { + beforeEach(() => { + mockBraintrust.currentSpan.mockReset(); + }); + + it("logs agent and tool spans in order with canonical token metrics", async () => { + const calls: string[] = []; + const agentSpan = createMockSpan("agent", calls); + const toolSpan = createMockSpan("tool", calls); + const parentSpan = { + startSpan: vi.fn((args: unknown) => { + calls.push(`parent.startSpan:${JSON.stringify(args)}`); + return agentSpan; + }), + }; + agentSpan.startSpan.mockImplementation((args: unknown) => { + calls.push(`agent.startSpan:${JSON.stringify(args)}`); + return toolSpan; + }); + mockBraintrust.currentSpan.mockReturnValue(parentSpan); + const client = createMockClient(); + + const events = [ + { event: "agent_message", text: "Hello " }, + { + sessionUpdate: "tool_call", + toolCallId: "tc-1", + title: "Read file", + kind: "read", + input: { path: "README.md" }, + }, + { + sessionUpdate: "tool_call_update", + toolCallId: "tc-1", + content: [{ type: "text", text: "file contents" }], + status: "completed", + }, + { + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "world" }, + }, + ] as unknown as AcpEvent[]; + const ctx: SpawnContext = { + sessionId: "session-1", + agent: "codex", + model: "gpt-5", + events, + usage: { + inputTokens: 11, + outputTokens: 7, + cachedTokens: 3, + }, + threadId: "thread-1", + prompt: "Say hello", + mode: "edit", + cwd: "/repo", + }; + + await logSpawnSession(client, ctx); + + expect(calls).toEqual([ + 'parent.startSpan:{"name":"agent:codex:gpt-5","type":"task"}', + 'agent.startSpan:{"name":"tool_call:read","type":"tool"}', + 'tool.log:{"input":{"path":"README.md"},"output":"file contents"}', + "tool.end", + 'agent.log:{"input":{"prompt":"Say hello","mode":"edit","cwd":"/repo"},"output":"Hello world","metadata":{"sessionId":"session-1","threadId":"thread-1"},"metrics":{"prompt_tokens":11,"completion_tokens":7,"tokens":18,"prompt_cached_tokens":3}}', + "agent.end", + ]); + expect(client.recordError).not.toHaveBeenCalled(); + }); + + it("records span-building errors and does not throw", async () => { + mockBraintrust.currentSpan.mockReturnValue({}); + const client = createMockClient(); + const ctx: SpawnContext = { + sessionId: "session-1", + agent: "codex", + events: [], + usage: { + inputTokens: 0, + outputTokens: 0, + }, + }; + + await expect(logSpawnSession(client, ctx)).resolves.toBeUndefined(); + + expect(client.recordError).toHaveBeenCalledTimes(1); + expect(client.recordError).toHaveBeenCalledWith( + expect.any(Error), + "log spawn session", + ); + }); + + it("includes spawn metadata on the agent span", async () => { + const calls: string[] = []; + const agentSpan = createMockSpan("agent", calls); + mockBraintrust.currentSpan.mockReturnValue({ + startSpan: vi.fn(() => agentSpan), + }); + const client = createMockClient(); + const ctx: SpawnContext & { metadata: Record } = { + sessionId: "session-1", + agent: "codex", + events: [], + usage: { + inputTokens: 0, + outputTokens: 0, + }, + metadata: { + aborted: true, + }, + }; + + await logSpawnSession(client, ctx); + + expect(calls).toContain( + 'agent.log:{"input":{},"output":"","metadata":{"sessionId":"session-1","aborted":true},"metrics":{"prompt_tokens":0,"completion_tokens":0,"tokens":0}}', + ); + }); +}); + +function createMockSpan(name: string, calls: string[]) { + return { + startSpan: vi.fn(), + log: vi.fn((event: unknown) => { + calls.push(`${name}.log:${JSON.stringify(event)}`); + }), + end: vi.fn(() => { + calls.push(`${name}.end`); + }), + }; +} + +function createMockClient(): BraintrustClient { + return { + getSdk: vi.fn(), + getRootLogger: vi.fn(), + getExperiment: vi.fn(), + flush: vi.fn(), + recordError: vi.fn(), + status: vi.fn(() => ({ + lastError: null, + errorCount: 0, + project: "project", + })), + }; +} diff --git a/packages/braintrust/src/span-builder.ts b/packages/braintrust/src/span-builder.ts new file mode 100644 index 0000000000..17c4cd3f24 --- /dev/null +++ b/packages/braintrust/src/span-builder.ts @@ -0,0 +1,244 @@ +import type { AcpEvent, AcpSpawnContext as SpawnContext } from "@poe-code/agent-spawn"; + +import type { BraintrustClient } from "./client.js"; +import { redact } from "./redact.js"; + +interface BraintrustSpan { + startSpan(args: { name: string; type: "task" | "tool" }): BraintrustSpan; + log(event: { + input?: unknown; + output?: unknown; + metadata?: Record; + metrics?: Record; + }): void; + end(): void; +} + +interface BraintrustSpanParent { + startSpan(args: { name: string; type: "task" | "tool" }): BraintrustSpan; +} + +type EventRecord = Record; +type SpawnContextWithMetadata = SpawnContext & { + metadata?: Record; +}; + +export async function logSpawnSession( + client: BraintrustClient, + ctx: SpawnContextWithMetadata, +): Promise { + try { + const { currentSpan } = await import("braintrust"); + const agentSpan = asSpanParent(currentSpan()).startSpan({ + name: `agent:${ctx.agent}:${ctx.model ?? "?"}`, + type: "task", + }); + + try { + logToolSpans(agentSpan, ctx.events); + agentSpan.log({ + input: redact({ + prompt: ctx.prompt, + mode: ctx.mode, + cwd: ctx.cwd, + }), + output: redact(accumulateAgentOutput(ctx.events)), + metadata: { + sessionId: ctx.sessionId, + threadId: ctx.threadId, + ...ctx.metadata, + }, + metrics: buildMetrics(ctx), + }); + } finally { + agentSpan.end(); + } + } catch (err) { + client.recordError(err, "log spawn session"); + } +} + +function logToolSpans(agentSpan: BraintrustSpan, events: AcpEvent[]): void { + for (const [index, event] of events.entries()) { + const toolCall = asToolCall(event); + if (toolCall === undefined) { + continue; + } + + const toolSpan = agentSpan.startSpan({ + name: `tool_call:${readString(toolCall.kind) ?? "unknown"}`, + type: "tool", + }); + + try { + toolSpan.log({ + input: redact(readToolInput(toolCall)), + output: redact(assembleToolOutput(events, index, readString(toolCall.toolCallId))), + }); + } finally { + toolSpan.end(); + } + } +} + +function accumulateAgentOutput(events: AcpEvent[]): string { + let output = ""; + + for (const event of events) { + const record = asRecord(event); + if (record === undefined) { + continue; + } + + if (record.event === "agent_message") { + output += readString(record.text) ?? ""; + continue; + } + + if (record.sessionUpdate === "agent_message_chunk") { + output += readContentText(record.content); + } + } + + return output; +} + +function assembleToolOutput( + events: AcpEvent[], + toolCallIndex: number, + toolCallId: string | undefined, +): unknown { + const outputs: unknown[] = []; + let text = ""; + + for (const event of events.slice(toolCallIndex + 1)) { + const update = asToolCallUpdate(event); + if (update === undefined) { + continue; + } + + if (toolCallId !== undefined && update.toolCallId !== toolCallId) { + continue; + } + + if (Object.hasOwn(update, "rawOutput")) { + outputs.push(update.rawOutput); + } + + const contentText = readContentText(update.content); + if (contentText.length > 0) { + text += contentText; + } + } + + if (outputs.length === 0) { + return text; + } + + if (text.length > 0) { + outputs.push(text); + } + + return outputs.length === 1 ? outputs[0] : outputs; +} + +function buildMetrics(ctx: SpawnContext): Record { + const usage = ctx.usage as unknown as Record; + const metrics: Record = {}; + const promptTokens = readNumber(usage.prompt_tokens) ?? readNumber(usage.inputTokens); + const completionTokens = readNumber(usage.completion_tokens) ?? readNumber(usage.outputTokens); + + addMetric(metrics, "prompt_tokens", promptTokens); + addMetric(metrics, "completion_tokens", completionTokens); + addMetric( + metrics, + "tokens", + readNumber(usage.tokens) ?? sumIfPresent(promptTokens, completionTokens), + ); + addMetric( + metrics, + "prompt_cached_tokens", + readNumber(usage.prompt_cached_tokens) ?? readNumber(usage.cachedTokens), + ); + addMetric( + metrics, + "prompt_cache_creation_tokens", + readNumber(usage.prompt_cache_creation_tokens), + ); + addMetric(metrics, "durationMs", readNumber(usage.durationMs)); + + return metrics; +} + +function asSpanParent(value: unknown): BraintrustSpanParent { + const span = value as Partial | undefined; + if (span === undefined || typeof span.startSpan !== "function") { + throw new Error("Braintrust current span unavailable"); + } + + return span as BraintrustSpanParent; +} + +function asToolCall(event: AcpEvent): EventRecord | undefined { + const record = asRecord(event); + return record?.sessionUpdate === "tool_call" ? record : undefined; +} + +function asToolCallUpdate(event: AcpEvent): EventRecord | undefined { + const record = asRecord(event); + return record?.sessionUpdate === "tool_call_update" ? record : undefined; +} + +function readToolInput(toolCall: EventRecord): unknown { + if (Object.hasOwn(toolCall, "input")) { + return toolCall.input; + } + + return toolCall.rawInput; +} + +function readContentText(value: unknown): string { + if (Array.isArray(value)) { + return value.map(readContentText).join(""); + } + + const record = asRecord(value); + if (record === undefined || record.type !== "text") { + return ""; + } + + return readString(record.text) ?? ""; +} + +function asRecord(value: unknown): EventRecord | undefined { + return typeof value === "object" && value !== null + ? value as EventRecord + : undefined; +} + +function readString(value: unknown): string | undefined { + return typeof value === "string" ? value : undefined; +} + +function readNumber(value: unknown): number | undefined { + return typeof value === "number" && Number.isFinite(value) + ? value + : undefined; +} + +function addMetric( + metrics: Record, + key: string, + value: number | undefined, +): void { + if (value !== undefined) { + metrics[key] = value; + } +} + +function sumIfPresent( + left: number | undefined, + right: number | undefined, +): number | undefined { + return left !== undefined && right !== undefined ? left + right : undefined; +} diff --git a/packages/braintrust/src/trace-run.test.ts b/packages/braintrust/src/trace-run.test.ts new file mode 100644 index 0000000000..da22ab924a --- /dev/null +++ b/packages/braintrust/src/trace-run.test.ts @@ -0,0 +1,106 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import { createClient } from "./client.js"; +import { makeTraceRun } from "./trace-run.js"; + +const mockBraintrust = vi.hoisted(() => ({ + importCount: 0, + initLogger: vi.fn(), + initExperiment: vi.fn(), + flush: vi.fn(), + traced: vi.fn(), + currentSpan: vi.fn(), +})); + +vi.mock("braintrust", () => { + mockBraintrust.importCount += 1; + + return { + initLogger: mockBraintrust.initLogger, + initExperiment: mockBraintrust.initExperiment, + flush: mockBraintrust.flush, + get traced() { + return mockBraintrust.traced; + }, + currentSpan: mockBraintrust.currentSpan, + }; +}); + +describe("makeTraceRun", () => { + beforeEach(() => { + mockBraintrust.importCount = 0; + mockBraintrust.initLogger.mockReset(); + mockBraintrust.initExperiment.mockReset(); + mockBraintrust.flush.mockReset(); + mockBraintrust.traced.mockReset(); + mockBraintrust.currentSpan.mockReset(); + }); + + it("runs the callback inside a named task span with the surface tag", async () => { + mockBraintrust.initLogger.mockReturnValue({ id: "logger" }); + mockBraintrust.traced.mockImplementation( + async (fn: () => Promise) => fn(), + ); + const client = createClient({ apiKey: "key", project: "project" }); + const traceRun = makeTraceRun(client); + const fn = vi.fn(async () => "done"); + + await expect(traceRun("spawn", "worker", fn)).resolves.toBe("done"); + + expect(mockBraintrust.importCount).toBe(1); + expect(mockBraintrust.initLogger).toHaveBeenCalledTimes(1); + expect(mockBraintrust.traced).toHaveBeenCalledTimes(1); + expect(mockBraintrust.traced).toHaveBeenCalledWith(expect.any(Function), { + name: "spawn:worker", + type: "task", + event: { + tags: ["surface:spawn"], + }, + }); + expect(fn).toHaveBeenCalledTimes(1); + }); + + it("falls back to the callback and records setup errors", async () => { + mockBraintrust.initLogger.mockReturnValue({ id: "logger" }); + mockBraintrust.traced.mockImplementation(() => { + throw new Error("trace init failed"); + }); + const client = createClient({ apiKey: "key", project: "project" }); + const traceRun = makeTraceRun(client); + const fn = vi.fn(async () => "fallback"); + + await expect(traceRun("pipeline", "orchestrate", fn)).resolves.toBe( + "fallback", + ); + + expect(fn).toHaveBeenCalledTimes(1); + expect(client.status()).toEqual({ + project: "project", + errorCount: 1, + lastError: "trace pipeline:orchestrate: trace init failed", + }); + }); + + it("does not fallback when the traced callback fails", async () => { + mockBraintrust.initLogger.mockReturnValue({ id: "logger" }); + mockBraintrust.traced.mockImplementation( + async (fn: () => Promise) => fn(), + ); + const client = createClient({ apiKey: "key", project: "project" }); + const traceRun = makeTraceRun(client); + const fn = vi.fn(async () => { + throw new Error("task failed"); + }); + + await expect(traceRun("experiment", "trial", fn)).rejects.toThrow( + "task failed", + ); + + expect(fn).toHaveBeenCalledTimes(1); + expect(client.status()).toEqual({ + project: "project", + errorCount: 0, + lastError: null, + }); + }); +}); diff --git a/packages/braintrust/src/trace-run.ts b/packages/braintrust/src/trace-run.ts new file mode 100644 index 0000000000..6942bb0d04 --- /dev/null +++ b/packages/braintrust/src/trace-run.ts @@ -0,0 +1,85 @@ +import type * as BraintrustSdk from "braintrust"; + +import type { BraintrustClient } from "./client.js"; + +export type TraceSurface = + | "pipeline" + | "superintendent" + | "experiment" + | "spawn"; + +export function makeTraceRun(client: BraintrustClient): ( + surface: TraceSurface, + name: string, + fn: () => Promise, +) => Promise { + return async ( + surface: TraceSurface, + name: string, + fn: () => Promise, + ): Promise => { + const spanName = `${surface}:${name}`; + let callbackCompleted = false; + let callbackFailed = false; + let callbackError: unknown; + let callbackValue: T | undefined; + + try { + const rootLogger = await client.getRootLogger(); + if (rootLogger === undefined) { + throw new Error("Braintrust logger unavailable"); + } + + const sdk = await client.getSdk(); + const traced = resolveTraced(sdk); + + const tracedValue = await traced( + async () => { + try { + callbackValue = await fn(); + } catch (err) { + callbackFailed = true; + callbackError = err; + throw err; + } + callbackCompleted = true; + return callbackValue; + }, + { + name: spanName, + type: "task", + event: { + tags: [`surface:${surface}`], + }, + }, + ); + + return tracedValue; + } catch (err) { + if (callbackFailed) { + throw callbackError; + } + + client.recordError(err, `trace ${spanName}`); + if (callbackCompleted) { + return callbackValue as T; + } + + return fn(); + } + }; +} + +function resolveTraced( + sdk: typeof BraintrustSdk | undefined, +): typeof BraintrustSdk.traced { + if (sdk === undefined) { + throw new Error("Braintrust SDK unavailable"); + } + + if (typeof sdk.traced !== "function") { + throw new Error("Braintrust SDK traced unavailable"); + } + + return sdk.traced; +} diff --git a/packages/braintrust/tsconfig.json b/packages/braintrust/tsconfig.json new file mode 100644 index 0000000000..44b01ee753 --- /dev/null +++ b/packages/braintrust/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "outDir": "dist", + "rootDir": "src", + "noEmit": false, + "declaration": true + }, + "include": ["src"], + "exclude": ["**/*.test.ts"] +} diff --git a/packages/poe-code-config/src/index.ts b/packages/poe-code-config/src/index.ts index d24816342e..7012d966d3 100644 --- a/packages/poe-code-config/src/index.ts +++ b/packages/poe-code-config/src/index.ts @@ -3,7 +3,9 @@ export type { ConfigFieldType, ConfigStore, ConfigStoreOptions, + BraintrustIntegrationConfig, InferConfig, + IntegrationsConfig, MemoryCacheConfig, MemoryConfidenceConfig, MemoryConfig, @@ -17,7 +19,7 @@ export type { TypeMap } from "./types.js"; -export { defineScope } from "./schema.js"; +export { defineScope, integrationsConfigScope } from "./schema.js"; export { parseRunner, parseRuntime, @@ -35,6 +37,15 @@ export { export { planConfigScope } from "./plan-scope.js"; export { createConfigStore } from "./config.js"; export { deepMergeDocuments } from "./merge.js"; +export { + mergeExperimentCallbacks, + mergeLoopCallbacks, + mergePipelineCallbacks, + type ExperimentCallbackFields, + type LoopCallbacks, + type PipelineCallbackFields +} from "./merge-callbacks.js"; +export { loadIntegrations, type Integrations } from "./integrations-loader.js"; export { loadAgentModel, loadDefaultModel, diff --git a/packages/poe-code-config/src/integrations-loader.test.ts b/packages/poe-code-config/src/integrations-loader.test.ts new file mode 100644 index 0000000000..09ddbb0ef8 --- /dev/null +++ b/packages/poe-code-config/src/integrations-loader.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it, vi } from "vitest"; +import type { ConfigDocument } from "./types.js"; + +describe("loadIntegrations", () => { + it("returns null without importing Braintrust when disabled", async () => { + let imported = false; + vi.doMock("@poe-code/braintrust", () => { + imported = true; + return { + bootstrap: vi.fn() + }; + }); + + const { loadIntegrations } = await import("./integrations-loader.js"); + const result = await loadIntegrations({ + integrations: { + braintrust: { + enabled: false + } + } + } as ConfigDocument); + + expect(result).toBeNull(); + expect(imported).toBe(false); + + vi.doUnmock("@poe-code/braintrust"); + }); +}); diff --git a/packages/poe-code-config/src/integrations-loader.ts b/packages/poe-code-config/src/integrations-loader.ts new file mode 100644 index 0000000000..0202a49905 --- /dev/null +++ b/packages/poe-code-config/src/integrations-loader.ts @@ -0,0 +1,39 @@ +import type { ConfigDocument as PoeCodeConfig } from "./types.js"; +import type { + ExperimentCallbackFields, + LoopCallbacks, + PipelineCallbackFields +} from "./merge-callbacks.js"; + +export type TraceSurface = "pipeline" | "experiment" | "superintendent" | "spawn"; + +export type AcpMiddleware = ( + ctx: unknown, + next: () => Promise +) => Promise; + +export interface Integrations { + spawnMiddleware?: AcpMiddleware; + pipelineCallbacks?: PipelineCallbackFields; + experimentCallbacks?: ExperimentCallbackFields; + superintendentCallbacks?: LoopCallbacks; + traceRun( + surface: TraceSurface, + name: string, + fn: () => Promise + ): Promise; + shutdown(): Promise; +} + +type BraintrustModule = { + bootstrap(config: PoeCodeConfig): Promise; +}; + +export async function loadIntegrations( + config: PoeCodeConfig +): Promise { + if (!config.integrations?.braintrust?.enabled) return null; + const packageName = "@poe-code/braintrust"; + const mod = await import(packageName) as BraintrustModule; + return mod.bootstrap(config); +} diff --git a/packages/poe-code-config/src/merge-callbacks.test.ts b/packages/poe-code-config/src/merge-callbacks.test.ts new file mode 100644 index 0000000000..61586745cb --- /dev/null +++ b/packages/poe-code-config/src/merge-callbacks.test.ts @@ -0,0 +1,119 @@ +import { describe, expect, it, vi } from "vitest"; +import type { PipelineCallbackFields } from "./merge-callbacks.js"; +import { + mergeExperimentCallbacks, + mergeLoopCallbacks, + mergePipelineCallbacks +} from "./merge-callbacks.js"; + +describe("mergePipelineCallbacks", () => { + it("runs user callbacks before added callbacks", () => { + const calls: string[] = []; + const merged = mergePipelineCallbacks( + { onTaskStart: () => calls.push("user") }, + { onTaskStart: () => calls.push("added") } + ); + + merged?.onTaskStart?.({ + taskId: "task-1", + taskTitle: "Task 1", + stepName: "Build", + taskIndex: 0, + totalTasks: 1 + }); + + expect(calls).toEqual(["user", "added"]); + }); + + it("propagates user callback errors without running the added callback", () => { + const error = new Error("user failed"); + const added = vi.fn(); + const merged = mergePipelineCallbacks( + { + onTaskComplete: () => { + throw error; + } + }, + { onTaskComplete: added } + ); + + expect(() => + merged?.onTaskComplete?.({ + taskId: "task-1", + taskTitle: "Task 1", + stepName: "Build", + taskIndex: 0, + totalTasks: 1, + durationMs: 1, + success: true + }) + ).toThrow(error); + expect(added).not.toHaveBeenCalled(); + }); + + it("swallows added callback errors and warns once with the callback name", () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const merged = mergePipelineCallbacks( + { onPlanResolved: vi.fn() }, + { + onPlanResolved: () => { + throw new Error("added failed"); + } + } + ); + + expect(() => + merged?.onPlanResolved?.({ + planPath: "/tmp/plan.md", + done: 0, + failed: 0, + open: 1, + total: 1 + }) + ).not.toThrow(); + expect(warn).toHaveBeenCalledTimes(1); + expect(warn.mock.calls[0]?.[0]).toContain("onPlanResolved"); + + warn.mockRestore(); + }); + + it("uses only-user and only-added callbacks directly", () => { + const onlyUser: PipelineCallbackFields["onTaskStart"] = vi.fn(); + const onlyAdded: PipelineCallbackFields["onTaskComplete"] = vi.fn(); + + const merged = mergePipelineCallbacks( + { onTaskStart: onlyUser }, + { onTaskComplete: onlyAdded } + ); + + expect(merged?.onTaskStart).toBe(onlyUser); + expect(merged?.onTaskComplete).toBe(onlyAdded); + }); +}); + +describe("mergeExperimentCallbacks", () => { + it("runs user callbacks before added callbacks", () => { + const calls: string[] = []; + const merged = mergeExperimentCallbacks( + { onExperimentStart: () => calls.push("user") }, + { onExperimentStart: () => calls.push("added") } + ); + + merged?.onExperimentStart?.(1, "codex"); + + expect(calls).toEqual(["user", "added"]); + }); +}); + +describe("mergeLoopCallbacks", () => { + it("preserves user return values while still running added callbacks", () => { + const added = vi.fn(); + const merged = mergeLoopCallbacks( + { shouldPause: () => true }, + { shouldPause: added } + ); + + expect(merged?.shouldPause?.()).toBe(true); + expect(added).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/poe-code-config/src/merge-callbacks.ts b/packages/poe-code-config/src/merge-callbacks.ts new file mode 100644 index 0000000000..521e8fd636 --- /dev/null +++ b/packages/poe-code-config/src/merge-callbacks.ts @@ -0,0 +1,103 @@ +type BivariantCallback = { + callback(...args: Args): Return; +}["callback"]; + +export type PipelineCallbackFields = { + onPlanResolved?: BivariantCallback<[summary: unknown]>; + onTaskStart?: BivariantCallback<[progress: unknown]>; + onTaskComplete?: BivariantCallback<[progress: unknown]>; + onLockStatusChange?: BivariantCallback<[status: unknown]>; +}; + +export type ExperimentCallbackFields = { + onExperimentStart?: BivariantCallback<[index: number, agent: string]>; + onBaselineCollected?: BivariantCallback<[baseline: Record]>; + onMetricResult?: BivariantCallback<[metric: unknown, result: unknown]>; + onCommit?: BivariantCallback<[commitHash: string]>; + onReset?: BivariantCallback<[targetHash: string]>; + onExperimentComplete?: BivariantCallback<[index: number, entry: unknown]>; +}; + +export type LoopCallbacks = { + onBuilderStart?: () => void; + onBuilderComplete?: BivariantCallback<[result: unknown]>; + onBuilderFailed?: BivariantCallback<[error: Error]>; + onInspectorStart?: BivariantCallback<[name: string]>; + onInspectorComplete?: BivariantCallback<[result: unknown]>; + onInspectorFailed?: BivariantCallback<[name: string, error: Error]>; + onSuperintendentStart?: () => void; + onSuperintendentComplete?: BivariantCallback<[result: unknown]>; + onOwnerStart?: () => void; + onOwnerComplete?: BivariantCallback<[result: unknown]>; + onRoundComplete?: BivariantCallback<[round: number]>; + onLoopComplete?: BivariantCallback<[state: unknown]>; + onStateChange?: BivariantCallback<[state: unknown]>; + shouldPause?: () => boolean; + shouldStop?: () => boolean; +}; + +type Callback = (this: unknown, ...args: never[]) => unknown; +type CallbackFields = Record; + +export function mergePipelineCallbacks( + user: PipelineCallbackFields | undefined, + added: PipelineCallbackFields | undefined +): PipelineCallbackFields | undefined { + return mergeCallbacks(user, added); +} + +export function mergeExperimentCallbacks( + user: ExperimentCallbackFields | undefined, + added: ExperimentCallbackFields | undefined +): ExperimentCallbackFields | undefined { + return mergeCallbacks(user, added); +} + +export function mergeLoopCallbacks( + user: LoopCallbacks | undefined, + added: LoopCallbacks | undefined +): LoopCallbacks | undefined { + return mergeCallbacks(user, added); +} + +function mergeCallbacks( + user: T | undefined, + added: T | undefined +): T | undefined { + if (!user) { + return added; + } + + if (!added) { + return user; + } + + const userCallbacks = user as unknown as CallbackFields; + const addedCallbacks = added as unknown as CallbackFields; + const result: CallbackFields = {}; + const keys = new Set([...Object.keys(user), ...Object.keys(added)]); + + for (const key of keys) { + const userCallback = userCallbacks[key]; + const addedCallback = addedCallbacks[key]; + + if (userCallback && addedCallback) { + result[key] = function mergedCallback(this: unknown, ...args: never[]) { + const userResult = userCallback.apply(this, args); + + try { + addedCallback.apply(this, args); + } catch (error) { + console.warn(`Added callback ${key} failed`, error); + } + + return userResult; + }; + continue; + } + + result[key] = userCallback ?? addedCallback; + } + + return result as unknown as T; +} diff --git a/packages/poe-code-config/src/poe-code-config.test.ts b/packages/poe-code-config/src/poe-code-config.test.ts index b8247044b0..2e7113e45a 100644 --- a/packages/poe-code-config/src/poe-code-config.test.ts +++ b/packages/poe-code-config/src/poe-code-config.test.ts @@ -11,7 +11,7 @@ import { saveAgentModel, saveDefaultModel } from "./models.js"; -import { planConfigScope } from "./index.js"; +import { integrationsConfigScope, planConfigScope } from "./index.js"; import { resolveScope } from "./resolve.js"; import { defineScope } from "./schema.js"; import { readDocument, readMergedDocument, resolveProjectConfigPath, writeScope } from "./store.js"; @@ -317,6 +317,75 @@ describe("planConfigScope", () => { }); }); +describe("integrationsConfigScope", () => { + it("parses a config with no integrations block", async () => { + const fs = createMockFs( + { + "~/.poe-code/config.json": `${JSON.stringify({ + models: { + default: "anthropic/claude-sonnet-4.6" + } + })}\n` + }, + homeDir + ); + + const document = await readDocument(fs, configPath); + + expect(resolveScope(integrationsConfigScope.schema, document.integrations)).toEqual({ + braintrust: { + enabled: false + } + }); + }); + + it("parses disabled Braintrust config without apiKey or project", async () => { + const fs = createMockFs( + { + "~/.poe-code/config.json": `${JSON.stringify({ + integrations: { + braintrust: { + enabled: false + } + } + })}\n` + }, + homeDir + ); + + const document = await readDocument(fs, configPath); + + expect(resolveScope(integrationsConfigScope.schema, document.integrations)).toEqual({ + braintrust: { + enabled: false + } + }); + }); + + it("parses enabled Braintrust config without cross-field validation", async () => { + const fs = createMockFs( + { + "~/.poe-code/config.json": `${JSON.stringify({ + integrations: { + braintrust: { + enabled: true + } + } + })}\n` + }, + homeDir + ); + + const document = await readDocument(fs, configPath); + + expect(resolveScope(integrationsConfigScope.schema, document.integrations)).toEqual({ + braintrust: { + enabled: true + } + }); + }); +}); + function parseNullablePluginEntries( value: unknown ): Array<{ name: string; options?: unknown }> | null { diff --git a/packages/poe-code-config/src/schema.ts b/packages/poe-code-config/src/schema.ts index 6a78cdf57f..33d7828e07 100644 --- a/packages/poe-code-config/src/schema.ts +++ b/packages/poe-code-config/src/schema.ts @@ -1,4 +1,8 @@ -import type { ScopeDefinition, ScopeSchema } from "./types.js"; +import type { + BraintrustIntegrationConfig, + ScopeDefinition, + ScopeSchema +} from "./types.js"; export function defineScope( scope: string, @@ -10,4 +14,49 @@ export function defineScope( }; } +export const integrationsConfigScope = defineScope("integrations", { + braintrust: { + type: "json", + default: { + enabled: false + } satisfies BraintrustIntegrationConfig, + parse: parseBraintrustIntegrationConfig, + doc: "Braintrust integration configuration" + } +}); + export { runtimeConfigScope } from "./runtime.js"; + +function parseBraintrustIntegrationConfig(value: unknown): BraintrustIntegrationConfig { + if (!isRecord(value)) { + throw new Error("expected an object"); + } + + const enabled = value.enabled === undefined ? false : value.enabled; + if (typeof enabled !== "boolean") { + throw new Error("enabled must be a boolean"); + } + + return { + enabled, + ...optionalStringEntry("apiKey", value.apiKey), + ...optionalStringEntry("apiUrl", value.apiUrl), + ...optionalStringEntry("project", value.project) + }; +} + +function optionalStringEntry(key: string, value: unknown): Record { + if (value === undefined) { + return {}; + } + + if (typeof value !== "string") { + throw new Error(`${key} must be a string`); + } + + return { [key]: value }; +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} diff --git a/packages/poe-code-config/src/types.ts b/packages/poe-code-config/src/types.ts index 8ff2ebf82a..bac0b94a53 100644 --- a/packages/poe-code-config/src/types.ts +++ b/packages/poe-code-config/src/types.ts @@ -76,6 +76,17 @@ export interface MemoryConfig extends Record { query?: MemoryQueryConfig; } +export interface BraintrustIntegrationConfig extends Record { + enabled: boolean; + apiKey?: string; + apiUrl?: string; + project?: string; +} + +export interface IntegrationsConfig extends Record { + braintrust?: BraintrustIntegrationConfig; +} + export interface ScopedConfig { get(key: K): Promise[K]>; getAll(): Promise>; @@ -94,6 +105,7 @@ export interface ConfigStoreOptions { } export type ConfigDocument = Record> & { + integrations?: IntegrationsConfig; memory?: MemoryConfig; runtime?: Record; }; diff --git a/packages/superintendent/src/commands/run.test.ts b/packages/superintendent/src/commands/run.test.ts index 5c3fbef1cf..bb6524ff69 100644 --- a/packages/superintendent/src/commands/run.test.ts +++ b/packages/superintendent/src/commands/run.test.ts @@ -660,7 +660,8 @@ describe("superintendent run command", () => { await dispatch(0); }); const renderAcpStreamMock = vi.fn(async (events: AsyncIterable) => { - for await (const _event of events) { + for await (const ignoredEvent of events) { + void ignoredEvent; // exhaust stream } }); @@ -912,6 +913,58 @@ describe("superintendent run command", () => { }); }); + it("runs integration superintendent callbacks after dashboard callbacks", async () => { + const fs = createFs({ + "/repo/docs/plans/plan.md": createDoc("claude-code") + }); + const calls: string[] = []; + const dashboardMock = createDashboardMock(); + dashboardMock.appendOutput.mockImplementation((entry: { text?: string }) => { + if (entry.text?.includes("Builder starting")) { + calls.push("dashboard"); + } + }); + const runLoopMock = vi.fn(async (options: RunLoopOptions) => { + options.callbacks?.onBuilderStart?.(); + return { + state: "completed" as const, + round: 1, + reviewTurn: 0, + maxRounds: 100, + maxReviewTurns: 5, + stopReason: "completed" as const + }; + }); + + const { runSuperintendentCommand } = await import("./run.js"); + await runSuperintendentCommand({ + cwd: "/repo", + homeDir: "/home/test", + docPath: "/repo/docs/plans/plan.md", + assumeYes: true, + interactive: true, + useDashboard: true, + fs, + createDashboard: () => dashboardMock.dashboard, + runLoop: runLoopMock, + now: () => 0, + setInterval: (() => 0) as typeof global.setInterval, + clearInterval: vi.fn(), + openInEditor: vi.fn(), + env: {}, + stderr: { write: () => true } as NodeJS.WritableStream, + integrations: { + superintendentCallbacks: { + onBuilderStart: () => calls.push("integration") + }, + traceRun: async (_surface, _name, run) => run(), + shutdown: vi.fn(async () => undefined) + } + }); + + expect(calls).toEqual(["dashboard", "integration"]); + }); + it("streams agent stdout and stderr lines into the dashboard output", async () => { const fs = createFs({ "/repo/docs/plans/plan.md": createDoc("codex") diff --git a/packages/superintendent/src/commands/run.ts b/packages/superintendent/src/commands/run.ts index e0afd30db5..052c739be0 100644 --- a/packages/superintendent/src/commands/run.ts +++ b/packages/superintendent/src/commands/run.ts @@ -33,10 +33,14 @@ import { } from "@poe-code/design-system"; import { planConfigScope, + loadIntegrations, + mergeLoopCallbacks, readMergedDocument, resolveConfigPath, resolveProjectConfigPath, - resolveScope + resolveScope, + type ConfigDocument, + type Integrations } from "@poe-code/poe-code-config"; import { superintendentConfigScope } from "../config-scope.js"; import { parseSuperintendentDoc, readExplicitBuilderAgent } from "../document/parse.js"; @@ -95,6 +99,7 @@ export type RunCommandOptions = { openInEditor?: (absolutePath: string, env: Record) => void; stderr?: NodeJS.WritableStream; exit?: (code: number) => never; + integrations?: Integrations | null; }; type OutputKind = "info" | "success" | "error" | "tool" | "status"; @@ -151,25 +156,36 @@ export const runCommand = defineCommand({ const cwd = process.cwd(); const homeDir = process.env.HOME ?? process.env.USERPROFILE ?? cwd; const commandConfig = await resolveSuperintendentCommandConfig(cwd, homeDir, process.env); + const integrations = await loadIntegrations(commandConfig.configDoc); const tuiEnabled = params.tui ?? commandConfig.tui; - return runSuperintendentCommand({ - cwd, - homeDir, - docPath: params.doc, - ...(params.agent ? { builderAgent: params.agent } : {}), - ...(params.runtime ? { runtime: params.runtime } : {}), - ...(params.runtimeImage ? { runtimeImage: params.runtimeImage } : {}), - ...(params.runtimeTemplate ? { runtimeTemplate: params.runtimeTemplate } : {}), - ...(params.detach ? { detach: params.detach } : {}), - ...(params.mountPoeCode ? { mountPoeCode: params.mountPoeCode } : {}), - configuredDefaultAgent: commandConfig.configuredDefaultAgent, - assumeYes: process.argv.includes("--yes"), - interactive: Boolean(process.stdin.isTTY), - useDashboard: shouldUseInteractiveDashboard(tuiEnabled) && resolveOutputFormat() === "terminal", - env: process.env, - ...(commandConfig.planDirectory ? { planDirectory: commandConfig.planDirectory } : {}) - }); + try { + const runOptions: RunCommandOptions = { + cwd, + homeDir, + docPath: params.doc, + ...(params.agent ? { builderAgent: params.agent } : {}), + ...(params.runtime ? { runtime: params.runtime } : {}), + ...(params.runtimeImage ? { runtimeImage: params.runtimeImage } : {}), + ...(params.runtimeTemplate ? { runtimeTemplate: params.runtimeTemplate } : {}), + ...(params.detach ? { detach: params.detach } : {}), + ...(params.mountPoeCode ? { mountPoeCode: params.mountPoeCode } : {}), + configuredDefaultAgent: commandConfig.configuredDefaultAgent, + assumeYes: process.argv.includes("--yes"), + interactive: Boolean(process.stdin.isTTY), + useDashboard: shouldUseInteractiveDashboard(tuiEnabled) && resolveOutputFormat() === "terminal", + env: process.env, + integrations, + ...(commandConfig.planDirectory ? { planDirectory: commandConfig.planDirectory } : {}) + }; + return integrations + ? await integrations.traceRun("superintendent", params.doc ?? "run", () => + runSuperintendentCommand(runOptions) + ) + : await runSuperintendentCommand(runOptions); + } finally { + await integrations?.shutdown(); + } }, render: { rich: (result, { logger }) => { @@ -216,25 +232,36 @@ export function createRunMcpCommand(runners?: RunMcpCommandRunners) { const cwd = process.cwd(); const homeDir = process.env.HOME ?? process.env.USERPROFILE ?? cwd; const commandConfig = await resolveSuperintendentCommandConfig(cwd, homeDir, process.env); - - return runSuperintendentCommand({ - cwd, - homeDir, - docPath: params.doc, - ...(params.agent ? { builderAgent: params.agent } : {}), - ...(params.runtime ? { runtime: params.runtime } : {}), - ...(params.runtimeImage ? { runtimeImage: params.runtimeImage } : {}), - ...(params.runtimeTemplate ? { runtimeTemplate: params.runtimeTemplate } : {}), - ...(params.detach ? { detach: params.detach } : {}), - ...(params.mountPoeCode ? { mountPoeCode: params.mountPoeCode } : {}), - configuredDefaultAgent: commandConfig.configuredDefaultAgent, - assumeYes: true, - interactive: false, - useDashboard: false, - env: process.env, - ...(commandConfig.planDirectory ? { planDirectory: commandConfig.planDirectory } : {}), - ...(runners?.runLoop ? { runLoop: runners.runLoop } : {}) - }); + const integrations = await loadIntegrations(commandConfig.configDoc); + + try { + const runOptions: RunCommandOptions = { + cwd, + homeDir, + docPath: params.doc, + ...(params.agent ? { builderAgent: params.agent } : {}), + ...(params.runtime ? { runtime: params.runtime } : {}), + ...(params.runtimeImage ? { runtimeImage: params.runtimeImage } : {}), + ...(params.runtimeTemplate ? { runtimeTemplate: params.runtimeTemplate } : {}), + ...(params.detach ? { detach: params.detach } : {}), + ...(params.mountPoeCode ? { mountPoeCode: params.mountPoeCode } : {}), + configuredDefaultAgent: commandConfig.configuredDefaultAgent, + assumeYes: true, + interactive: false, + useDashboard: false, + env: process.env, + integrations, + ...(commandConfig.planDirectory ? { planDirectory: commandConfig.planDirectory } : {}), + ...(runners?.runLoop ? { runLoop: runners.runLoop } : {}) + }; + return integrations + ? await integrations.traceRun("superintendent", params.doc ?? "run", () => + runSuperintendentCommand(runOptions) + ) + : await runSuperintendentCommand(runOptions); + } finally { + await integrations?.shutdown(); + } }, render: runCommand.render }); @@ -247,7 +274,12 @@ async function resolveSuperintendentCommandConfig( homeDir: string, env: Record, fs?: SuperintendentFileSystem -): Promise<{ configuredDefaultAgent: string | null; planDirectory?: string; tui: boolean }> { +): Promise<{ + configDoc: ConfigDocument; + configuredDefaultAgent: string | null; + planDirectory?: string; + tui: boolean; +}> { const configPath = resolveConfigPath(homeDir); const projectConfigPath = resolveProjectConfigPath(cwd); try { @@ -264,12 +296,13 @@ async function resolveSuperintendentCommandConfig( ); const coreResolved = resolveScope(coreDefaultAgentConfigSchema, document.core, env); return { + configDoc: document, configuredDefaultAgent: normalizeAgentSelection(coreResolved.defaultAgent) ?? null, ...(planDirectory ? { planDirectory } : {}), tui: superintendentResolved.tui === true }; } catch { - return { configuredDefaultAgent: null, tui: false }; + return { configDoc: {}, configuredDefaultAgent: null, tui: false }; } } @@ -346,6 +379,16 @@ export async function runSuperintendentCommand( const useDashboard = options.useDashboard ?? resolveOutputFormat() === "terminal"; const stderr = options.stderr ?? process.stderr; const exitProcess = options.exit ?? ((code: number) => process.exit(code)); + const integrations = options.integrations ?? null; + const shutdownAndExit = (code: number): void => { + if (!integrations) { + exitProcess(code); + return; + } + void integrations.shutdown().finally(() => { + exitProcess(code); + }); + }; const selectedDocPath = await resolveDocPath({ cwd: options.cwd, @@ -390,7 +433,7 @@ export async function runSuperintendentCommand( const headlessAbort = new AbortController(); const headlessSigint = () => { headlessAbort.abort(); - exitProcess(130); + shutdownAndExit(130); }; process.on("SIGINT", headlessSigint); try { @@ -401,7 +444,7 @@ export async function runSuperintendentCommand( ...(options.fs ? { fs } : {}), signal: headlessAbort.signal, logDir: runLogDir, - callbacks: { + callbacks: mergeLoopCallbacks({ onBuilderStart: () => { activeStage = "builder"; }, @@ -432,11 +475,12 @@ export async function runSuperintendentCommand( onOwnerComplete: () => { activeStage = undefined; } - }, + }, integrations?.superintendentCallbacks), runAgent: createAgentRunner({ session: undefined, executeAgent: options.executeAgent, selectedBuilderAgent, + integrations, runtime: { runtime: options.runtime, runtimeImage: options.runtimeImage, @@ -615,7 +659,7 @@ export async function runSuperintendentCommand( abortController.abort(); session.dashboard.stop(); session.dashboard.destroy(); - exitProcess(130); + shutdownAndExit(130); }; const handleDashboardCommand = (command: string) => { @@ -699,13 +743,14 @@ export async function runSuperintendentCommand( cwd: options.cwd, homeDir: options.homeDir, ...(options.fs ? { fs } : {}), - callbacks, + callbacks: mergeLoopCallbacks(callbacks, integrations?.superintendentCallbacks), signal: abortController.signal, logDir: runLogDir, runAgent: createAgentRunner({ session, executeAgent: options.executeAgent, selectedBuilderAgent, + integrations, runtime: { runtime: options.runtime, runtimeImage: options.runtimeImage, @@ -908,6 +953,7 @@ function createAgentRunner(options: { session: RunSession | undefined; executeAgent: RunCommandOptions["executeAgent"]; selectedBuilderAgent: string; + integrations: Integrations | null; runtime: Pick< RunCommandOptions, "runtime" | "runtimeImage" | "runtimeTemplate" | "detach" | "mountPoeCode" @@ -919,7 +965,9 @@ function createAgentRunner(options: { return async (input) => { const activeStage = options.activeStage(); const agent = activeStage === "builder" ? options.selectedBuilderAgent : input.agent; - const executeAgent = options.executeAgent ?? executeSpawnAgent; + const executeAgent = options.executeAgent ?? + ((nextAgent: string, nextInput: AgentRunInput) => + executeSpawnAgent(nextAgent, nextInput, options.integrations)); const stageLabel = formatStageLabel(activeStage); const emitLine = (kind: OutputKind, line: string) => { @@ -1003,7 +1051,8 @@ function formatStageLabel(stage: RunSession["activeStage"]): string { async function executeSpawnAgent( agent: string, - input: AgentRunInput + input: AgentRunInput, + integrations: Integrations | null ): Promise< AgentRunResult & { usage?: { inputTokens: number; outputTokens: number; cachedTokens?: number }; @@ -1014,7 +1063,7 @@ async function executeSpawnAgent( } if ((input.onStdout || input.onStderr) && supportsStreaming(agent)) { - return executeSpawnAgentStreaming(agent, input); + return executeSpawnAgentStreaming(agent, input, integrations); } const tee = @@ -1057,7 +1106,8 @@ function supportsStreaming(agent: string): boolean { async function executeSpawnAgentStreaming( agent: string, - input: AgentRunInput + input: AgentRunInput, + integrations: Integrations | null ): Promise< AgentRunResult & { usage?: { inputTokens: number; outputTokens: number; cachedTokens?: number }; @@ -1096,7 +1146,15 @@ async function executeSpawnAgentStreaming( ...(input.mode ? { mode: input.mode as "read" | "edit" | "yolo" } : {}) }; - await applyMiddlewares([spawnLog, usageCapture, sessionCapture], middlewareContext); + await applyMiddlewares( + [ + spawnLog, + usageCapture, + sessionCapture, + ...(integrations?.spawnMiddleware ? [integrations.spawnMiddleware] : []) + ], + middlewareContext + ); await acp.withAcpWriter(writer, () => renderAcpStream(middlewareContext.eventStream ?? rawEvents)); const final = await done; diff --git a/src/cli/commands/braintrust-command.test.ts b/src/cli/commands/braintrust-command.test.ts new file mode 100644 index 0000000000..a38fd5066d --- /dev/null +++ b/src/cli/commands/braintrust-command.test.ts @@ -0,0 +1,173 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { Volume, createFsFromVolume } from "memfs"; +import { resolveConfigPath } from "@poe-code/poe-code-config"; +import { createProgram } from "../program.js"; +import type { FileSystem } from "../utils/file-system.js"; + +const braintrustMock = vi.hoisted(() => ({ + bootstrap: vi.fn(), + shutdown: vi.fn() +})); + +vi.mock("@poe-code/braintrust", () => ({ + bootstrap: braintrustMock.bootstrap +})); + +const cwd = "/repo"; +const homeDir = "/home/test"; +const configPath = resolveConfigPath(homeDir); + +function createMemFs(): FileSystem { + const volume = new Volume(); + volume.mkdirSync(`${homeDir}/.poe-code`, { recursive: true }); + volume.mkdirSync(`${cwd}/.poe-code`, { recursive: true }); + return createFsFromVolume(volume).promises as unknown as FileSystem; +} + +async function writeConfig(fs: FileSystem, document: unknown): Promise { + await fs.writeFile(configPath, `${JSON.stringify(document, null, 2)}\n`, "utf8"); +} + +async function runBraintrustStatus(fs: FileSystem): Promise { + const logs: string[] = []; + const program = createProgram({ + fs, + prompts: vi.fn(), + env: { cwd, homeDir }, + logger: (message) => logs.push(message) + }); + vi.spyOn(program, "optsWithGlobals").mockReturnValue({ yes: false, dryRun: false } as any); + + await program.parseAsync(["node", "cli", "braintrust", "status"]); + return logs; +} + +describe("braintrust command", () => { + let fs: FileSystem; + + beforeEach(() => { + fs = createMemFs(); + braintrustMock.bootstrap.mockReset(); + braintrustMock.shutdown.mockReset(); + }); + + it("prints disabled when Braintrust config is absent", async () => { + const logs = await runBraintrustStatus(fs); + + expect(logs).toContain("disabled"); + expect(braintrustMock.bootstrap).not.toHaveBeenCalled(); + }); + + it("prints disabled when Braintrust config is disabled", async () => { + await writeConfig(fs, { + integrations: { + braintrust: { + enabled: false + } + } + }); + + const logs = await runBraintrustStatus(fs); + + expect(logs).toContain("disabled"); + expect(braintrustMock.bootstrap).not.toHaveBeenCalled(); + }); + + it("prints one line per missing required field without bootstrapping", async () => { + await writeConfig(fs, { + integrations: { + braintrust: { + enabled: true + } + } + }); + + const logs = await runBraintrustStatus(fs); + + expect(logs).toContain("missing apiKey"); + expect(logs).toContain("missing project"); + expect(braintrustMock.bootstrap).not.toHaveBeenCalled(); + }); + + it("prints peer install guidance when bootstrap reports the Braintrust SDK is missing", async () => { + await writeConfig(fs, { + integrations: { + braintrust: { + enabled: true, + apiKey: "key", + project: "poe-code" + } + } + }); + braintrustMock.bootstrap.mockRejectedValue( + new Error( + "Braintrust integration is enabled but the 'braintrust' package is not installed. Run: npm i braintrust" + ) + ); + + const logs = await runBraintrustStatus(fs); + + expect(logs).toContain("not installed: run npm i braintrust"); + }); + + it("bootstraps configured Braintrust and shuts it down before exit", async () => { + await writeConfig(fs, { + integrations: { + braintrust: { + enabled: true, + apiKey: "key", + project: "poe-code" + } + } + }); + braintrustMock.bootstrap.mockResolvedValue({ + status: () => ({ + project: "poe-code", + lastError: "flush failed", + errorCount: 2 + }), + shutdown: braintrustMock.shutdown + }); + + const logs = await runBraintrustStatus(fs); + + expect(braintrustMock.bootstrap).toHaveBeenCalledWith( + expect.objectContaining({ + integrations: { + braintrust: { + enabled: true, + apiKey: "key", + project: "poe-code" + } + } + }) + ); + expect(logs).toContain("enabled, project=poe-code, last error: flush failed, errors: 2"); + expect(braintrustMock.shutdown).toHaveBeenCalledOnce(); + }); + + it("prints none for an enabled configured integration with no last error", async () => { + await writeConfig(fs, { + integrations: { + braintrust: { + enabled: true, + apiKey: "key", + project: "poe-code" + } + } + }); + braintrustMock.bootstrap.mockResolvedValue({ + status: () => ({ + project: "poe-code", + lastError: null, + errorCount: 0 + }), + shutdown: braintrustMock.shutdown + }); + + const logs = await runBraintrustStatus(fs); + + expect(logs).toContain("enabled, project=poe-code, last error: none, errors: 0"); + expect(braintrustMock.shutdown).toHaveBeenCalledOnce(); + }); +}); diff --git a/src/cli/commands/braintrust.ts b/src/cli/commands/braintrust.ts new file mode 100644 index 0000000000..4063f66499 --- /dev/null +++ b/src/cli/commands/braintrust.ts @@ -0,0 +1,118 @@ +import type { Command } from "commander"; +import type { ConfigDocument } from "@poe-code/poe-code-config"; +import type { CliContainer } from "../container.js"; +import { + createExecutionResources, + resolveCommandFlags, + resolveMergedDocument +} from "./shared.js"; + +interface BraintrustStatus { + project: string; + lastError: string | null; + errorCount: number; +} + +interface BraintrustIntegrations { + status(): BraintrustStatus; + shutdown(): Promise; +} + +interface BraintrustModule { + bootstrap(config: ConfigDocument): Promise; +} + +const BRAINTRUST_INSTALL_ERROR = + "Braintrust integration is enabled but the 'braintrust' package is not installed. Run: npm i braintrust"; + +export function registerBraintrustCommand(program: Command, container: CliContainer): void { + const braintrust = program + .command("braintrust") + .description("Inspect Braintrust integration status."); + + braintrust + .command("status") + .description("Show Braintrust integration status.") + .action(async () => { + await executeBraintrustStatus(program, container); + }); +} + +async function executeBraintrustStatus( + program: Command, + container: CliContainer +): Promise { + const flags = resolveCommandFlags(program); + const resources = createExecutionResources(container, flags, "braintrust:status"); + const config = await resolveMergedDocument(container); + const braintrust = config.integrations?.braintrust; + + resources.logger.intro("braintrust status"); + + if (braintrust?.enabled !== true) { + resources.logger.info("disabled"); + resources.context.finalize(); + return; + } + + const missing = missingBraintrustFields(braintrust); + if (missing.length > 0) { + for (const field of missing) { + resources.logger.info(`missing ${field}`); + } + resources.context.finalize(); + return; + } + + let integrations: BraintrustIntegrations | null = null; + try { + const { bootstrap } = await importBraintrustModule(); + integrations = await bootstrap(config); + + if (integrations === null) { + resources.logger.info("disabled"); + resources.context.finalize(); + return; + } + + const status = integrations.status(); + resources.logger.info( + `enabled, project=${status.project}, last error: ${status.lastError ?? "none"}, errors: ${status.errorCount}` + ); + resources.context.finalize(); + } catch (error) { + if (isBraintrustInstallError(error)) { + resources.logger.info("not installed: run npm i braintrust"); + resources.context.finalize(); + return; + } + throw error; + } finally { + await integrations?.shutdown(); + } +} + +function missingBraintrustFields( + braintrust: Record +): Array<"apiKey" | "project"> { + const missing: Array<"apiKey" | "project"> = []; + if (!hasNonEmptyString(braintrust.apiKey)) { + missing.push("apiKey"); + } + if (!hasNonEmptyString(braintrust.project)) { + missing.push("project"); + } + return missing; +} + +function hasNonEmptyString(value: unknown): value is string { + return typeof value === "string" && value.trim().length > 0; +} + +async function importBraintrustModule(): Promise { + return await import("@poe-code/braintrust") as BraintrustModule; +} + +function isBraintrustInstallError(error: unknown): boolean { + return error instanceof Error && error.message === BRAINTRUST_INSTALL_ERROR; +} diff --git a/src/cli/commands/experiment-ralph.test.ts b/src/cli/commands/experiment-ralph.test.ts index 784f1fe77b..280c593fee 100644 --- a/src/cli/commands/experiment-ralph.test.ts +++ b/src/cli/commands/experiment-ralph.test.ts @@ -722,6 +722,71 @@ describe("experiment run command", () => { expect(dashboardMock.destroy).toHaveBeenCalledTimes(1); }); + it("runs integration experiment callbacks after CLI callbacks when enabled", async () => { + const calls: string[] = []; + vi.doMock("@poe-code/braintrust", () => ({ + bootstrap: vi.fn(async () => ({ + experimentCallbacks: { + onExperimentStart: () => calls.push("integration") + }, + traceRun: async (_surface: string, _name: string, fn: () => Promise) => fn(), + shutdown: vi.fn(async () => undefined) + })) + })); + vi.mocked(sdkRunExperiment).mockImplementationOnce(async (options) => { + options.onExperimentStart?.(1, "codex"); + return { + stopReason: "max_experiments", + docPath: options.docPath, + experimentsCompleted: 1, + experimentsKept: 0, + totalDurationMs: 1_000 + }; + }); + + const container = createCliContainer({ + fs: createMemFs({ + [`${homeDir}/.poe-code/config.json`]: JSON.stringify({ + integrations: { + braintrust: { + enabled: true, + apiKey: "key", + project: "project" + } + } + }), + "/repo/docs/loop.md": "# Loop" + }), + prompts: vi.fn().mockResolvedValue({}), + env: { cwd, homeDir }, + logger: (message) => { + if (message === "Experiment 1 (codex)") { + calls.push("cli"); + } + } + }); + const program = createBaseProgram(); + registerExperimentCommand(program, container); + + await program.parseAsync([ + "node", + "cli", + "--yes", + "experiment", + "run", + "docs/loop.md", + "--agent", + "codex", + "--max-experiments", + "1", + "--no-tui" + ]); + + expect(calls).toEqual(["cli", "integration"]); + + vi.doUnmock("@poe-code/braintrust"); + }); + it("uses the experiment.tui config value when set", async () => { vi.useFakeTimers(); vi.setSystemTime(new Date(0)); diff --git a/src/cli/commands/experiment.ts b/src/cli/commands/experiment.ts index fb1aa39bde..d9b96f8078 100644 --- a/src/cli/commands/experiment.ts +++ b/src/cli/commands/experiment.ts @@ -31,6 +31,7 @@ import { } from "@poe-code/agent-skill-config"; import { discoverExperimentDocs, parseExperimentFrontmatter } from "@poe-code/experiment-loop"; import type { ExperimentFrontmatter } from "@poe-code/experiment-loop"; +import type { AcpMiddleware } from "@poe-code/agent-spawn"; import type { CliContainer } from "../container.js"; import { ValidationError } from "../errors.js"; import { createExecutionResources, resolveCommandFlags, resolveDefaultAgent } from "./shared.js"; @@ -41,7 +42,14 @@ import { } from "../../sdk/experiment.js"; import { spawn as sdkSpawn } from "../../sdk/spawn.js"; import { experimentConfigScope, planConfigScope } from "../../services/config.js"; -import { readMergedDocument, resolveScope } from "@poe-code/poe-code-config"; +import { + loadIntegrations, + mergeExperimentCallbacks, + readMergedDocument, + resolveScope, + type ConfigDocument, + type Integrations +} from "@poe-code/poe-code-config"; import type { ExperimentRunOptions } from "@poe-code/experiment-loop"; import { createDashboardLineBuffer, @@ -69,6 +77,7 @@ type ExperimentDashboardRunOptions = { maxExperiments?: number; runOptions: Parameters[0]; runtimeOptions: RuntimeCliOptions; + integrations?: Integrations; }; function resolveExperimentPaths( @@ -241,6 +250,7 @@ function createExperimentDashboardRunAgent(options: { appendOutput: (kind: "tool" | "error", message: string) => void; activeStage: () => string; runtimeOptions: RuntimeCliOptions; + middlewares?: AcpMiddleware[]; }): NonNullable { return async (input) => { const errorBuffer = createDashboardLineBuffer((line) => { @@ -260,6 +270,7 @@ function createExperimentDashboardRunAgent(options: { mode: "yolo", ...options.runtimeOptions, ...(input.signal ? { signal: input.signal } : {}), + ...(options.middlewares ? { middlewares: options.middlewares } : {}), useStdin: true, tee: { stderr: { @@ -280,6 +291,22 @@ function createExperimentDashboardRunAgent(options: { }; } +function createExperimentCliRunAgent(options: { + runtimeOptions: RuntimeCliOptions; + middlewares: AcpMiddleware[]; +}): NonNullable { + return async (input) => + sdkSpawn.autonomous(input.agent, { + prompt: input.prompt, + cwd: input.cwd, + model: input.model, + mode: "yolo", + ...options.runtimeOptions, + ...(input.signal ? { signal: input.signal } : {}), + middlewares: options.middlewares + }); +} + async function runExperimentWithDashboard( options: ExperimentDashboardRunOptions ): Promise>> { @@ -353,11 +380,14 @@ async function runExperimentWithDashboard( const runAgent = createExperimentDashboardRunAgent({ appendOutput, activeStage: () => formatExperimentStageLabel(currentExperimentIndex), - runtimeOptions: options.runtimeOptions + runtimeOptions: options.runtimeOptions, + ...(options.integrations?.spawnMiddleware + ? { middlewares: [options.integrations.spawnMiddleware] } + : {}) }); try { - const result = await sdkRunExperiment({ + const runOptions: Parameters[0] = { ...options.runOptions, signal: abortController.signal, runAgent, @@ -397,7 +427,15 @@ async function runExperimentWithDashboard( ); syncStats(); } - }); + }; + const result = await runExperimentWithIntegrations( + options.integrations, + options.docPath, + { + ...runOptions, + ...mergeExperimentCallbacks(runOptions, options.integrations?.experimentCallbacks) + } + ); status = "done"; iterations = result.experimentsCompleted; @@ -417,6 +455,15 @@ async function runExperimentWithDashboard( } } +async function runExperimentWithIntegrations( + integrations: Integrations | null | undefined, + name: string, + options: Parameters[0] +): Promise>> { + return integrations?.traceRun("experiment", name, () => sdkRunExperiment(options)) ?? + sdkRunExperiment(options); +} + function resolveExperimentAgent(value: string | undefined, sourceLabel = "agent"): string { if (!value || value.trim().length === 0) { return DEFAULT_EXPERIMENT_AGENT; @@ -451,6 +498,7 @@ function parseNonNegativeInt(value: string | undefined, fieldName: string): numb } async function resolveExperimentCommandConfig(container: CliContainer): Promise<{ + configDoc: ConfigDocument; planDirectory: string; tui: boolean; }> { @@ -470,6 +518,7 @@ async function resolveExperimentCommandConfig(container: CliContainer): Promise< container.env.variables ); return { + configDoc, planDirectory: planConfig.plan_directory, tui: experimentConfig.tui === true }; @@ -636,8 +685,10 @@ export function registerExperimentCommand(program: Command, container: CliContai resources.logger.intro("experiment run"); + let integrations: Integrations | null = null; try { const commandConfig = await resolveExperimentCommandConfig(container); + integrations = await loadIntegrations(commandConfig.configDoc); const docPath = await resolveDocPath({ container, program, @@ -700,6 +751,12 @@ export function registerExperimentCommand(program: Command, container: CliContai ); } }; + if (integrations?.spawnMiddleware) { + runOptions.runAgent = createExperimentCliRunAgent({ + runtimeOptions, + middlewares: [integrations.spawnMiddleware] + }); + } const useDashboard = shouldUseInteractiveDashboard(options.tui ?? commandConfig.tui); const result = useDashboard ? await runExperimentWithDashboard({ @@ -707,9 +764,17 @@ export function registerExperimentCommand(program: Command, container: CliContai docPath, maxExperiments, runOptions, - runtimeOptions + runtimeOptions, + ...(integrations ? { integrations } : {}) }) - : await sdkRunExperiment(runOptions); + : await runExperimentWithIntegrations( + integrations, + docPath, + { + ...runOptions, + ...mergeExperimentCallbacks(runOptions, integrations?.experimentCallbacks) + } + ); const summary = [ `Experiments: ${result.experimentsCompleted}`, @@ -728,6 +793,7 @@ export function registerExperimentCommand(program: Command, container: CliContai resources.logger.resolved("Run summary", summary); resources.logger.success("Experiment run finished."); } finally { + await integrations?.shutdown(); resources.context.finalize(); } }); diff --git a/src/cli/commands/pipeline-command.test.ts b/src/cli/commands/pipeline-command.test.ts index 955ca4ab74..8edf76c095 100644 --- a/src/cli/commands/pipeline-command.test.ts +++ b/src/cli/commands/pipeline-command.test.ts @@ -221,6 +221,82 @@ describe("pipeline run command", () => { ); }); + it("runs integration pipeline callbacks after CLI callbacks when enabled", async () => { + const calls: string[] = []; + vi.doMock("@poe-code/braintrust", () => ({ + bootstrap: vi.fn(async () => ({ + pipelineCallbacks: { + onTaskStart: () => calls.push("integration") + }, + traceRun: async (_surface: string, _name: string, fn: () => Promise) => fn(), + shutdown: vi.fn(async () => undefined) + })) + })); + vi.mocked(sdkRunPipeline).mockImplementationOnce(async (options) => { + options.onTaskStart?.({ + taskId: "task-1", + taskTitle: "Task 1", + taskIndex: 1, + totalTasks: 1 + }); + return { + stopReason: "completed", + planPath: "custom-plan.yaml", + runsCompleted: 1, + totalDurationMs: 1_000, + metrics: { + totalInputTokens: 0, + totalOutputTokens: 0, + totalCachedTokens: 0, + tasksCompleted: 1, + tasksFailed: 0, + stepsCompleted: 1 + } + }; + }); + + const fs = createMemFs({ + [`${homeDir}/.poe-code/config.json`]: JSON.stringify({ + integrations: { + braintrust: { + enabled: true, + apiKey: "key", + project: "project" + } + } + }) + }); + await fs.writeFile("/repo/custom-plan.yaml", "tasks: []\n", { encoding: "utf8" }); + const container = createCliContainer({ + fs, + prompts: vi.fn().mockResolvedValue({}), + env: { cwd, homeDir }, + logger: (message) => { + if (message.startsWith("Task 1")) { + calls.push("cli"); + } + } + }); + const program = createBaseProgram(); + registerPipelineCommand(program, container); + + await program.parseAsync([ + "node", + "cli", + "--yes", + "pipeline", + "run", + "--plan", + "custom-plan.yaml", + "--agent", + "codex" + ]); + + expect(calls).toEqual(["cli", "integration"]); + + vi.doUnmock("@poe-code/braintrust"); + }); + it("reads plan.plan_directory for pipeline discovery", async () => { const fs = createMemFs(); await fs.mkdir(`${homeDir}/.poe-code`, { recursive: true }); diff --git a/src/cli/commands/pipeline.ts b/src/cli/commands/pipeline.ts index c671cf06c5..3d6ebd9c24 100644 --- a/src/cli/commands/pipeline.ts +++ b/src/cli/commands/pipeline.ts @@ -17,14 +17,21 @@ import { formatAgentSpecifier, allAgents } from "@poe-code/agent-defs"; -import { renderAcpEvent, type AcpEvent } from "@poe-code/agent-spawn"; +import { renderAcpEvent, type AcpEvent, type AcpMiddleware } from "@poe-code/agent-spawn"; import { skillPlanConfigSection } from "@poe-code/agent-harness-tools"; import { installSkill, resolveAgentSupport, type SkillScope } from "@poe-code/agent-skill-config"; -import { readMergedDocument, resolveScope } from "@poe-code/poe-code-config"; +import { + loadIntegrations, + mergePipelineCallbacks, + readMergedDocument, + resolveScope, + type ConfigDocument, + type Integrations +} from "@poe-code/poe-code-config"; import type { CliContainer } from "../container.js"; import { pipelineConfigScope, planConfigScope } from "../../services/config.js"; import { ValidationError } from "../errors.js"; @@ -36,6 +43,7 @@ import { runPipeline as sdkRunPipeline, type AgentRunUsage, type PipelineInitSource, + type PipelineLockStatus, type PipelineRunOptions, type PipelineRunResult, type PlanSummary, @@ -64,6 +72,7 @@ import { } from "./dashboard-loop-shared.js"; async function resolvePipelineCommandConfig(container: CliContainer): Promise<{ + configDoc: ConfigDocument; planDirectory: string; tui: boolean; }> { @@ -94,6 +103,7 @@ async function resolvePipelineCommandConfig(container: CliContainer): Promise<{ const planDirectory: string = typeof yamlPlanDirectory === "string" ? yamlPlanDirectory : globalPlanDirectory; return { + configDoc, planDirectory, tui: pipelineConfig.tui === true }; @@ -124,6 +134,7 @@ type PipelineDashboardRunOptions = { planIndex: number; totalPlans: number; runOptions: PipelineRunOptions; + integrations?: Integrations; }; function resolvePipelineAgent(value: string | undefined): string { @@ -351,6 +362,7 @@ async function streamAcpEventsToDashboard(options: { function createPipelineDashboardRunAgent(options: { appendOutput: (kind: "tool" | "error", message: string) => void; activeStage: () => string; + middlewares?: AcpMiddleware[]; }): NonNullable { return async (input) => { const toolBuffer = createDashboardLineBuffer((line) => { @@ -373,6 +385,7 @@ function createPipelineDashboardRunAgent(options: { mode: input.mode, ...(input.mcpServers ? { mcpServers: input.mcpServers } : {}), ...(input.signal ? { signal: input.signal } : {}), + ...(options.middlewares ? { middlewares: options.middlewares } : {}), tee: { stdout: { write(chunk: string) { @@ -429,6 +442,22 @@ function createPipelineDashboardRunAgent(options: { }; } +function createPipelineCliRunAgent( + middlewares: AcpMiddleware[] +): NonNullable { + return async (input) => + sdkSpawn.autonomous(input.agent, { + prompt: input.prompt, + cwd: input.cwd, + logDir: input.logDir, + model: input.model, + mode: input.mode, + ...(input.mcpServers ? { mcpServers: input.mcpServers } : {}), + ...(input.signal ? { signal: input.signal } : {}), + middlewares + }); +} + function dashboardStatusForResult(result: PipelineRunResult): "done" | "error" { return result.stopReason === "failed" ? "error" : "done"; } @@ -508,11 +537,14 @@ async function runPipelineWithDashboard( process.on("SIGINT", sigintHandler); try { - const result = await sdkRunPipeline({ + const runOptions: PipelineRunOptions = { ...options.runOptions, runAgent: createPipelineDashboardRunAgent({ appendOutput, - activeStage: () => currentStage + activeStage: () => currentStage, + ...(options.integrations?.spawnMiddleware + ? { middlewares: [options.integrations.spawnMiddleware] } + : {}) }), signal: abortController.signal, onPlanReloadError(error: Error) { @@ -560,7 +592,15 @@ async function runPipelineWithDashboard( appendOutput(progress.success ? "success" : "error", formatTaskCompleteMessage(progress)); syncStats(); } - }); + }; + const result = await runPipelineWithIntegrations( + options.integrations, + options.planPath, + { + ...runOptions, + ...mergePipelineCallbacks(runOptions, options.integrations?.pipelineCallbacks) + } + ); status = dashboardStatusForResult(result); syncStats(); @@ -579,6 +619,15 @@ async function runPipelineWithDashboard( } } +async function runPipelineWithIntegrations( + integrations: Integrations | null | undefined, + name: string, + options: PipelineRunOptions +): Promise { + return integrations?.traceRun("pipeline", name, () => sdkRunPipeline(options)) ?? + sdkRunPipeline(options); +} + function resolvePipelinePaths( scope: SkillScope, cwd: string, @@ -710,6 +759,7 @@ export function registerPipelineCommand(program: Command, container: CliContaine resources.logger.intro("pipeline run"); + let integrations: Integrations | null = null; try { const selectedAgent = await resolvePipelineLoopAgent({ providedAgent: options.agent, @@ -727,6 +777,7 @@ export function registerPipelineCommand(program: Command, container: CliContaine const agent = resolvePipelineAgent(selectedAgent.agent); const commandConfig = await resolvePipelineCommandConfig(container); + integrations = await loadIntegrations(commandConfig.configDoc); const maxRuns = resolveMaxRuns(options.maxRuns); if (options.plan && options.plans && options.plans.length > 0) { @@ -786,6 +837,9 @@ export function registerPipelineCommand(program: Command, container: CliContaine ...(maxRuns != null ? { maxRuns } : {}), assumeYes: flags.assumeYes }; + if (integrations?.spawnMiddleware) { + runOptions.runAgent = createPipelineCliRunAgent([integrations.spawnMiddleware]); + } const useDashboard = shouldUseInteractiveDashboard(options.tui ?? commandConfig.tui); const result = useDashboard @@ -795,38 +849,48 @@ export function registerPipelineCommand(program: Command, container: CliContaine planPath, planIndex: index, totalPlans, - runOptions + runOptions, + ...(integrations ? { integrations } : {}) }) - : await sdkRunPipeline({ - ...runOptions, - onPlanReloadError(error: Error) { - resources.logger.warn( - `Plan reload failed, using last good state: ${error.message}` - ); - }, - onLockStatusChange(lockStatus) { - resources.logger.info(lockStatus.message); - }, - onPlanResolved(summary: PlanSummary) { - resources.logger.resolved( - "Config", - formatPipelineConfigSummary({ - agent, - model: options.model, - planPath: summary.planPath, - planIndex: index, - totalPlans - }).replaceAll(" · ", "\n ") - ); - resources.logger.resolved("Tasks", formatPipelineTasksSummary(summary)); - }, - onTaskStart(progress: TaskProgress) { - resources.logger.info(formatTaskStartMessage(progress)); - }, - onTaskComplete(progress: TaskCompletion) { - resources.logger.info(formatTaskCompleteMessage(progress)); + : await runPipelineWithIntegrations( + integrations, + planPath, + { + ...runOptions, + onPlanReloadError(error: Error) { + resources.logger.warn( + `Plan reload failed, using last good state: ${error.message}` + ); + }, + ...mergePipelineCallbacks( + { + onLockStatusChange(lockStatus: PipelineLockStatus) { + resources.logger.info(lockStatus.message); + }, + onPlanResolved(summary: PlanSummary) { + resources.logger.resolved( + "Config", + formatPipelineConfigSummary({ + agent, + model: options.model, + planPath: summary.planPath, + planIndex: index, + totalPlans + }).replaceAll(" · ", "\n ") + ); + resources.logger.resolved("Tasks", formatPipelineTasksSummary(summary)); + }, + onTaskStart(progress: TaskProgress) { + resources.logger.info(formatTaskStartMessage(progress)); + }, + onTaskComplete(progress: TaskCompletion) { + resources.logger.info(formatTaskCompleteMessage(progress)); + } + }, + integrations?.pipelineCallbacks + ) } - }); + ); const summary = formatRunSummary(result); @@ -865,6 +929,7 @@ export function registerPipelineCommand(program: Command, container: CliContaine planPaths.length > 1 ? "Pipeline sequence finished." : "Pipeline run finished." ); } finally { + await integrations?.shutdown(); resources.context.finalize(); } }); diff --git a/src/cli/commands/spawn-command.test.ts b/src/cli/commands/spawn-command.test.ts index a2f88e6645..0b26f3db1a 100644 --- a/src/cli/commands/spawn-command.test.ts +++ b/src/cli/commands/spawn-command.test.ts @@ -5,6 +5,7 @@ import { resolveConfigPath } from "@poe-code/poe-code-config"; import { Readable } from "node:stream"; import { Command } from "commander"; import { resetOutputFormatCache } from "@poe-code/design-system"; +import type { AcpMiddleware } from "@poe-code/agent-spawn"; import { DEFAULT_CLAUDE_CODE_MODEL, DEFAULT_CODEX_MODEL, @@ -345,6 +346,70 @@ describe("spawn command", () => { ); }); + it("wraps spawn runs with enabled integrations and passes spawn middleware", async () => { + const calls: string[] = []; + const spawnMiddleware: AcpMiddleware = vi.fn(async (_ctx, next) => { + calls.push("middleware"); + await next(); + }); + const traceRun = vi.fn(async (_surface: string, _name: string, run: () => Promise) => { + calls.push("trace:start"); + const result = await run(); + calls.push("trace:end"); + return result; + }); + const shutdown = vi.fn(async () => { + calls.push("shutdown"); + }); + + vi.doMock("@poe-code/braintrust", () => ({ + bootstrap: vi.fn(async () => ({ + spawnMiddleware, + traceRun, + shutdown + })) + })); + vi.mocked(sdkSpawn).mockImplementation((_service, options) => { + calls.push("spawn"); + expect(options.middlewares).toEqual([spawnMiddleware]); + return { + events: emptyAsyncIterable(), + result: Promise.resolve({ stdout: "", stderr: "", exitCode: 0 }) + }; + }); + await fs.writeFile( + resolveConfigPath(homeDir), + `${JSON.stringify({ + integrations: { + braintrust: { + enabled: true, + apiKey: "key", + project: "project" + } + } + })}\n`, + { encoding: "utf8" } + ); + + const { runner } = createCommandRunnerStub(); + const program = createProgram({ + fs, + prompts: vi.fn().mockResolvedValue({}), + env: { cwd, homeDir }, + commandRunner: runner, + logger: () => {} + }); + + try { + await program.parseAsync(["node", "cli", "--yes", "spawn", "codex", "hello"]); + + expect(traceRun).toHaveBeenCalledWith("spawn", "codex", expect.any(Function)); + expect(calls).toEqual(["trace:start", "spawn", "trace:end", "shutdown"]); + } finally { + vi.doUnmock("@poe-code/braintrust"); + } + }); + it("emits ACP NDJSON plus a final spawn_result event in json mode", async () => { process.env.OUTPUT_FORMAT = "json"; resetOutputFormatCache(); diff --git a/src/cli/commands/spawn.ts b/src/cli/commands/spawn.ts index d34ea96211..22c3996042 100644 --- a/src/cli/commands/spawn.ts +++ b/src/cli/commands/spawn.ts @@ -26,9 +26,11 @@ import { resolveServiceAdapter, formatServiceList, buildResumeCommand, + resolveMergedDocument, type CommandFlags, type ExecutionResources } from "./shared.js"; +import { loadIntegrations, type Integrations } from "@poe-code/poe-code-config"; import type { SpawnCommandOptions } from "../../providers/spawn-options.js"; import { resolveConfiguredModel, spawnCore } from "../../sdk/spawn-core.js"; import { spawn as spawnSdk } from "../../sdk/spawn.js"; @@ -111,6 +113,7 @@ export function registerSpawnCommand( activityTimeoutMs?: number; } & RuntimeCliOptions>(); const runtimeOptions = pickRuntimeOptions(commandOptions); + let integrations: Integrations | null = null; const shouldEmitUiOutput = resolveOutputFormat() !== "json"; const rawMcpInput = commandOptions.mcpServers ?? commandOptions.mcpConfig; const mcpInput = await resolveMcpSpawnInput(rawMcpInput, container.fs, container.env.cwd); @@ -160,6 +163,7 @@ export function registerSpawnCommand( const cwdOverride = workspace.cwd; try { + integrations = await loadIntegrations(await resolveMergedDocument(container)); if (commandOptions.interactive) { const adapter = resolveServiceAdapter(container, service); const canonicalService = adapter.name; @@ -200,6 +204,9 @@ export function registerSpawnCommand( cwd: cwdOverride, logDir: commandOptions.logDir, activityTimeoutMs: commandOptions.activityTimeoutMs, + ...(integrations?.spawnMiddleware + ? { middlewares: [integrations.spawnMiddleware] } + : {}), ...runtimeOptions, useStdin: shouldReadFromStdin }; @@ -285,20 +292,23 @@ export function registerSpawnCommand( return; } - const final = await spawnAutonomous(spawnSdk, { - service: canonicalService, - prompt: spawnOptions.prompt, - args: spawnOptions.args, - model: spawnOptions.model, - mode: spawnOptions.mode, - cwd: spawnOptions.cwd, - ...(spawnOptions.mcpServers ? { mcpServers: spawnOptions.mcpServers } : {}), - ...(spawnOptions.logDir !== undefined ? { logDir: spawnOptions.logDir } : {}), - ...(spawnOptions.activityTimeoutMs !== undefined - ? { activityTimeoutMs: spawnOptions.activityTimeoutMs } - : {}), - ...runtimeOptions - }); + const final = await traceSpawnRun(integrations, canonicalService, () => + spawnAutonomous(spawnSdk, { + service: canonicalService, + prompt: spawnOptions.prompt, + args: spawnOptions.args, + model: spawnOptions.model, + mode: spawnOptions.mode, + cwd: spawnOptions.cwd, + ...(spawnOptions.mcpServers ? { mcpServers: spawnOptions.mcpServers } : {}), + ...(spawnOptions.logDir !== undefined ? { logDir: spawnOptions.logDir } : {}), + ...(spawnOptions.activityTimeoutMs !== undefined + ? { activityTimeoutMs: spawnOptions.activityTimeoutMs } + : {}), + ...(spawnOptions.middlewares ? { middlewares: spawnOptions.middlewares } : {}), + ...runtimeOptions + }) + ); process.exitCode = final.exitCode; if (shouldEmitUiOutput && final.detached) { @@ -356,11 +366,20 @@ export function registerSpawnCommand( } } } finally { + await integrations?.shutdown(); await workspace.cleanup?.(); } }); } +async function traceSpawnRun( + integrations: Integrations | null, + name: string, + run: () => Promise +): Promise { + return integrations?.traceRun("spawn", name, run) ?? run(); +} + function formatDetachedJob(detached: { jobId: string; envId: string }): string { return `job started: ${detached.jobId}\nsandbox: ${detached.envId}\ndetached.`; } diff --git a/src/cli/program.ts b/src/cli/program.ts index 6f8328831c..29e66406ba 100644 --- a/src/cli/program.ts +++ b/src/cli/program.ts @@ -33,6 +33,7 @@ import { registerMemoryCommand } from "./commands/memory.js"; import { registerProviderCommand } from "./commands/provider.js"; import { registerRuntimeCommand } from "./commands/runtime/index.js"; import { registerHarnessCommand } from "./commands/harness.js"; +import { registerBraintrustCommand } from "./commands/braintrust.js"; import packageJson from "../../package.json" with { type: "json" }; import { throwCommandNotFound } from "./command-not-found.js"; import { @@ -94,6 +95,7 @@ const ROOT_HELP_COMMAND_SPECS: readonly RootHelpCommandSpec[] = [ { path: ["provider", "list"] }, { path: ["provider", "login"], args: "" }, { path: ["provider", "logout"], args: "" }, + { path: ["braintrust", "status"] }, { path: ["runtime", "init"] }, { path: ["runtime", "build"] }, { path: ["runtime", "templates", "ls"] }, @@ -492,6 +494,7 @@ function bootstrapProgram(container: CliContainer): Command { registerProviderCommand(program, container); registerRuntimeCommand(program, container); registerHarnessCommand(program, container); + registerBraintrustCommand(program, container); registerForwardedToolcraftCommand( program, container, diff --git a/src/providers/spawn-options.ts b/src/providers/spawn-options.ts index a7053e1209..237aea01bd 100644 --- a/src/providers/spawn-options.ts +++ b/src/providers/spawn-options.ts @@ -1,4 +1,4 @@ -import type { McpSpawnConfig, SpawnMode } from "@poe-code/agent-spawn"; +import type { AcpMiddleware, McpSpawnConfig, SpawnMode } from "@poe-code/agent-spawn"; import type { RuntimeOverrideOptions } from "@poe-code/agent-harness-tools"; export interface SpawnCommandOptions { @@ -9,6 +9,7 @@ export interface SpawnCommandOptions { mcpServers?: McpSpawnConfig; logDir?: string; activityTimeoutMs?: number; + middlewares?: AcpMiddleware[]; cwd?: string; useStdin?: boolean; interactive?: boolean; diff --git a/src/sdk/spawn.test.ts b/src/sdk/spawn.test.ts index dd759b4bdc..f40592a21f 100644 --- a/src/sdk/spawn.test.ts +++ b/src/sdk/spawn.test.ts @@ -953,6 +953,31 @@ describe("SDK spawn()", () => { expect(ctx.logDir).toBe("/repo/.poe-code/pipeline/plans/logs/task-1-implement.jsonl"); }); + it("appends user middlewares after built-in streaming middlewares", async () => { + vi.mocked(getSpawnConfig).mockReturnValue({ + kind: "cli", + agentId: "codex", + adapter: "codex" + } as any); + + vi.mocked(spawnStreaming).mockImplementation(() => ({ + events: (async function* () {})(), + done: Promise.resolve({ stdout: "", stderr: "", exitCode: 0 }) + })); + + const extraMiddleware = vi.fn(); + const { result } = spawn("codex", "test prompt", { + middlewares: [extraMiddleware] + }); + + await result; + + expect(applyMiddlewares).toHaveBeenCalledWith( + [sessionCapture, usageCapture, spawnLog, extraMiddleware], + expect.any(Object) + ); + }); + it("forwards an explicitly empty logDir to middleware context", async () => { vi.mocked(getSpawnConfig).mockReturnValue({ kind: "cli", diff --git a/src/sdk/spawn.ts b/src/sdk/spawn.ts index dcf6362837..54ea948051 100644 --- a/src/sdk/spawn.ts +++ b/src/sdk/spawn.ts @@ -187,7 +187,10 @@ export function spawn( startedAt: new Date() }; - await applyMiddlewares([sessionCapture, usageCapture, spawnLog], middlewareContext); + await applyMiddlewares( + [sessionCapture, usageCapture, spawnLog, ...(options.middlewares ?? [])], + middlewareContext + ); resolveEventsOnce(middlewareContext.eventStream ?? emptyEvents); const final = await done; @@ -247,7 +250,10 @@ export function spawn( startedAt: new Date() }; - await applyMiddlewares([sessionCapture, usageCapture, spawnLog], middlewareContext); + await applyMiddlewares( + [sessionCapture, usageCapture, spawnLog, ...(options.middlewares ?? [])], + middlewareContext + ); resolveEventsOnce(middlewareContext.eventStream ?? emptyEvents); const final = await done; diff --git a/src/sdk/types.ts b/src/sdk/types.ts index 1a1b83bf32..23c7396f9d 100644 --- a/src/sdk/types.ts +++ b/src/sdk/types.ts @@ -1,5 +1,10 @@ import type { RuntimeOverrideOptions } from "@poe-code/agent-harness-tools"; -import type { McpSpawnConfig, SessionResult, SpawnMode } from "@poe-code/agent-spawn"; +import type { + AcpMiddleware, + McpSpawnConfig, + SessionResult, + SpawnMode +} from "@poe-code/agent-spawn"; /** * Options for spawning a provider CLI. @@ -23,6 +28,8 @@ export interface SpawnOptions { logDir?: string; /** Filename override for the spawn log. Requires `logDir`. */ logFileName?: string; + /** Additional ACP middlewares appended to the spawn capture chain. */ + middlewares?: AcpMiddleware[]; /** Launch the agent in interactive (TUI) mode with inherited stdio */ interactive?: boolean; /** Abort signal used to terminate the spawned agent */ From 2bac5a14c93fb45f603f171c04ed9dee5cbb5ad7 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 01:43:44 -0500 Subject: [PATCH 061/111] feat(runner-e2b): support sandbox workspace directory --- docs/plans/braintrust-integration.md.lock | 1 - docs/plans/e2b-runtime-spawn-fixes.md | 4 +- docs/plans/e2b-runtime-spawn-fixes.md.lock | 1 + packages/poe-code-config/src/runtime.test.ts | 8 + packages/poe-code-config/src/runtime.ts | 19 ++ packages/runner-e2b/README.md | 2 + .../src/e2b-execution-env.integration.ts | 4 +- packages/runner-e2b/src/factory.ts | 2 + packages/runner-e2b/src/opened-env.test.ts | 206 +++++++++++++++++- packages/runner-e2b/src/opened-env.ts | 48 +++- 10 files changed, 274 insertions(+), 21 deletions(-) delete mode 100644 docs/plans/braintrust-integration.md.lock create mode 100644 docs/plans/e2b-runtime-spawn-fixes.md.lock diff --git a/docs/plans/braintrust-integration.md.lock b/docs/plans/braintrust-integration.md.lock deleted file mode 100644 index 47cfe31803..0000000000 --- a/docs/plans/braintrust-integration.md.lock +++ /dev/null @@ -1 +0,0 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T06:32:27.846Z"} \ No newline at end of file diff --git a/docs/plans/e2b-runtime-spawn-fixes.md b/docs/plans/e2b-runtime-spawn-fixes.md index 60b004cc7a..3d3d4a47bd 100644 --- a/docs/plans/e2b-runtime-spawn-fixes.md +++ b/docs/plans/e2b-runtime-spawn-fixes.md @@ -34,8 +34,8 @@ tasks: assertion that the sandbox path differs from the host cwd and uploads still round-trip. status: - implement: open - test: open + implement: done + test: done commit: open - id: runRemoteOrThrow-error-tail diff --git a/docs/plans/e2b-runtime-spawn-fixes.md.lock b/docs/plans/e2b-runtime-spawn-fixes.md.lock new file mode 100644 index 0000000000..d96d875289 --- /dev/null +++ b/docs/plans/e2b-runtime-spawn-fixes.md.lock @@ -0,0 +1 @@ +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T06:42:29.003Z"} \ No newline at end of file diff --git a/packages/poe-code-config/src/runtime.test.ts b/packages/poe-code-config/src/runtime.test.ts index 841262ebbc..0167a5a7da 100644 --- a/packages/poe-code-config/src/runtime.test.ts +++ b/packages/poe-code-config/src/runtime.test.ts @@ -150,6 +150,7 @@ describe("runtime config", () => { template_id: "tmpl_123", build_args: {}, mounts: [], + workspace_dir: "/workspace", preserve_after_exit_hours: 24 }); @@ -160,6 +161,7 @@ describe("runtime config", () => { cpu: 4, memory_mb: 8192, timeout_minutes: 60, + workspace_dir: "/sandbox/workspace/../project/", preserve_after_exit_hours: 168 }) ).toMatchObject({ @@ -167,12 +169,16 @@ describe("runtime config", () => { cpu: 4, memory_mb: 8192, timeout_minutes: 60, + workspace_dir: "/sandbox/project", preserve_after_exit_hours: 168 }); expect(() => parseRuntime({ type: "e2b", template_id: "tmpl_123", preserve_after_exit_hours: 169 }) ).toThrow("preserve_after_exit_hours: expected a number from 0 to 168"); + expect(() => + parseRuntime({ type: "e2b", template_id: "tmpl_123", workspace_dir: "workspace" }) + ).toThrow("workspace_dir: expected an absolute sandbox path"); }); it("resolves dockerfile and build context defaults when a docker runtime builds from a Dockerfile", () => { @@ -276,6 +282,7 @@ describe("runtime config", () => { { type: "e2b", template_id: "tmpl_123", + workspace_dir: "/sandbox/workspace", preserve_after_exit_hours: 0 }, {} @@ -286,6 +293,7 @@ describe("runtime config", () => { template_id: "tmpl_123", build_args: {}, mounts: [], + workspace_dir: "/sandbox/workspace", preserve_after_exit_hours: 0 }); }); diff --git a/packages/poe-code-config/src/runtime.ts b/packages/poe-code-config/src/runtime.ts index 6ec3ab9c57..01c122605b 100644 --- a/packages/poe-code-config/src/runtime.ts +++ b/packages/poe-code-config/src/runtime.ts @@ -43,6 +43,7 @@ export interface E2bRuntime extends SharedRuntimeFields { from_template?: string; dockerfile?: string; build_context?: string; + workspace_dir?: string; cpu?: number; memory_mb?: number; timeout_minutes?: number; @@ -116,6 +117,11 @@ export const runtimeConfigScope = { default: "", doc: "Path to the Docker build context" }, + workspace_dir: { + type: "string", + default: "/workspace", + doc: "Sandbox-local workspace directory for E2B runtime upload, execution, and download" + }, engine: { type: "string", default: "", @@ -233,6 +239,7 @@ export function parseRuntime(raw: unknown): RuntimeConfig { from_template: parseOptionalString(record.from_template), dockerfile: parseOptionalString(record.dockerfile), build_context: parseOptionalString(record.build_context), + workspace_dir: parseWorkspaceDir(record.workspace_dir), cpu: parseOptionalNumber(record.cpu), memory_mb: parseOptionalNumber(record.memory_mb), timeout_minutes: parseOptionalNumber(record.timeout_minutes), @@ -340,6 +347,18 @@ function parseRuntimeType(value: unknown): RuntimeConfig["type"] { throw new Error('type: expected "host", "docker", or "e2b".'); } +function parseWorkspaceDir(value: unknown): string { + const workspaceDir = parseOptionalString(value) ?? "/workspace"; + if (!path.posix.isAbsolute(workspaceDir)) { + throw new Error("workspace_dir: expected an absolute sandbox path."); + } + let normalized = path.posix.normalize(workspaceDir); + while (normalized.length > 1 && normalized.endsWith("/")) { + normalized = normalized.slice(0, -1); + } + return normalized; +} + function createDefaultRunnerScope(): RunnerScope { return { detach: false, diff --git a/packages/runner-e2b/README.md b/packages/runner-e2b/README.md index 4d932cb199..79cfb1ba33 100644 --- a/packages/runner-e2b/README.md +++ b/packages/runner-e2b/README.md @@ -36,6 +36,7 @@ Use these options under the `runtime` config scope: - `build_context`: build context path. Defaults to the project root. - `build_args`: build argument object included in the template hash. - `mounts`: runtime mounts passed through the shared runtime config. +- `workspace_dir`: sandbox-local workspace directory used for upload, execution, and download. Defaults to `/workspace`. - `cpu`: CPU count used when building an E2B template. - `memory_mb`: memory in megabytes used when building an E2B template. - `timeout_minutes`: sandbox timeout in minutes. @@ -56,6 +57,7 @@ Example project config: "type": "e2b", "dockerfile": ".poe-code/Dockerfile", "build_context": ".", + "workspace_dir": "/workspace", "timeout_minutes": 60, "preserve_after_exit_hours": 24, "runner": { diff --git a/packages/runner-e2b/src/e2b-execution-env.integration.ts b/packages/runner-e2b/src/e2b-execution-env.integration.ts index e61e8b1e14..d90f2c82a1 100644 --- a/packages/runner-e2b/src/e2b-execution-env.integration.ts +++ b/packages/runner-e2b/src/e2b-execution-env.integration.ts @@ -24,16 +24,18 @@ describe.skipIf(!process.env.E2B_API_KEY)("e2bExecutionEnvFactory integration", }); try { + expect("/workspace").not.toBe(cwd); await env.uploadWorkspace(); const handle = env.exec({ command: "sh", - args: ["-c", "echo ok > e2b-output.txt"], + args: ["-c", "pwd > e2b-pwd.txt && echo ok > e2b-output.txt"], cwd }); await expect(handle.result).resolves.toEqual({ exitCode: 0 }); await expect(env.downloadWorkspace({ conflictPolicy: "overwrite" })).resolves.toMatchObject({ conflicts: [] }); + await expect(readFile(path.join(cwd, "e2b-pwd.txt"), "utf8")).resolves.toBe("/workspace\n"); await expect(readFile(path.join(cwd, "e2b-output.txt"), "utf8")).resolves.toBe("ok\n"); } finally { await env.close(); diff --git a/packages/runner-e2b/src/factory.ts b/packages/runner-e2b/src/factory.ts index a793014d1e..0825f890a3 100644 --- a/packages/runner-e2b/src/factory.ts +++ b/packages/runner-e2b/src/factory.ts @@ -47,6 +47,7 @@ export const e2bExecutionEnvFactory: ExecutionEnvFactory = { type: "e2b", build_args: {}, mounts: [], + workspace_dir: "/workspace", preserve_after_exit_hours: 24 }, env: {}, @@ -58,6 +59,7 @@ export const e2bExecutionEnvFactory: ExecutionEnvFactory = { type: "e2b", build_args: {}, mounts: [], + workspace_dir: "/workspace", preserve_after_exit_hours: 24 } }); diff --git a/packages/runner-e2b/src/opened-env.test.ts b/packages/runner-e2b/src/opened-env.test.ts index 31b3ddc48e..bbe52872ed 100644 --- a/packages/runner-e2b/src/opened-env.test.ts +++ b/packages/runner-e2b/src/opened-env.test.ts @@ -1,8 +1,35 @@ -import { describe, expect, it, vi } from "vitest"; +import { beforeEach, describe, expect, it, vi } from "vitest"; import { createOpenedE2bEnv } from "./opened-env.js"; +const fsMocks = vi.hoisted(() => ({ + mkdtempSync: vi.fn(), + rmSync: vi.fn(), + readFile: vi.fn(), + writeFile: vi.fn() +})); + +vi.mock("node:fs", async (importActual) => ({ + ...(await importActual()), + mkdtempSync: fsMocks.mkdtempSync, + rmSync: fsMocks.rmSync +})); + +vi.mock("node:fs/promises", async (importActual) => ({ + ...(await importActual()), + readFile: fsMocks.readFile, + writeFile: fsMocks.writeFile +})); + describe("createOpenedE2bEnv", () => { - it("executes commands with E2B command run and returns a RunHandle", async () => { + beforeEach(() => { + vi.clearAllMocks(); + fsMocks.mkdtempSync.mockImplementation((prefix: string) => `${prefix}test`); + fsMocks.rmSync.mockImplementation(() => undefined); + fsMocks.readFile.mockResolvedValue(Buffer.from("tar")); + fsMocks.writeFile.mockResolvedValue(undefined); + }); + + it("executes commands in the sandbox workspace when cwd is the host workspace", async () => { const commandHandle = { pid: 321, wait: vi.fn().mockResolvedValue({ exitCode: 0 }), @@ -12,7 +39,7 @@ describe("createOpenedE2bEnv", () => { sandbox.commands.run.mockResolvedValue(commandHandle); const env = createOpenedE2bEnv({ sandbox, - runtime: createRuntime(), + runtime: { ...createRuntime(), workspace_dir: "/sandbox/workspace" }, spec: createSpec() }); @@ -29,7 +56,7 @@ describe("createOpenedE2bEnv", () => { await expect(handle.result).resolves.toEqual({ exitCode: 0 }); expect(sandbox.commands.run).toHaveBeenCalledWith("'printf' 'ok'", { background: true, - cwd: "/repo", + cwd: "/sandbox/workspace", envs: { A: "1" }, stdin: true, onStdout: expect.any(Function), @@ -37,6 +64,159 @@ describe("createOpenedE2bEnv", () => { }); }); + it("leaves non-workspace command cwd values unchanged", async () => { + const commandHandle = { + pid: 321, + wait: vi.fn().mockResolvedValue({ exitCode: 0 }), + kill: vi.fn() + }; + const sandbox = createSandboxMock(); + sandbox.commands.run.mockResolvedValue(commandHandle); + const env = createOpenedE2bEnv({ + sandbox, + runtime: { ...createRuntime(), workspace_dir: "/sandbox/workspace" }, + spec: createSpec() + }); + + const handle = env.exec({ + command: "pwd", + cwd: "/tmp" + }); + + await expect(handle.result).resolves.toEqual({ exitCode: 0 }); + expect(sandbox.commands.run).toHaveBeenCalledWith("'pwd'", { + background: true, + cwd: "/tmp", + envs: undefined, + stdin: false, + onStdout: expect.any(Function), + onStderr: expect.any(Function) + }); + }); + + it("uses /workspace as the default sandbox workspace", async () => { + const commandHandle = { + pid: 321, + wait: vi.fn().mockResolvedValue({ exitCode: 0 }), + kill: vi.fn() + }; + const sandbox = createSandboxMock(); + sandbox.commands.run.mockResolvedValue(commandHandle); + const env = createOpenedE2bEnv({ + sandbox, + runtime: createRuntime(), + spec: createSpec() + }); + + const handle = env.exec({ + command: "pwd", + cwd: "/repo/." + }); + + await expect(handle.result).resolves.toEqual({ exitCode: 0 }); + expect(sandbox.commands.run).toHaveBeenCalledWith("'pwd'", { + background: true, + cwd: "/workspace", + envs: undefined, + stdin: false, + onStdout: expect.any(Function), + onStderr: expect.any(Function) + }); + }); + + it("normalizes configured sandbox workspace directories", async () => { + const commandHandle = { + pid: 321, + wait: vi.fn().mockResolvedValue({ exitCode: 0 }), + kill: vi.fn() + }; + const sandbox = createSandboxMock(); + sandbox.commands.run.mockResolvedValue(commandHandle); + const env = createOpenedE2bEnv({ + sandbox, + runtime: { ...createRuntime(), workspace_dir: "/sandbox/workspace/../project/" }, + spec: createSpec() + }); + + const handle = env.exec({ + command: "pwd", + cwd: "/repo" + }); + + await expect(handle.result).resolves.toEqual({ exitCode: 0 }); + expect(sandbox.commands.run).toHaveBeenCalledWith("'pwd'", { + background: true, + cwd: "/sandbox/project", + envs: undefined, + stdin: false, + onStdout: expect.any(Function), + onStderr: expect.any(Function) + }); + }); + + it("uploads the host workspace into the sandbox workspace", async () => { + const hostRunner = createHostRunnerMock(); + const sandbox = createSandboxMock(); + sandbox.commands.run.mockResolvedValue({ exitCode: 0 }); + const env = createOpenedE2bEnv({ + sandbox, + runtime: { ...createRuntime(), workspace_dir: "/sandbox/workspace" }, + spec: { ...createSpec(), hostRunner, uploadIgnoreFiles: ["node_modules"] } + }); + + await expect(env.uploadWorkspace()).resolves.toEqual({ files: 0, bytes: 0, skipped: [] }); + + expect(hostRunner.exec).toHaveBeenCalledWith({ + command: "tar", + args: [ + "--exclude", + "node_modules", + "-cf", + expect.stringContaining("poe-e2b-upload-test/workspace.tar"), + "-C", + "/repo", + "." + ], + stdout: "pipe", + stderr: "pipe" + }); + expect(sandbox.files.write).toHaveBeenCalledWith( + "/tmp/poe-workspace-upload.tar", + expect.any(ArrayBuffer) + ); + expect(sandbox.commands.run).toHaveBeenCalledWith( + "mkdir -p '/sandbox/workspace' && tar -xf /tmp/poe-workspace-upload.tar -C '/sandbox/workspace'" + ); + }); + + it("downloads the sandbox workspace back into the host workspace", async () => { + const hostRunner = createHostRunnerMock(); + const sandbox = createSandboxMock(); + sandbox.commands.run.mockResolvedValue({ exitCode: 0 }); + sandbox.files.read.mockResolvedValue(new Uint8Array(Buffer.from("tar"))); + const env = createOpenedE2bEnv({ + sandbox, + runtime: { ...createRuntime(), workspace_dir: "/sandbox/workspace" }, + spec: { ...createSpec(), hostRunner } + }); + + await expect(env.downloadWorkspace({ conflictPolicy: "overwrite" })).resolves.toEqual({ + files: 0, + bytes: 3, + conflicts: [] + }); + + expect(sandbox.commands.run).toHaveBeenCalledWith( + "tar -cf /tmp/poe-workspace-download.tar -C '/sandbox/workspace' ." + ); + expect(hostRunner.exec).toHaveBeenCalledWith({ + command: "tar", + args: ["-xf", expect.stringContaining("poe-e2b-download-test/workspace.tar"), "-C", "/repo"], + stdout: "pipe", + stderr: "pipe" + }); + }); + it("creates a job handle for the last running command and preserves sandbox timeout on wait", async () => { const commandHandle = { pid: 321, @@ -84,7 +264,7 @@ describe("createOpenedE2bEnv", () => { sandbox.pty.create.mockResolvedValue(ptyHandle); const env = createOpenedE2bEnv({ sandbox, - runtime: createRuntime(), + runtime: { ...createRuntime(), workspace_dir: "/sandbox/workspace" }, spec: createSpec() }); @@ -94,7 +274,7 @@ describe("createOpenedE2bEnv", () => { expect(sandbox.pty.create).toHaveBeenCalledWith({ cols: expect.any(Number), rows: expect.any(Number), - cwd: "/repo", + cwd: "/sandbox/workspace", envs: {}, onData: expect.any(Function) }); @@ -127,6 +307,20 @@ function createRuntime() { }; } +function createHostRunnerMock() { + return { + name: "host", + exec: vi.fn().mockReturnValue({ + pid: null, + stdin: null, + stdout: null, + stderr: null, + result: Promise.resolve({ exitCode: 0 }), + kill: vi.fn() + }) + }; +} + function createSpec() { return { cwd: "/repo", diff --git a/packages/runner-e2b/src/opened-env.ts b/packages/runner-e2b/src/opened-env.ts index 7081cc297e..929728803d 100644 --- a/packages/runner-e2b/src/opened-env.ts +++ b/packages/runner-e2b/src/opened-env.ts @@ -32,21 +32,32 @@ export function createOpenedE2bEnv(input: { runtime: E2bRuntime; }): E2bOpenedEnv { const hostRunner = input.spec.hostRunner ?? createHostRunner(); + const hostWorkspaceDir = path.resolve(input.spec.cwd); + const sandboxWorkspaceDir = normalizeSandboxWorkspaceDir(input.runtime.workspace_dir); let lastProcess: { started: Promise } | null = null; let detachedJobContext: DetachedJobContext | null = null; + const mapWorkspaceCwd = (cwd: string | undefined): string | undefined => { + if (cwd === undefined) { + return undefined; + } + if (path.isAbsolute(cwd) && path.resolve(cwd) === hostWorkspaceDir) { + return sandboxWorkspaceDir; + } + return cwd; + }; const attachedJobId = (input.spec as OpenSpec & { detachedJobId?: string }).detachedJobId; const env: E2bOpenedEnv = { id: input.sandbox.sandboxId, job: attachedJobId ? createE2bJobHandle({ - sandbox: input.sandbox, - envId: input.sandbox.sandboxId, - jobId: attachedJobId, - tool: input.spec.jobLabel.tool, - argv: input.spec.jobLabel.argv, - preserveAfterExitHours: input.runtime.preserve_after_exit_hours ?? 24 - }) + sandbox: input.sandbox, + envId: input.sandbox.sandboxId, + jobId: attachedJobId, + tool: input.spec.jobLabel.tool, + argv: input.spec.jobLabel.argv, + preserveAfterExitHours: input.runtime.preserve_after_exit_hours ?? 24 + }) : null, fs: createE2bLogStreamFs(input.sandbox), setDetachedJobContext(context) { @@ -75,7 +86,7 @@ export function createOpenedE2bEnv(input: { ); await runRemoteOrThrow( input.sandbox, - `mkdir -p ${shellQuote(input.spec.cwd)} && tar -xf /tmp/poe-workspace-upload.tar -C ${shellQuote(input.spec.cwd)}` + `mkdir -p ${shellQuote(sandboxWorkspaceDir)} && tar -xf /tmp/poe-workspace-upload.tar -C ${shellQuote(sandboxWorkspaceDir)}` ); return { files: 0, bytes: 0, skipped: [] }; } finally { @@ -88,7 +99,7 @@ export function createOpenedE2bEnv(input: { try { await runRemoteOrThrow( input.sandbox, - `tar -cf /tmp/poe-workspace-download.tar -C ${shellQuote(input.spec.cwd)} .` + `tar -cf /tmp/poe-workspace-download.tar -C ${shellQuote(sandboxWorkspaceDir)} .` ); const archive = await input.sandbox.files.read("/tmp/poe-workspace-download.tar", { format: "bytes" @@ -111,7 +122,10 @@ export function createOpenedE2bEnv(input: { } }, exec(spec) { - const handle = runE2bCommand(input.sandbox, spec); + const handle = runE2bCommand(input.sandbox, { + ...spec, + cwd: mapWorkspaceCwd(spec.cwd) + }); lastProcess = { started: handle.started }; return handle; }, @@ -144,7 +158,7 @@ export function createOpenedE2bEnv(input: { return runE2bPty(input.sandbox, { command, ...(shellSpec?.args ? { args: shellSpec.args } : {}), - cwd: input.spec.cwd, + cwd: mapWorkspaceCwd(shellSpec?.cwd ?? input.spec.cwd), env: shellSpec && "env" in shellSpec ? shellSpec.env : input.spec.env, stdin: "inherit", stdout: "inherit", @@ -328,6 +342,18 @@ function shellQuote(value: string): string { return `'${value.replaceAll("'", "'\\''")}'`; } +function normalizeSandboxWorkspaceDir(workspaceDir: string | undefined): string { + const resolvedWorkspaceDir = workspaceDir ?? "/workspace"; + if (!path.posix.isAbsolute(resolvedWorkspaceDir)) { + throw new Error("E2B runtime workspace_dir must be an absolute sandbox path."); + } + let normalized = path.posix.normalize(resolvedWorkspaceDir); + while (normalized.length > 1 && normalized.endsWith("/")) { + normalized = normalized.slice(0, -1); + } + return normalized; +} + function isExitError(error: unknown): error is { exitCode: number } { return Boolean( error && From 2b7729834721933ea2e652b744d9aca7558b49dc Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 01:48:24 -0500 Subject: [PATCH 062/111] fix: surface e2b command stderr failures --- docs/plans/e2b-runtime-spawn-fixes.md | 6 +- docs/plans/e2b-runtime-spawn-fixes.md.lock | 2 +- packages/runner-e2b/src/opened-env.test.ts | 83 +++++++++++++++- packages/runner-e2b/src/opened-env.ts | 107 ++++++++++++++++++++- 4 files changed, 189 insertions(+), 9 deletions(-) diff --git a/docs/plans/e2b-runtime-spawn-fixes.md b/docs/plans/e2b-runtime-spawn-fixes.md index 3d3d4a47bd..043ff6f04f 100644 --- a/docs/plans/e2b-runtime-spawn-fixes.md +++ b/docs/plans/e2b-runtime-spawn-fixes.md @@ -36,7 +36,7 @@ tasks: status: implement: done test: done - commit: open + commit: done - id: runRemoteOrThrow-error-tail title: Surface failing command and stderr from runRemoteOrThrow @@ -61,8 +61,8 @@ tasks: CommandExitError and asserts the rethrown message contains the command and stderr tail. status: - implement: open - test: open + implement: done + test: done commit: open - id: configure-on-spawn diff --git a/docs/plans/e2b-runtime-spawn-fixes.md.lock b/docs/plans/e2b-runtime-spawn-fixes.md.lock index d96d875289..91390123bc 100644 --- a/docs/plans/e2b-runtime-spawn-fixes.md.lock +++ b/docs/plans/e2b-runtime-spawn-fixes.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T06:42:29.003Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T06:47:32.101Z"} \ No newline at end of file diff --git a/packages/runner-e2b/src/opened-env.test.ts b/packages/runner-e2b/src/opened-env.test.ts index bbe52872ed..0bcb946ec2 100644 --- a/packages/runner-e2b/src/opened-env.test.ts +++ b/packages/runner-e2b/src/opened-env.test.ts @@ -185,8 +185,83 @@ describe("createOpenedE2bEnv", () => { expect.any(ArrayBuffer) ); expect(sandbox.commands.run).toHaveBeenCalledWith( - "mkdir -p '/sandbox/workspace' && tar -xf /tmp/poe-workspace-upload.tar -C '/sandbox/workspace'" + "mkdir -p '/sandbox/workspace' && tar -xf /tmp/poe-workspace-upload.tar -C '/sandbox/workspace'", + { + onStdout: expect.any(Function), + onStderr: expect.any(Function) + } + ); + }); + + it("decorates remote command exit errors with the command and stderr tail", async () => { + const hostRunner = createHostRunnerMock(); + const sandbox = createSandboxMock(); + sandbox.commands.run.mockImplementation( + async (_command: string, opts?: { onStderr?: (data: string) => void }) => { + for (let index = 1; index <= 35; index += 1) { + opts?.onStderr?.(`stderr line ${index}\n`); + } + throw Object.assign(new Error("exit status 1"), { + name: "CommandExitError", + exitCode: 1 + }); + } + ); + const env = createOpenedE2bEnv({ + sandbox, + runtime: { ...createRuntime(), workspace_dir: "/sandbox/workspace" }, + spec: { ...createSpec(), hostRunner } + }); + + let thrown: unknown; + try { + await env.uploadWorkspace(); + } catch (error) { + thrown = error; + } + + expect(thrown).toBeInstanceOf(Error); + const message = (thrown as Error).message; + expect(message).toContain( + "E2B command failed: mkdir -p '/sandbox/workspace' && tar -xf /tmp/poe-workspace-upload.tar -C '/sandbox/workspace'" ); + expect(message).toContain("Last stderr output:"); + expect(message).toContain("stderr line 6"); + expect(message).toContain("stderr line 35"); + expect(message).not.toContain("stderr line 5"); + }); + + it("uses stderr carried by remote command exit errors when callbacks do not receive output", async () => { + const hostRunner = createHostRunnerMock(); + const sandbox = createSandboxMock(); + sandbox.commands.run.mockRejectedValue( + Object.assign(new Error("exit status 1"), { + name: "CommandExitError", + exitCode: 1, + stderr: Array.from({ length: 35 }, (_value, index) => `error stderr ${index + 1}`).join( + "\n" + ) + }) + ); + const env = createOpenedE2bEnv({ + sandbox, + runtime: { ...createRuntime(), workspace_dir: "/sandbox/workspace" }, + spec: { ...createSpec(), hostRunner } + }); + + let thrown: unknown; + try { + await env.uploadWorkspace(); + } catch (error) { + thrown = error; + } + + expect(thrown).toBeInstanceOf(Error); + const message = (thrown as Error).message; + expect(message).toContain("E2B command failed: mkdir -p '/sandbox/workspace'"); + expect(message).toContain("error stderr 6"); + expect(message).toContain("error stderr 35"); + expect(message).not.toContain("error stderr 5"); }); it("downloads the sandbox workspace back into the host workspace", async () => { @@ -207,7 +282,11 @@ describe("createOpenedE2bEnv", () => { }); expect(sandbox.commands.run).toHaveBeenCalledWith( - "tar -cf /tmp/poe-workspace-download.tar -C '/sandbox/workspace' ." + "tar -cf /tmp/poe-workspace-download.tar -C '/sandbox/workspace' .", + { + onStdout: expect.any(Function), + onStderr: expect.any(Function) + } ); expect(hostRunner.exec).toHaveBeenCalledWith({ command: "tar", diff --git a/packages/runner-e2b/src/opened-env.ts b/packages/runner-e2b/src/opened-env.ts index 929728803d..7f5afb9436 100644 --- a/packages/runner-e2b/src/opened-env.ts +++ b/packages/runner-e2b/src/opened-env.ts @@ -13,7 +13,15 @@ import type { } from "@poe-code/agent-harness-tools"; import { createHostRunner, type Runner } from "@poe-code/process-runner"; import { createE2bJobHandle, createE2bLogStreamFs } from "./job-handle.js"; -import { readableToString, toArrayBuffer, type E2bCommandHandle, type E2bSandbox } from "./sdk.js"; +import { + readableToString, + toArrayBuffer, + type E2bCommandHandle, + type E2bCommandResult, + type E2bSandbox +} from "./sdk.js"; + +const REMOTE_COMMAND_STDERR_TAIL_SIZE = 30; interface DetachedJobContext { id: string; @@ -317,12 +325,94 @@ function runE2bPty(sandbox: E2bSandbox, spec: RunSpec): RunHandle { } async function runRemoteOrThrow(sandbox: E2bSandbox, command: string): Promise { - const result = await sandbox.commands.run(command); + const stdoutTail = createLineTail(REMOTE_COMMAND_STDERR_TAIL_SIZE); + const stderrTail = createLineTail(REMOTE_COMMAND_STDERR_TAIL_SIZE); + let result: E2bCommandResult | E2bCommandHandle; + try { + result = await sandbox.commands.run(command, { + onStdout(data) { + stdoutTail.push(data); + }, + onStderr(data) { + stderrTail.push(data); + } + }); + } catch (error) { + appendRemoteCommandOutput(error, stdoutTail, stderrTail); + if (isCommandExitError(error)) { + throw decorateRemoteCommandError(error, command, stderrTail.values()); + } + throw error; + } + appendRemoteCommandOutput(result, stdoutTail, stderrTail); if ("exitCode" in result && result.exitCode !== 0) { - throw new Error(`E2B command failed with exit code ${result.exitCode}: ${command}`); + throw decorateRemoteCommandError( + new Error(`E2B command failed with exit code ${result.exitCode}`), + command, + stderrTail.values() + ); } } +function appendRemoteCommandOutput( + source: unknown, + stdoutTail: { push(chunk: string): void }, + stderrTail: { push(chunk: string): void } +): void { + if (!source || typeof source !== "object") { + return; + } + const output = source as { stdout?: unknown; stderr?: unknown }; + if (typeof output.stdout === "string") { + stdoutTail.push(output.stdout); + } + if (typeof output.stderr === "string") { + stderrTail.push(output.stderr); + } +} + +function decorateRemoteCommandError(error: unknown, command: string, stderrTail: string[]): Error { + const original = error instanceof Error ? error : new Error(String(error)); + const tail = stderrTail.length === 0 ? "" : `\n\nLast stderr output:\n${stderrTail.join("\n")}`; + const decorated = new Error(`E2B command failed: ${command}\n${original.message}${tail}`); + decorated.stack = original.stack; + (decorated as Error & { cause?: unknown }).cause = original; + return decorated; +} + +function createLineTail(maxLines: number): { push(chunk: string): void; values(): string[] } { + const lines: string[] = []; + let pending = ""; + const appendLine = (line: string): void => { + lines.push(trimTrailingCarriageReturn(line)); + while (lines.length > maxLines) { + lines.shift(); + } + }; + + return { + push(chunk) { + pending += chunk; + const parts = pending.split("\n"); + pending = parts.pop() ?? ""; + for (const line of parts) { + appendLine(line); + } + }, + values() { + const output = [...lines]; + if (pending.length > 0) { + output.push(trimTrailingCarriageReturn(pending)); + } + return output.slice(-maxLines); + } + }; +} + +function trimTrailingCarriageReturn(value: string): string { + return value.endsWith("\r") ? value.slice(0, -1) : value; +} + async function runOrThrow(runner: Runner, spec: RunSpec): Promise { const handle = runner.exec(spec); const stderr = readableToString(handle.stderr); @@ -361,3 +451,14 @@ function isExitError(error: unknown): error is { exitCode: number } { typeof (error as { exitCode?: unknown }).exitCode === "number" ); } + +function isCommandExitError(error: unknown): boolean { + return ( + isExitError(error) || + Boolean( + error && + typeof error === "object" && + (error as { name?: unknown }).name === "CommandExitError" + ) + ); +} From 019e8d2832958881210b0b6325e93b15d9bacd18 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 02:10:49 -0500 Subject: [PATCH 063/111] fix: configure e2b spawn agents automatically --- docs/plans/e2b-runtime-spawn-fixes.md | 6 +- docs/plans/e2b-runtime-spawn-fixes.md.lock | 2 +- .../agent-harness-tools/src/binary-exists.ts | 37 +++ packages/agent-harness-tools/src/index.ts | 5 + .../src/run-poe-command.test.ts | 248 +++++++++++++++++- .../src/run-poe-command.ts | 129 +++++++++ packages/runner-e2b/src/opened-env.test.ts | 45 ++++ packages/runner-e2b/src/opened-env.ts | 45 ++-- src/cli/commands/configure.test.ts | 27 ++ src/cli/commands/configure.ts | 240 +++++++++++++++++ src/utils/command-checks.ts | 38 +-- src/utils/utils.test.ts | 17 ++ 12 files changed, 777 insertions(+), 62 deletions(-) create mode 100644 packages/agent-harness-tools/src/binary-exists.ts diff --git a/docs/plans/e2b-runtime-spawn-fixes.md b/docs/plans/e2b-runtime-spawn-fixes.md index 043ff6f04f..452a48db62 100644 --- a/docs/plans/e2b-runtime-spawn-fixes.md +++ b/docs/plans/e2b-runtime-spawn-fixes.md @@ -63,7 +63,7 @@ tasks: status: implement: done test: done - commit: open + commit: done - id: configure-on-spawn title: Run poe-code configure inside the sandbox before each spawn @@ -97,8 +97,8 @@ tasks: asserting the agent talks to api.poe.com (e.g. via `claude --version` followed by a one-shot prompt that succeeds). status: - implement: open - test: open + implement: done + test: done commit: open - id: e2b-spawn-end-to-end diff --git a/docs/plans/e2b-runtime-spawn-fixes.md.lock b/docs/plans/e2b-runtime-spawn-fixes.md.lock index 91390123bc..29871ce07f 100644 --- a/docs/plans/e2b-runtime-spawn-fixes.md.lock +++ b/docs/plans/e2b-runtime-spawn-fixes.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T06:47:32.101Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T07:10:00.145Z"} \ No newline at end of file diff --git a/packages/agent-harness-tools/src/binary-exists.ts b/packages/agent-harness-tools/src/binary-exists.ts new file mode 100644 index 0000000000..f32476c3cf --- /dev/null +++ b/packages/agent-harness-tools/src/binary-exists.ts @@ -0,0 +1,37 @@ +export interface BinaryExistsDetectorResult { + exitCode: number; + stdout: string; +} + +export interface BinaryExistsDetector { + command: string; + args: string[]; + validate(result: BinaryExistsDetectorResult): boolean; +} + +export function createBinaryExistsDetectors(binaryName: string): BinaryExistsDetector[] { + const commonPaths = [ + `/usr/local/bin/${binaryName}`, + `/usr/bin/${binaryName}`, + `$HOME/.local/bin/${binaryName}`, + `$HOME/.claude/local/bin/${binaryName}` + ]; + + return [ + { + command: "which", + args: [binaryName], + validate: (result) => result.exitCode === 0 + }, + { + command: "where", + args: [binaryName], + validate: (result) => result.exitCode === 0 && result.stdout.trim().length > 0 + }, + { + command: "sh", + args: ["-c", commonPaths.map((p) => `test -f "${p}"`).join(" || ")], + validate: (result) => result.exitCode === 0 + } + ]; +} diff --git a/packages/agent-harness-tools/src/index.ts b/packages/agent-harness-tools/src/index.ts index 9510f3cc3e..7f7f140d5f 100644 --- a/packages/agent-harness-tools/src/index.ts +++ b/packages/agent-harness-tools/src/index.ts @@ -48,6 +48,11 @@ export { type LogStreamFs } from "./log-stream.js"; export { runPoeCommand } from "./run-poe-command.js"; +export { + createBinaryExistsDetectors, + type BinaryExistsDetector, + type BinaryExistsDetectorResult +} from "./binary-exists.js"; export { applyRuntimeOverrides, resolvePoeCommandExecution, diff --git a/packages/agent-harness-tools/src/run-poe-command.test.ts b/packages/agent-harness-tools/src/run-poe-command.test.ts index 1edb7bf476..5cd9e5a47b 100644 --- a/packages/agent-harness-tools/src/run-poe-command.test.ts +++ b/packages/agent-harness-tools/src/run-poe-command.test.ts @@ -112,7 +112,9 @@ function createMockEnv( }, exec(spec): RunHandle { env.execSpecs.push(spec); - void writeExitFile(rawFs.promises, spec, commandExitCode); + if (spec.command === "sh" && spec.args?.[0] === "-c") { + void writeExitFile(rawFs.promises, spec, commandExitCode); + } return { pid: 123, stdout: null, @@ -189,6 +191,18 @@ function createFactory(env: OpenedEnv): ExecutionEnvFactory { }; } +function createE2bFactory(env: OpenedEnv): ExecutionEnvFactory { + return { + type: "e2b", + async open() { + return env; + }, + async attach() { + return env; + } + }; +} + function deferred(): { promise: Promise; resolve(value: T): void; @@ -303,6 +317,238 @@ describe("runPoeCommand", () => { expect(execStarted).toBe(true); }); + it("configures the spawned E2B agent after upload and before the agent command", async () => { + const { state } = createRecordingState(); + const env = createMockEnv(); + const upload = env.uploadWorkspace.bind(env); + const exec = env.exec.bind(env); + let uploadFinished = false; + + env.uploadWorkspace = async () => { + const result = await upload(); + uploadFinished = true; + return result; + }; + env.exec = (spec): RunHandle => { + expect(uploadFinished).toBe(true); + return exec(spec); + }; + + await runPoeCommand({ + factory: createE2bFactory(env), + openSpec: createOpenSpec({ + env: { POE_API_KEY: "sk-test" }, + jobLabel: { tool: "claude-code", argv: ["claude", "-p", "hello"] } + }), + detach: false, + state + }); + + expect(env.execSpecs.map((spec) => [spec.command, ...(spec.args ?? [])])).toEqual([ + ["which", "claude"], + [ + "poe-code", + "configure", + "--yes", + "--skip-if-configured", + "--provider", + "poe", + "claude-code" + ], + ["sh", "-c", expect.stringContaining("'claude' '-p' 'hello'")] + ]); + expect(env.execSpecs[1]).toMatchObject({ + cwd: "/repo", + env: { POE_API_KEY: "sk-test" }, + stdin: "ignore", + stdout: "pipe", + stderr: "pipe" + }); + }); + + it("skips E2B configure when the spawned agent binary is absent", async () => { + const { state } = createRecordingState(); + const env = createMockEnv(); + const exec = env.exec.bind(env); + + env.exec = (spec): RunHandle => { + env.execSpecs.push(spec); + const isBinaryCheck = + spec.command === "which" || + spec.command === "where" || + (spec.command === "sh" && + spec.args?.[0] === "-c" && + spec.args[1]?.includes("test -f")); + if (isBinaryCheck) { + return { + pid: 123, + stdout: null, + stderr: null, + stdin: null, + result: Promise.resolve({ exitCode: 1 }), + kill() {} + }; + } + env.execSpecs.pop(); + return exec(spec); + }; + + await runPoeCommand({ + factory: createE2bFactory(env), + openSpec: createOpenSpec({ + jobLabel: { tool: "codex", argv: ["codex", "exec", "hello"] } + }), + detach: false, + state + }); + + expect(env.execSpecs.map((spec) => [spec.command, ...(spec.args ?? [])])).toEqual([ + ["which", "codex"], + ["where", "codex"], + [ + "sh", + "-c", + 'test -f "/usr/local/bin/codex" || test -f "/usr/bin/codex" || test -f "$HOME/.local/bin/codex" || test -f "$HOME/.claude/local/bin/codex"' + ], + ["sh", "-c", expect.stringContaining("'codex' 'exec' 'hello'")] + ]); + }); + + it("does not treat an empty where result as an existing E2B agent binary", async () => { + const { state } = createRecordingState(); + const env = createMockEnv(); + const exec = env.exec.bind(env); + + env.exec = (spec): RunHandle => { + env.execSpecs.push(spec); + if (spec.command === "which") { + return { + pid: 123, + stdout: null, + stderr: null, + stdin: null, + result: Promise.resolve({ exitCode: 1 }), + kill() {} + }; + } + if (spec.command === "where") { + const stdout = new PassThrough(); + stdout.end(""); + return { + pid: 123, + stdout, + stderr: null, + stdin: null, + result: Promise.resolve({ exitCode: 0 }), + kill() {} + }; + } + if ( + spec.command === "sh" && + spec.args?.[0] === "-c" && + spec.args[1]?.includes("test -f") + ) { + return { + pid: 123, + stdout: null, + stderr: null, + stdin: null, + result: Promise.resolve({ exitCode: 1 }), + kill() {} + }; + } + env.execSpecs.pop(); + return exec(spec); + }; + + await runPoeCommand({ + factory: createE2bFactory(env), + openSpec: createOpenSpec({ + jobLabel: { tool: "opencode", argv: ["opencode", "run", "hello"] } + }), + detach: false, + state + }); + + expect(env.execSpecs.map((spec) => [spec.command, ...(spec.args ?? [])])).toEqual([ + ["which", "opencode"], + ["where", "opencode"], + [ + "sh", + "-c", + 'test -f "/usr/local/bin/opencode" || test -f "/usr/bin/opencode" || test -f "$HOME/.local/bin/opencode" || test -f "$HOME/.claude/local/bin/opencode"' + ], + ["sh", "-c", expect.stringContaining("'opencode' 'run' 'hello'")] + ]); + }); + + it("fails the E2B spawn when sandbox configure fails after the binary check passes", async () => { + const { state } = createRecordingState(); + const env = createMockEnv(); + const exec = env.exec.bind(env); + + env.exec = (spec): RunHandle => { + env.execSpecs.push(spec); + if (spec.command === "which") { + return { + pid: 123, + stdout: null, + stderr: null, + stdin: null, + result: Promise.resolve({ exitCode: 0 }), + kill() {} + }; + } + if (spec.command === "poe-code") { + const stdout = new PassThrough(); + const stderr = new PassThrough(); + stdout.end("configure stdout\n"); + stderr.end("configure stderr\n"); + return { + pid: 123, + stdout, + stderr, + stdin: null, + result: Promise.resolve({ exitCode: 2 }), + kill() {} + }; + } + env.execSpecs.pop(); + return exec(spec); + }; + + await expect( + runPoeCommand({ + factory: createE2bFactory(env), + openSpec: createOpenSpec({ + jobLabel: { tool: "claude-code", argv: ["claude", "-p", "hello"] } + }), + detach: false, + state + }) + ).rejects.toThrow( + [ + "Failed to configure claude-code for Poe inside E2B sandbox.", + "Exit code: 2", + "stdout:\nconfigure stdout", + "stderr:\nconfigure stderr" + ].join("\n") + ); + + expect(env.execSpecs.map((spec) => [spec.command, ...(spec.args ?? [])])).toEqual([ + ["which", "claude"], + [ + "poe-code", + "configure", + "--yes", + "--skip-if-configured", + "--provider", + "poe", + "claude-code" + ] + ]); + }); + it("returns the download result with conflicts from sync mode", async () => { const { state } = createRecordingState(); const env = createMockEnv({ diff --git a/packages/agent-harness-tools/src/run-poe-command.ts b/packages/agent-harness-tools/src/run-poe-command.ts index 931bc8418a..90e86fc676 100644 --- a/packages/agent-harness-tools/src/run-poe-command.ts +++ b/packages/agent-harness-tools/src/run-poe-command.ts @@ -1,7 +1,9 @@ import { randomBytes } from "node:crypto"; +import { allAgents, resolveAgentId } from "@poe-code/agent-defs"; import type { StateManager } from "@poe-code/poe-code-config"; import type { RunHandle } from "@poe-code/process-runner"; import type { Readable } from "node:stream"; +import { createBinaryExistsDetectors } from "./binary-exists.js"; import type { DownloadResult, ExecutionEnvFactory, OpenedEnv, OpenSpec } from "./execution-env.js"; import { waitForExit, wrapForLogTee, type LogStreamEnv } from "./log-stream.js"; @@ -44,6 +46,11 @@ export async function runPoeCommand(opts: { try { const upload = env.uploadWorkspace(); await Promise.all([pendingJob, upload]); + await configureE2bSpawnAgentIfAvailable({ + env, + openSpec: opts.openSpec, + factoryType: opts.factory.type + }); const argv = wrapCommand ? wrapForLogTee(opts.openSpec.jobLabel.argv, jobId) : opts.openSpec.jobLabel.argv; @@ -114,6 +121,128 @@ export async function runPoeCommand(opts: { } } +async function configureE2bSpawnAgentIfAvailable(opts: { + env: OpenedEnv; + openSpec: OpenSpec; + factoryType: string; +}): Promise { + if (opts.factoryType !== "e2b") { + return; + } + + const agentId = resolveAgentId(opts.openSpec.jobLabel.tool); + const agent = allAgents.find((candidate) => candidate.id === agentId); + const binaryName = agent?.binaryName; + if (!agentId || !binaryName) { + return; + } + + const commandEnv = resolveExecutionEnv(opts.openSpec); + const exists = await binaryExists(opts.env, { + binaryName, + cwd: opts.openSpec.cwd, + env: commandEnv + }); + if (!exists) { + return; + } + + const result = await runProbeCommand(opts.env, { + command: "poe-code", + args: [ + "configure", + "--yes", + "--skip-if-configured", + "--provider", + "poe", + agentId + ], + cwd: opts.openSpec.cwd, + env: commandEnv + }); + if (result.exitCode !== 0) { + throw new Error( + `Failed to configure ${agentId} for Poe inside E2B sandbox.\n${formatProbeResult(result)}` + ); + } +} + +async function binaryExists( + env: OpenedEnv, + opts: { binaryName: string; cwd: string; env: Record | undefined } +): Promise { + for (const detector of createBinaryExistsDetectors(opts.binaryName)) { + const result = await runProbeCommand(env, { + ...detector, + cwd: opts.cwd, + env: opts.env + }); + if (detector.validate(result)) { + return true; + } + } + + return false; +} + +function resolveExecutionEnv(openSpec: OpenSpec): Record | undefined { + const execution = openSpec.execution; + return execution && "env" in execution ? execution.env : openSpec.env; +} + +async function runProbeCommand( + env: OpenedEnv, + spec: { + command: string; + args?: string[]; + cwd: string; + env: Record | undefined; + } +): Promise<{ exitCode: number; stdout: string; stderr: string }> { + const handle = env.exec({ + command: spec.command, + args: spec.args, + cwd: spec.cwd, + env: spec.env, + stdin: "ignore", + stdout: "pipe", + stderr: "pipe" + }); + const stdout = readStream(handle.stdout); + const stderr = readStream(handle.stderr); + const result = await handle.result; + return { + exitCode: result.exitCode, + stdout: await stdout, + stderr: await stderr + }; +} + +function readStream(stream: Readable | null): Promise { + if (!stream) { + return Promise.resolve(""); + } + return new Promise((resolve, reject) => { + let output = ""; + stream.setEncoding("utf8"); + stream.on("data", (chunk) => { + output += chunk.toString(); + }); + stream.on("error", reject); + stream.on("end", () => resolve(output)); + }); +} + +function formatProbeResult(result: { exitCode: number; stdout: string; stderr: string }): string { + return [ + `Exit code: ${result.exitCode}`, + result.stdout.trim() ? `stdout:\n${result.stdout.trim()}` : "", + result.stderr.trim() ? `stderr:\n${result.stderr.trim()}` : "" + ] + .filter(Boolean) + .join("\n"); +} + async function runSync(opts: { env: OpenedEnv; handle: RunHandle; diff --git a/packages/runner-e2b/src/opened-env.test.ts b/packages/runner-e2b/src/opened-env.test.ts index 0bcb946ec2..eb2cd9fa4a 100644 --- a/packages/runner-e2b/src/opened-env.test.ts +++ b/packages/runner-e2b/src/opened-env.test.ts @@ -64,6 +64,51 @@ describe("createOpenedE2bEnv", () => { }); }); + it("queues stdin writes until the E2B command handle is ready", async () => { + const commandHandle = { + pid: 321, + wait: vi.fn().mockResolvedValue({ exitCode: 0 }), + kill: vi.fn() + }; + let resolveRun!: (handle: typeof commandHandle) => void; + const sandbox = createSandboxMock(); + sandbox.commands.run.mockReturnValue( + new Promise((resolve) => { + resolveRun = resolve; + }) + ); + const env = createOpenedE2bEnv({ + sandbox, + runtime: createRuntime(), + spec: createSpec() + }); + + const handle = env.exec({ + command: "cat", + stdin: "pipe", + stdout: "pipe", + stderr: "pipe" + }); + const stdinFinished = new Promise((resolve, reject) => { + handle.stdin!.end("hello", (error?: Error | null) => { + if (error) { + reject(error); + return; + } + resolve(); + }); + }); + + expect(sandbox.commands.sendStdin).not.toHaveBeenCalled(); + + resolveRun(commandHandle); + + await stdinFinished; + await expect(handle.result).resolves.toEqual({ exitCode: 0 }); + expect(sandbox.commands.sendStdin).toHaveBeenCalledWith(321, Buffer.from("hello")); + expect(sandbox.commands.closeStdin).toHaveBeenCalledWith(321); + }); + it("leaves non-workspace command cwd values unchanged", async () => { const commandHandle = { pid: 321, diff --git a/packages/runner-e2b/src/opened-env.ts b/packages/runner-e2b/src/opened-env.ts index 7f5afb9436..c3b20264da 100644 --- a/packages/runner-e2b/src/opened-env.ts +++ b/packages/runner-e2b/src/opened-env.ts @@ -189,27 +189,6 @@ function runE2bCommand( const stdout = spec.stdout === "inherit" ? null : new PassThrough(); const stderr = spec.stderr === "inherit" ? null : new PassThrough(); let e2bHandle: E2bCommandHandle | null = null; - const stdin = - spec.stdin === "pipe" - ? new Writable({ - write(chunk, _encoding, callback) { - if (e2bHandle === null) { - callback(new Error("E2B command stdin is not ready.")); - return; - } - sandbox.commands - .sendStdin(e2bHandle.pid, Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk))) - .then(() => callback(), callback); - }, - final(callback) { - if (e2bHandle === null || sandbox.commands.closeStdin === undefined) { - callback(); - return; - } - sandbox.commands.closeStdin(e2bHandle.pid).then(() => callback(), callback); - } - }) - : null; const command = shellCommand([spec.command, ...(spec.args ?? [])]); const started = sandbox.commands.run(command, { background: true, @@ -229,6 +208,30 @@ function runE2bCommand( } } }) as Promise; + const stdin = + spec.stdin === "pipe" + ? new Writable({ + write(chunk, _encoding, callback) { + started + .then((handle) => + sandbox.commands.sendStdin( + handle.pid, + Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)) + ) + ) + .then(() => callback(), callback); + }, + final(callback) { + if (sandbox.commands.closeStdin === undefined) { + callback(); + return; + } + started + .then((handle) => sandbox.commands.closeStdin!(handle.pid)) + .then(() => callback(), callback); + } + }) + : null; const result = started .then((handle) => { e2bHandle = handle; diff --git a/src/cli/commands/configure.test.ts b/src/cli/commands/configure.test.ts index a983486f76..8f12397ad6 100644 --- a/src/cli/commands/configure.test.ts +++ b/src/cli/commands/configure.test.ts @@ -41,6 +41,7 @@ function createFakeProvider(id: string, label: string): AuthProvider { function mockOptions(container: ReturnType) { vi.spyOn(container.options, "resolveApiKey").mockResolvedValue("sk-test"); vi.spyOn(container.options, "resolveModel").mockImplementation(async ({ defaultValue }) => defaultValue); + vi.spyOn(container.options, "resolveReasoning").mockImplementation(async ({ defaultValue }) => defaultValue); } function stubInvoke(container: ReturnType) { @@ -317,4 +318,30 @@ describe("configure provider resolution", () => { expect(services["claude-code"]).toMatchObject({ provider: "poe" }); }); + it("--skip-if-configured exits before writes when configure would only create a backup", async () => { + const container = createContainer(fs, { POE_API_KEY: "sk-env" }); + mockOptions(container); + + await executeConfigure( + createTestProgram(["node", "cli", "--yes"]), + container, + "codex", + { provider: "poe" } + ); + + const configFile = `${homeDir}/.codex/config.toml`; + const before = await fs.readFile(configFile, "utf8"); + const writeSpy = vi.spyOn(fs, "writeFile"); + + await executeConfigure( + createTestProgram(["node", "cli", "--yes"]), + container, + "codex", + { provider: "poe", skipIfConfigured: true } + ); + + expect(writeSpy).not.toHaveBeenCalled(); + await expect(fs.readFile(configFile, "utf8")).resolves.toBe(before); + }); + }); diff --git a/src/cli/commands/configure.ts b/src/cli/commands/configure.ts index acd9d9bfc6..e9fa456384 100644 --- a/src/cli/commands/configure.ts +++ b/src/cli/commands/configure.ts @@ -1,4 +1,5 @@ import type { Command } from "commander"; +import type { Stats } from "node:fs"; import { parseAgentSpecifier } from "@poe-code/agent-defs"; import type { CliContainer } from "../container.js"; import type { AuthProvider } from "@poe-code/providers"; @@ -21,7 +22,10 @@ import { createMutationReporter } from "../../services/mutation-events.js"; import type { MutationObservers } from "@poe-code/config-mutations"; +import type { CommandContext } from "../context.js"; import { createConfigurePayload } from "./configure-payload.js"; +import type { ProviderContext, ProviderService } from "../service-registry.js"; +import type { FileSystem } from "../../utils/file-system.js"; const serviceSelectionPrompt = (action: string) => `Pick a tool to ${action}:`; const DEFAULT_SERVICE_AGENT = "claude-code"; @@ -31,6 +35,7 @@ export interface ConfigureCommandOptions { model?: string; reasoningEffort?: string; provider?: string; + skipIfConfigured?: boolean; } export function registerConfigureCommand(program: Command, container: CliContainer): Command { @@ -46,6 +51,7 @@ export function registerConfigureCommand(program: Command, container: CliContain .option("--model ", "Model identifier") .option("--reasoning-effort ", "Reasoning effort level") .option("--provider ", "Provider to use for this agent") + .option("--skip-if-configured", "Exit without writes when current config already matches") .action(async (service: string | undefined, options: ConfigureCommandOptions) => { const resolved = await resolveServiceArgument(program, container, service, { action: "configure" @@ -86,10 +92,24 @@ export async function executeConfigure( providerId }); + let skippedConfigured = false; await container.registry.invoke(canonicalService, "configure", async (entry) => { if (!entry.configure) { throw new Error(`Agent "${canonicalService}" does not support configure.`); } + if ( + options.skipIfConfigured === true && + !(await hasMaterialConfigureChange({ + entry, + adapter, + providerContext, + payload + })) + ) { + skippedConfigured = true; + return; + } + const tracker = createMutationTracker(); const mutationLogger = createMutationReporter(resources.logger); const observers = combineMutationObservers(tracker.observers, mutationLogger); @@ -137,6 +157,15 @@ export async function executeConfigure( } }); + if (skippedConfigured) { + resources.context.complete({ + success: `${adapter.label} is already configured.`, + dry: `Dry run: ${adapter.label} is already configured.` + }); + resources.context.finalize(); + return; + } + resources.context.complete({ success: `Configured ${adapter.label}.`, dry: `Dry run: would configure ${adapter.label}.` @@ -149,6 +178,217 @@ export async function executeConfigure( resources.context.finalize(); } +async function hasMaterialConfigureChange(input: { + entry: ProviderService; + adapter: ProviderService; + providerContext: ProviderContext; + payload: unknown; +}): Promise { + const overlay = createOverlayFileSystem(input.providerContext.command.fs); + const command = createSilentDryRunCommand(input.providerContext.command, overlay.fs); + + await input.entry.configure( + { + fs: overlay.fs, + env: input.providerContext.env, + command, + options: input.payload + }, + { observers: createNoopMutationObservers() } + ); + + const isolated = input.adapter.isolatedEnv; + if (isolated && isolated.requiresConfig !== false) { + await applyIsolatedConfiguration({ + adapter: input.entry, + providerContext: { + ...input.providerContext, + command + }, + payload: input.payload, + isolated, + providerName: input.adapter.name, + observers: createNoopMutationObservers() + }); + } + + return overlay.hasMaterialChange(); +} + +function createSilentDryRunCommand( + base: CommandContext, + fs: CommandContext["fs"] +): CommandContext { + return { + fs, + runCommand: base.runCommand, + runCommandWithEnv: base.runCommandWithEnv, + flushDryRun() {}, + complete() {}, + finalize() {} + }; +} + +function createNoopMutationObservers(): MutationObservers { + return {}; +} + +function createOverlayFileSystem(base: FileSystem): { + fs: FileSystem; + hasMaterialChange(): Promise; +} { + const writes = new Map(); + const directories = new Set(); + + const readOverlayText = async (filePath: string): Promise => { + if (writes.has(filePath)) { + const value = writes.get(filePath); + if (value === null) { + throw createNotFoundError(filePath); + } + return value ?? ""; + } + return base.readFile(filePath, "utf8"); + }; + + async function readFile(filePath: string, encoding: BufferEncoding): Promise; + async function readFile(filePath: string): Promise; + async function readFile(filePath: string, encoding?: BufferEncoding): Promise { + const content = await readOverlayText(filePath); + return encoding ? content : Buffer.from(content); + } + + const fs: FileSystem = { + readFile, + async writeFile(filePath, content) { + writes.set(filePath, stringifyFileContent(content)); + }, + async mkdir(directoryPath) { + directories.add(directoryPath); + }, + async unlink(filePath) { + writes.set(filePath, null); + }, + async stat(filePath) { + if (directories.has(filePath)) { + return createOverlayStats(); + } + if (writes.has(filePath)) { + if (writes.get(filePath) === null) { + throw createNotFoundError(filePath); + } + return createOverlayStats(); + } + return base.stat(filePath); + }, + async lstat(filePath) { + return fs.stat(filePath); + }, + async symlink() {}, + async readlink(filePath) { + return base.readlink(filePath); + }, + async rename(from, to) { + writes.set(to, await readOverlayText(from)); + writes.set(from, null); + }, + async readdir(directoryPath) { + return base.readdir(directoryPath); + }, + async rm(filePath) { + writes.set(filePath, null); + }, + async chmod() {} + }; + + return { + fs, + async hasMaterialChange() { + for (const directoryPath of directories) { + if (!(await pathExists(base, directoryPath))) { + return true; + } + } + for (const [filePath, content] of writes) { + if (isBackupPath(filePath)) { + continue; + } + const current = await readBaseText(base, filePath); + if (content === null) { + if (current !== null) { + return true; + } + continue; + } + if (current !== content) { + return true; + } + } + return false; + } + }; +} + +function stringifyFileContent(content: string | NodeJS.ArrayBufferView): string { + if (typeof content === "string") { + return content; + } + return Buffer.from(content.buffer, content.byteOffset, content.byteLength).toString("utf8"); +} + +function createOverlayStats(): Stats { + return { + isFile: () => true, + isDirectory: () => false, + isBlockDevice: () => false, + isCharacterDevice: () => false, + isSymbolicLink: () => false, + isFIFO: () => false, + isSocket: () => false + } as Stats; +} + +async function pathExists(fs: FileSystem, filePath: string): Promise { + try { + await fs.stat(filePath); + return true; + } catch (error) { + if (isNotFoundError(error)) { + return false; + } + throw error; + } +} + +async function readBaseText(fs: FileSystem, filePath: string): Promise { + try { + return await fs.readFile(filePath, "utf8"); + } catch (error) { + if (isNotFoundError(error)) { + return null; + } + throw error; + } +} + +function isBackupPath(filePath: string): boolean { + return filePath.includes(".backup-"); +} + +function createNotFoundError(filePath: string): NodeJS.ErrnoException { + const error = new Error(`ENOENT: no such file or directory, open '${filePath}'`) as NodeJS.ErrnoException; + error.code = "ENOENT"; + return error; +} + +function isNotFoundError(error: unknown): boolean { + return Boolean( + error && + typeof error === "object" && + (error as { code?: unknown }).code === "ENOENT" + ); +} + async function resolveProvider( agentId: string, options: Pick, diff --git a/src/utils/command-checks.ts b/src/utils/command-checks.ts index e8471e019c..86dc0a6f08 100644 --- a/src/utils/command-checks.ts +++ b/src/utils/command-checks.ts @@ -4,6 +4,7 @@ import type { CommandRunnerResult } from "@poe-code/agent-spawn"; import { buildSpawnArgs } from "@poe-code/agent-spawn"; +import { createBinaryExistsDetectors } from "@poe-code/agent-harness-tools"; export type { CommandRunner, @@ -216,42 +217,7 @@ export function createBinaryExistsCheck( id, description, async run({ runCommand }) { - // Common installation paths for CLI tools - const commonPaths = [ - `/usr/local/bin/${binaryName}`, - `/usr/bin/${binaryName}`, - `$HOME/.local/bin/${binaryName}`, - `$HOME/.claude/local/bin/${binaryName}` - ]; - - const detectors: Array<{ - command: string; - args: string[]; - validate: (result: CommandRunnerResult) => boolean; - }> = [ - { - command: "which", - args: [binaryName], - validate: (result) => result.exitCode === 0 - }, - { - command: "where", - args: [binaryName], - validate: (result) => - result.exitCode === 0 && result.stdout.trim().length > 0 - }, - // Check common installation paths using shell expansion for $HOME - { - command: "sh", - args: [ - "-c", - commonPaths.map((p) => `test -f "${p}"`).join(" || ") - ], - validate: (result) => result.exitCode === 0 - } - ]; - - for (const detector of detectors) { + for (const detector of createBinaryExistsDetectors(binaryName)) { const result = await runCommand(detector.command, detector.args); if (detector.validate(result)) { return; diff --git a/src/utils/utils.test.ts b/src/utils/utils.test.ts index 1e25dec875..4adafc57f3 100644 --- a/src/utils/utils.test.ts +++ b/src/utils/utils.test.ts @@ -341,6 +341,23 @@ describe("createBinaryExistsCheck", () => { expect(runCommand).toHaveBeenCalledWith("which", ["demo"]); expect(runCommand).toHaveBeenCalledWith("where", ["demo"]); }); + + it("does not accept an empty where result as present", async () => { + const runCommand = createRunner({ + "which demo": { stdout: "", exitCode: 1 }, + "where demo": { stdout: "", exitCode: 0 }, + 'sh -c test -f "/usr/local/bin/demo" || test -f "/usr/bin/demo" || test -f "$HOME/.local/bin/demo" || test -f "$HOME/.claude/local/bin/demo"': { + stdout: "", + exitCode: 1 + } + }); + + const check = createBinaryExistsCheck("demo", "demo-id", "demo desc"); + + await expect(check.run({ isDryRun: false, runCommand })).rejects.toThrow( + "demo CLI binary not found on PATH." + ); + }); }); describe("createSpawnHealthCheck", () => { From 3f10e12c500a3cc01ae48d043728a311b53983ae Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 02:28:32 -0500 Subject: [PATCH 064/111] fix: support e2b runtime spawn workspaces --- docs/plans/e2b-runtime-spawn-fixes.md | 6 +- docs/plans/e2b-runtime-spawn-fixes.md.lock | 2 +- .../src/execution-env.test.ts | 2 +- .../agent-harness-tools/src/execution-env.ts | 1 + .../src/poe-command-execution.ts | 9 +- .../src/run-poe-command.test.ts | 2 - .../src/run-poe-command.ts | 13 +- packages/agent-spawn/src/acp/spawn.ts | 1 + .../src/e2b-spawn.integration.test.ts | 253 ++++++++++++++++++ packages/agent-spawn/src/spawn-interactive.ts | 1 + packages/agent-spawn/src/spawn.ts | 1 + packages/agent-spawn/src/types.ts | 2 + packages/runner-e2b/src/factory.ts | 7 +- packages/runner-e2b/src/opened-env.test.ts | 45 +++- packages/runner-e2b/src/opened-env.ts | 29 +- src/cli/commands/auth-command.test.ts | 13 +- src/cli/commands/spawn-command.test.ts | 61 +++-- src/cli/commands/spawn.ts | 3 + src/providers/spawn-options.ts | 1 + src/sdk/spawn.ts | 3 + src/sdk/types.ts | 2 + 21 files changed, 408 insertions(+), 49 deletions(-) create mode 100644 packages/agent-spawn/src/e2b-spawn.integration.test.ts diff --git a/docs/plans/e2b-runtime-spawn-fixes.md b/docs/plans/e2b-runtime-spawn-fixes.md index 452a48db62..31f0ffedf8 100644 --- a/docs/plans/e2b-runtime-spawn-fixes.md +++ b/docs/plans/e2b-runtime-spawn-fixes.md @@ -99,7 +99,7 @@ tasks: status: implement: done test: done - commit: open + commit: done - id: e2b-spawn-end-to-end title: Make `spawn --runtime e2b` work end-to-end on a tmp workspace @@ -136,8 +136,8 @@ tasks: against a captured-sandbox fake when E2B_API_KEY is unset, so CI exercises the wiring even without real e2b access. status: - implement: open - test: open + implement: done + test: done commit: open - id: e2b-ralph-end-to-end diff --git a/docs/plans/e2b-runtime-spawn-fixes.md.lock b/docs/plans/e2b-runtime-spawn-fixes.md.lock index 29871ce07f..8b2b6559d6 100644 --- a/docs/plans/e2b-runtime-spawn-fixes.md.lock +++ b/docs/plans/e2b-runtime-spawn-fixes.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T07:10:00.145Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T07:27:31.200Z"} \ No newline at end of file diff --git a/packages/agent-harness-tools/src/execution-env.test.ts b/packages/agent-harness-tools/src/execution-env.test.ts index b113acc6eb..c9f58c6da8 100644 --- a/packages/agent-harness-tools/src/execution-env.test.ts +++ b/packages/agent-harness-tools/src/execution-env.test.ts @@ -78,7 +78,7 @@ describe("execution env registry", () => { expect(branchSites).toMatchInlineSnapshot(` [ - "execution-env.ts:96:return selectExecutionEnvFactory(runtime.type);", + "execution-env.ts:97:return selectExecutionEnvFactory(runtime.type);", ] `); }); diff --git a/packages/agent-harness-tools/src/execution-env.ts b/packages/agent-harness-tools/src/execution-env.ts index 973b44d7ab..99e06fb789 100644 --- a/packages/agent-harness-tools/src/execution-env.ts +++ b/packages/agent-harness-tools/src/execution-env.ts @@ -17,6 +17,7 @@ export interface ExecutionEnvFactory { export interface OpenSpec { cwd: string; + runtimeCwd?: string; runtime: RuntimeConfig; runner?: RunnerScope; state?: StateManager; diff --git a/packages/agent-harness-tools/src/poe-command-execution.ts b/packages/agent-harness-tools/src/poe-command-execution.ts index 4c7aee8884..1a57b396cb 100644 --- a/packages/agent-harness-tools/src/poe-command-execution.ts +++ b/packages/agent-harness-tools/src/poe-command-execution.ts @@ -27,6 +27,7 @@ export type RuntimeOverrideOptions = { export function resolvePoeCommandExecution(input: { cwd: string; + runtimeConfigCwd?: string; env: Record; argv: string[]; tool: string; @@ -43,9 +44,10 @@ export function resolvePoeCommandExecution(input: { state: StateManager; } { const homeDir = input.context?.homeDir ?? os.homedir(); - const loaded = loadRuntimeConfig(input.cwd, homeDir); - const config = applyRuntimeOverrides(loaded, input.runtime, input.cwd); - const resolved = resolveRuntime({ cwd: input.cwd, config }); + const runtimeConfigCwd = input.runtimeConfigCwd ?? input.cwd; + const loaded = loadRuntimeConfig(runtimeConfigCwd, homeDir); + const config = applyRuntimeOverrides(loaded, input.runtime, runtimeConfigCwd); + const resolved = resolveRuntime({ cwd: runtimeConfigCwd, config }); const factory = selectExecutionEnv(resolved.runtime); const state = input.context?.state ?? loadState(homeDir); @@ -55,6 +57,7 @@ export function resolvePoeCommandExecution(input: { state, openSpec: { cwd: input.cwd, + runtimeCwd: runtimeConfigCwd, runtime: resolved.runtime, runner: config.runner, state, diff --git a/packages/agent-harness-tools/src/run-poe-command.test.ts b/packages/agent-harness-tools/src/run-poe-command.test.ts index 5cd9e5a47b..c08b15134c 100644 --- a/packages/agent-harness-tools/src/run-poe-command.test.ts +++ b/packages/agent-harness-tools/src/run-poe-command.test.ts @@ -350,7 +350,6 @@ describe("runPoeCommand", () => { "poe-code", "configure", "--yes", - "--skip-if-configured", "--provider", "poe", "claude-code" @@ -541,7 +540,6 @@ describe("runPoeCommand", () => { "poe-code", "configure", "--yes", - "--skip-if-configured", "--provider", "poe", "claude-code" diff --git a/packages/agent-harness-tools/src/run-poe-command.ts b/packages/agent-harness-tools/src/run-poe-command.ts index 90e86fc676..6eed5ab327 100644 --- a/packages/agent-harness-tools/src/run-poe-command.ts +++ b/packages/agent-harness-tools/src/run-poe-command.ts @@ -60,7 +60,7 @@ export async function runPoeCommand(opts: { command: argv[0], args: argv.slice(1), cwd: opts.openSpec.cwd, - env: execution && "env" in execution ? execution.env : opts.openSpec.env, + env: resolveExecutionEnv(opts.openSpec), stdin: execution?.stdin ?? "inherit", stdout: execution?.stdout ?? "pipe", stderr: execution?.stderr ?? "pipe", @@ -149,14 +149,7 @@ async function configureE2bSpawnAgentIfAvailable(opts: { const result = await runProbeCommand(opts.env, { command: "poe-code", - args: [ - "configure", - "--yes", - "--skip-if-configured", - "--provider", - "poe", - agentId - ], + args: ["configure", "--yes", "--provider", "poe", agentId], cwd: opts.openSpec.cwd, env: commandEnv }); @@ -187,7 +180,7 @@ async function binaryExists( function resolveExecutionEnv(openSpec: OpenSpec): Record | undefined { const execution = openSpec.execution; - return execution && "env" in execution ? execution.env : openSpec.env; + return execution?.env ?? openSpec.env; } async function runProbeCommand( diff --git a/packages/agent-spawn/src/acp/spawn.ts b/packages/agent-spawn/src/acp/spawn.ts index c101904d7d..baf0849f16 100644 --- a/packages/agent-spawn/src/acp/spawn.ts +++ b/packages/agent-spawn/src/acp/spawn.ts @@ -189,6 +189,7 @@ export function spawnStreaming(options: SpawnStreamingOptions): SpawnStreamingRe const argv = [binaryName, ...args]; const execution = resolveSpawnExecution({ cwd: options.cwd ?? process.cwd(), + runtimeConfigCwd: options.runtimeConfigCwd, env: (processEnv ?? process.env) as Record, argv, tool: agentId, diff --git a/packages/agent-spawn/src/e2b-spawn.integration.test.ts b/packages/agent-spawn/src/e2b-spawn.integration.test.ts new file mode 100644 index 0000000000..e18e79ac0f --- /dev/null +++ b/packages/agent-spawn/src/e2b-spawn.integration.test.ts @@ -0,0 +1,253 @@ +import { mkdtemp, readdir, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { PassThrough } from "node:stream"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { + registerExecutionEnvFactory, + type ExecutionEnvFactory, + type OpenSpec, + type RunHandle, + type RunSpec +} from "@poe-code/agent-harness-tools"; +import { e2bExecutionEnvFactory } from "@poe-code/runner-e2b"; +import { spawn } from "./spawn.js"; + +describe.skipIf(process.env.E2B_API_KEY)("spawn through e2b with captured sandbox fake", () => { + const repoRoot = process.cwd(); + const originalEnv = { ...process.env }; + + beforeEach(() => { + process.env = { + ...originalEnv, + POE_API_KEY: "sk-poe-captured-sandbox" + }; + }); + + afterEach(() => { + process.env = { ...originalEnv }; + registerExecutionEnvFactory(e2bExecutionEnvFactory); + }); + + it("uploads a fresh tmp workspace, configures claude-code, and runs in the sandbox", async () => { + const sandbox = createCapturedSandbox(); + registerExecutionEnvFactory(createCapturedE2bFactory(sandbox)); + + const workspace = await mkdtemp(path.join(tmpdir(), "poe-e2b-spawn-")); + try { + await writeFile( + path.join(workspace, "README.md"), + "This is a tiny throwaway workspace for validating e2b spawn wiring.\n", + "utf8" + ); + await writeFile(path.join(workspace, "hello.txt"), "hello from the sandbox\n", "utf8"); + await expect(readdir(workspace).then((files) => files.sort())).resolves.toEqual([ + "README.md", + "hello.txt" + ]); + + const result = await spawn( + "claude-code", + { + prompt: "read hello.txt and summarize in one sentence", + cwd: workspace, + runtime: "e2b", + runtimeConfigCwd: repoRoot + }, + { + homeDir: path.join(workspace, ".home"), + state: createMemoryState() + } + ); + + expect(result.exitCode).toBe(0); + expect(result.stdout.trim()).not.toBe(""); + expect(sandbox.uploadedWorkspaces).toEqual([ + { cwd: workspace, files: ["README.md", "hello.txt"] } + ]); + expect(sandbox.downloadedWorkspaces).toEqual([workspace]); + expect(sandbox.openSpecs).toHaveLength(1); + expect(sandbox.openSpecs[0]).toMatchObject({ + cwd: workspace, + runtimeCwd: repoRoot, + runtime: expect.objectContaining({ type: "e2b" }) + }); + expect(sandbox.commands).toEqual( + expect.arrayContaining([ + expect.objectContaining({ command: "which", args: ["claude"] }), + expect.objectContaining({ + command: "poe-code", + args: [ + "configure", + "--yes", + "--provider", + "poe", + "claude-code" + ] + }), + expect.objectContaining({ command: "claude" }) + ]) + ); + expect(sandbox.requestLog).toContain("https://api.poe.com/v1/chat/completions"); + await expect(readdir(repoRoot)).resolves.not.toContain("hello.txt"); + } finally { + await rm(workspace, { recursive: true, force: true }); + } + }); +}); + +interface CapturedSandbox { + openSpecs: OpenSpec[]; + commands: Array<{ command: string; args: string[]; cwd?: string; env?: Record }>; + uploadedWorkspaces: Array<{ cwd: string; files: string[] }>; + downloadedWorkspaces: string[]; + requestLog: string[]; +} + +function createCapturedSandbox(): CapturedSandbox { + return { + openSpecs: [], + commands: [], + uploadedWorkspaces: [], + downloadedWorkspaces: [], + requestLog: [] + }; +} + +function createCapturedE2bFactory(sandbox: CapturedSandbox): ExecutionEnvFactory { + return { + type: "e2b", + supportsDetach: true, + async open(spec) { + sandbox.openSpecs.push(spec); + return { + id: "captured-sandbox", + job: null, + async uploadWorkspace() { + sandbox.uploadedWorkspaces.push({ + cwd: spec.cwd, + files: (await readdir(spec.cwd)).sort() + }); + return { files: 2, bytes: 1, skipped: [] }; + }, + async downloadWorkspace() { + sandbox.downloadedWorkspaces.push(spec.cwd); + return { files: 0, bytes: 0, conflicts: [] }; + }, + exec(runSpec) { + sandbox.commands.push({ + command: runSpec.command, + args: runSpec.args ?? [], + cwd: runSpec.cwd, + env: runSpec.env + }); + return runCapturedCommand(sandbox, runSpec); + }, + async detach() { + throw new Error("captured e2b fake does not support detach"); + }, + shell() { + throw new Error("captured e2b fake does not support shell"); + }, + async close() {} + }; + }, + async attach() { + throw new Error("captured e2b fake does not support attach"); + } + }; +} + +function runCapturedCommand(sandbox: CapturedSandbox, spec: RunSpec): RunHandle { + const stdout = new PassThrough(); + const stderr = new PassThrough(); + const result = new Promise<{ exitCode: number }>((resolve) => { + queueMicrotask(() => { + const response = capturedCommandResponse(sandbox, spec); + if (response.stdout) { + stdout.write(response.stdout); + } + if (response.stderr) { + stderr.write(response.stderr); + } + stdout.end(); + stderr.end(); + resolve({ exitCode: response.exitCode }); + }); + }); + + return { + pid: 123, + stdin: null, + stdout, + stderr, + result, + kill: vi.fn() + }; +} + +function capturedCommandResponse( + sandbox: CapturedSandbox, + spec: RunSpec +): { exitCode: number; stdout?: string; stderr?: string } { + if (spec.command === "which" && spec.args?.[0] === "claude") { + return { exitCode: 0, stdout: "/usr/local/bin/claude\n" }; + } + + if (spec.command === "poe-code" && spec.args?.[0] === "configure") { + return { exitCode: 0, stdout: "configured claude-code for poe\n" }; + } + + if (spec.command === "claude") { + if (!spec.env?.POE_API_KEY) { + return { exitCode: 1, stderr: "missing POE_API_KEY\n" }; + } + sandbox.requestLog.push("https://api.poe.com/v1/chat/completions"); + return { + exitCode: 0, + stdout: [ + JSON.stringify({ + type: "assistant", + message: { + content: [{ type: "text", text: "hello.txt says hello from the sandbox." }] + } + }), + JSON.stringify({ type: "result", usage: { input_tokens: 1, output_tokens: 1 } }), + "" + ].join("\n") + }; + } + + return { exitCode: 127, stderr: `${spec.command}: command not found\n` }; +} + +function createMemoryState() { + const jobs = new Map>(); + return { + templates: { + get: vi.fn(async () => null), + put: vi.fn(async () => undefined), + remove: vi.fn(async () => undefined), + list: vi.fn(async () => []) + }, + jobs: { + get: vi.fn(async (id: string) => jobs.get(id) ?? null), + put: vi.fn(async (entry: Record) => { + jobs.set(String(entry.id), entry); + }), + update: vi.fn(async (id: string, patch: Record) => { + const current = jobs.get(id); + if (!current) { + return null; + } + const updated = { ...current, ...patch, id }; + jobs.set(id, updated); + return updated; + }), + list: vi.fn(async () => Array.from(jobs.values())), + remove: vi.fn(async (id: string) => { + jobs.delete(id); + }) + } + }; +} diff --git a/packages/agent-spawn/src/spawn-interactive.ts b/packages/agent-spawn/src/spawn-interactive.ts index 7f625af5a2..2bedff159e 100644 --- a/packages/agent-spawn/src/spawn-interactive.ts +++ b/packages/agent-spawn/src/spawn-interactive.ts @@ -70,6 +70,7 @@ export async function spawnInteractive( const argv = [resolved.binaryName, ...args]; const execution = resolveSpawnExecution({ cwd: options.cwd ?? process.cwd(), + runtimeConfigCwd: options.runtimeConfigCwd, env: (processEnv ?? process.env) as Record, argv, tool: resolved.agentId, diff --git a/packages/agent-spawn/src/spawn.ts b/packages/agent-spawn/src/spawn.ts index 8f19b21d5a..559503f0d0 100644 --- a/packages/agent-spawn/src/spawn.ts +++ b/packages/agent-spawn/src/spawn.ts @@ -174,6 +174,7 @@ export async function spawn( const argv = [binaryName, ...spawnArgs]; const execution = resolveSpawnExecution({ cwd: options.cwd ?? process.cwd(), + runtimeConfigCwd: options.runtimeConfigCwd, env: (processEnv ?? process.env) as Record, argv, tool: resolvedId, diff --git a/packages/agent-spawn/src/types.ts b/packages/agent-spawn/src/types.ts index 3a602d0c7c..180ead8734 100644 --- a/packages/agent-spawn/src/types.ts +++ b/packages/agent-spawn/src/types.ts @@ -71,6 +71,8 @@ export interface SpawnOptions { runtimeImage?: string; /** E2B template override for e2b runtime. */ runtimeTemplate?: string; + /** Directory used to load runtime config/templates when different from cwd. */ + runtimeConfigCwd?: string; /** Run through a detached runtime job when the backend supports it. */ detach?: boolean; /** Mount the local poe-code checkout into the runtime for development. */ diff --git a/packages/runner-e2b/src/factory.ts b/packages/runner-e2b/src/factory.ts index 0825f890a3..7f738dc7dc 100644 --- a/packages/runner-e2b/src/factory.ts +++ b/packages/runner-e2b/src/factory.ts @@ -11,17 +11,18 @@ export const e2bExecutionEnvFactory: ExecutionEnvFactory = { supportsDetach: true, async open(spec): Promise { const runtime = parseE2bRuntime(spec.runtime); - const apiKey = await resolveE2bApiKey({ cwd: spec.cwd }); + const runtimeCwd = spec.runtimeCwd ?? spec.cwd; + const apiKey = await resolveE2bApiKey({ cwd: runtimeCwd }); const templateId = runtime.template_id ?? ( await buildE2bRuntimeTemplate({ runtime, dockerfilePath: path.resolve( - spec.cwd, + runtimeCwd, runtime.dockerfile ?? path.join(".poe-code", "Dockerfile") ), - buildContext: path.resolve(spec.cwd, runtime.build_context ?? "."), + buildContext: path.resolve(runtimeCwd, runtime.build_context ?? "."), state: spec.state, apiKey }) diff --git a/packages/runner-e2b/src/opened-env.test.ts b/packages/runner-e2b/src/opened-env.test.ts index eb2cd9fa4a..4cbbab840e 100644 --- a/packages/runner-e2b/src/opened-env.test.ts +++ b/packages/runner-e2b/src/opened-env.test.ts @@ -57,7 +57,7 @@ describe("createOpenedE2bEnv", () => { expect(sandbox.commands.run).toHaveBeenCalledWith("'printf' 'ok'", { background: true, cwd: "/sandbox/workspace", - envs: { A: "1" }, + envs: { A: "1", HOME: "/home/user" }, stdin: true, onStdout: expect.any(Function), onStderr: expect.any(Function) @@ -139,6 +139,38 @@ describe("createOpenedE2bEnv", () => { }); }); + it("uses the sandbox home instead of leaking the host HOME into commands", async () => { + const commandHandle = { + pid: 321, + wait: vi.fn().mockResolvedValue({ exitCode: 0 }), + kill: vi.fn() + }; + const sandbox = createSandboxMock(); + sandbox.commands.run.mockResolvedValue(commandHandle); + const env = createOpenedE2bEnv({ + sandbox, + runtime: createRuntime(), + spec: createSpec() + }); + + const handle = env.exec({ + command: "poe-code", + args: ["configure"], + cwd: "/repo", + env: { HOME: "/Users/local-dev", POE_API_KEY: "test-key" } + }); + + await expect(handle.result).resolves.toEqual({ exitCode: 0 }); + expect(sandbox.commands.run).toHaveBeenCalledWith("'poe-code' 'configure'", { + background: true, + cwd: "/workspace", + envs: { HOME: "/home/user", POE_API_KEY: "test-key" }, + stdin: false, + onStdout: expect.any(Function), + onStderr: expect.any(Function) + }); + }); + it("uses /workspace as the default sandbox workspace", async () => { const commandHandle = { pid: 321, @@ -230,7 +262,8 @@ describe("createOpenedE2bEnv", () => { expect.any(ArrayBuffer) ); expect(sandbox.commands.run).toHaveBeenCalledWith( - "mkdir -p '/sandbox/workspace' && tar -xf /tmp/poe-workspace-upload.tar -C '/sandbox/workspace'", + "mkdir -p '/sandbox/workspace' || { command -v sudo >/dev/null 2>&1 && sudo mkdir -p '/sandbox/workspace' && sudo chown \"$(id -u):$(id -g)\" '/sandbox/workspace'; }\n" + + "test -w '/sandbox/workspace' && tar -xf /tmp/poe-workspace-upload.tar -C '/sandbox/workspace'", { onStdout: expect.any(Function), onStderr: expect.any(Function) @@ -268,7 +301,7 @@ describe("createOpenedE2bEnv", () => { expect(thrown).toBeInstanceOf(Error); const message = (thrown as Error).message; expect(message).toContain( - "E2B command failed: mkdir -p '/sandbox/workspace' && tar -xf /tmp/poe-workspace-upload.tar -C '/sandbox/workspace'" + "E2B command failed: mkdir -p '/sandbox/workspace' || { command -v sudo >/dev/null 2>&1 && sudo mkdir -p '/sandbox/workspace'" ); expect(message).toContain("Last stderr output:"); expect(message).toContain("stderr line 6"); @@ -303,7 +336,9 @@ describe("createOpenedE2bEnv", () => { expect(thrown).toBeInstanceOf(Error); const message = (thrown as Error).message; - expect(message).toContain("E2B command failed: mkdir -p '/sandbox/workspace'"); + expect(message).toContain( + "E2B command failed: mkdir -p '/sandbox/workspace' || { command -v sudo" + ); expect(message).toContain("error stderr 6"); expect(message).toContain("error stderr 35"); expect(message).not.toContain("error stderr 5"); @@ -399,7 +434,7 @@ describe("createOpenedE2bEnv", () => { cols: expect.any(Number), rows: expect.any(Number), cwd: "/sandbox/workspace", - envs: {}, + envs: { HOME: "/home/user" }, onData: expect.any(Function) }); }); diff --git a/packages/runner-e2b/src/opened-env.ts b/packages/runner-e2b/src/opened-env.ts index c3b20264da..a10f43e6b8 100644 --- a/packages/runner-e2b/src/opened-env.ts +++ b/packages/runner-e2b/src/opened-env.ts @@ -94,7 +94,7 @@ export function createOpenedE2bEnv(input: { ); await runRemoteOrThrow( input.sandbox, - `mkdir -p ${shellQuote(sandboxWorkspaceDir)} && tar -xf /tmp/poe-workspace-upload.tar -C ${shellQuote(sandboxWorkspaceDir)}` + createUploadWorkspaceCommand(sandboxWorkspaceDir) ); return { files: 0, bytes: 0, skipped: [] }; } finally { @@ -132,7 +132,8 @@ export function createOpenedE2bEnv(input: { exec(spec) { const handle = runE2bCommand(input.sandbox, { ...spec, - cwd: mapWorkspaceCwd(spec.cwd) + cwd: mapWorkspaceCwd(spec.cwd), + env: resolveSandboxCommandEnv(spec.env) }); lastProcess = { started: handle.started }; return handle; @@ -167,7 +168,9 @@ export function createOpenedE2bEnv(input: { command, ...(shellSpec?.args ? { args: shellSpec.args } : {}), cwd: mapWorkspaceCwd(shellSpec?.cwd ?? input.spec.cwd), - env: shellSpec && "env" in shellSpec ? shellSpec.env : input.spec.env, + env: resolveSandboxCommandEnv( + shellSpec && "env" in shellSpec ? shellSpec.env : input.spec.env + ), stdin: "inherit", stdout: "inherit", stderr: "inherit", @@ -435,6 +438,26 @@ function shellQuote(value: string): string { return `'${value.replaceAll("'", "'\\''")}'`; } +function createUploadWorkspaceCommand(sandboxWorkspaceDir: string): string { + const quotedWorkspaceDir = shellQuote(sandboxWorkspaceDir); + return [ + `mkdir -p ${quotedWorkspaceDir} || { command -v sudo >/dev/null 2>&1 && sudo mkdir -p ${quotedWorkspaceDir} && sudo chown "$(id -u):$(id -g)" ${quotedWorkspaceDir}; }`, + `test -w ${quotedWorkspaceDir} && tar -xf /tmp/poe-workspace-upload.tar -C ${quotedWorkspaceDir}` + ].join("\n"); +} + +function resolveSandboxCommandEnv( + env: Record | undefined +): Record | undefined { + if (env === undefined) { + return undefined; + } + return { + ...env, + HOME: "/home/user" + }; +} + function normalizeSandboxWorkspaceDir(workspaceDir: string | undefined): string { const resolvedWorkspaceDir = workspaceDir ?? "/workspace"; if (!path.posix.isAbsolute(resolvedWorkspaceDir)) { diff --git a/src/cli/commands/auth-command.test.ts b/src/cli/commands/auth-command.test.ts index 2dc39cbc85..a12688925b 100644 --- a/src/cli/commands/auth-command.test.ts +++ b/src/cli/commands/auth-command.test.ts @@ -1,4 +1,4 @@ -import { describe, it, expect, beforeEach, vi } from "vitest"; +import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; import { Volume, createFsFromVolume } from "memfs"; import { createProgram } from "../program.js"; import type { FileSystem } from "../utils/file-system.js"; @@ -53,8 +53,11 @@ describe("auth command", () => { let fs: FileSystem; let logs: string[]; let httpClient: HttpClient; + let originalPoeApiKey: string | undefined; beforeEach(() => { + originalPoeApiKey = process.env.POE_API_KEY; + delete process.env.POE_API_KEY; fs = createMemfs(); logs = []; httpClient = vi.fn(); @@ -65,6 +68,14 @@ describe("auth command", () => { }); }); + afterEach(() => { + if (originalPoeApiKey === undefined) { + delete process.env.POE_API_KEY; + } else { + process.env.POE_API_KEY = originalPoeApiKey; + } + }); + it("shows logged-in identity from whoami endpoint", async () => { await storeApiKey(fs, "test-key"); diff --git a/src/cli/commands/spawn-command.test.ts b/src/cli/commands/spawn-command.test.ts index 0b26f3db1a..a1dadaaae7 100644 --- a/src/cli/commands/spawn-command.test.ts +++ b/src/cli/commands/spawn-command.test.ts @@ -235,7 +235,8 @@ describe("spawn command", () => { model: DEFAULT_CLAUDE_CODE_MODEL, mode: undefined, cwd: undefined, - activityTimeoutMs: 600_000 + activityTimeoutMs: 600_000, + runtimeConfigCwd: cwd }); const plainChunks = chunks.map((chunk) => stripAnsi(chunk)); @@ -781,7 +782,8 @@ describe("spawn command", () => { model: "some-model", mode: undefined, cwd: undefined, - activityTimeoutMs: 600_000 + activityTimeoutMs: 600_000, + runtimeConfigCwd: cwd }); }); @@ -809,7 +811,8 @@ describe("spawn command", () => { model: "openai/gpt-5.4", mode: undefined, cwd: undefined, - activityTimeoutMs: 600_000 + activityTimeoutMs: 600_000, + runtimeConfigCwd: cwd }); }); @@ -847,6 +850,7 @@ describe("spawn command", () => { mode: undefined, cwd: undefined, activityTimeoutMs: 600_000, + runtimeConfigCwd: cwd, mcpServers: { test: { command: "tiny-stdio-mcp-test-server", @@ -897,6 +901,7 @@ describe("spawn command", () => { mode: undefined, cwd: undefined, activityTimeoutMs: 600_000, + runtimeConfigCwd: cwd, mcpServers: { test: { command: "tiny-stdio-mcp-test-server", @@ -947,6 +952,7 @@ describe("spawn command", () => { mode: undefined, cwd: undefined, activityTimeoutMs: 600_000, + runtimeConfigCwd: cwd, mcpServers: { test: { command: "tiny-stdio-mcp-test-server", @@ -999,6 +1005,7 @@ describe("spawn command", () => { mode: undefined, cwd: undefined, activityTimeoutMs: 600_000, + runtimeConfigCwd: cwd, mcpServers: { test: { command: "tiny-stdio-mcp-test-server", @@ -1049,6 +1056,7 @@ describe("spawn command", () => { mode: undefined, cwd: undefined, activityTimeoutMs: 600_000, + runtimeConfigCwd: cwd, mcpServers: { test: { command: "tiny-stdio-mcp-test-server", @@ -1088,7 +1096,8 @@ describe("spawn command", () => { mode: undefined, cwd: undefined, logDir: "/tmp/spawn-logs", - activityTimeoutMs: 1500 + activityTimeoutMs: 1500, + runtimeConfigCwd: cwd }); }); @@ -1201,7 +1210,8 @@ describe("spawn command", () => { model: DEFAULT_CODEX_MODEL, mode: undefined, cwd: undefined, - activityTimeoutMs: 600_000 + activityTimeoutMs: 600_000, + runtimeConfigCwd: cwd }); }); @@ -1226,7 +1236,8 @@ describe("spawn command", () => { model: DEFAULT_CODEX_MODEL, mode: undefined, cwd: undefined, - activityTimeoutMs: 600_000 + activityTimeoutMs: 600_000, + runtimeConfigCwd: cwd }); }); @@ -1293,7 +1304,8 @@ describe("spawn command", () => { model: DEFAULT_CODEX_MODEL, mode: undefined, cwd: undefined, - activityTimeoutMs: 600_000 + activityTimeoutMs: 600_000, + runtimeConfigCwd: cwd }); }); @@ -1355,7 +1367,8 @@ describe("spawn command", () => { model: DEFAULT_CLAUDE_CODE_MODEL, mode: undefined, cwd: customCwd, - activityTimeoutMs: 600_000 + activityTimeoutMs: 600_000, + runtimeConfigCwd: cwd }); }); @@ -1387,7 +1400,8 @@ describe("spawn command", () => { model: DEFAULT_CODEX_MODEL, mode: undefined, cwd: resolved, - activityTimeoutMs: 600_000 + activityTimeoutMs: 600_000, + runtimeConfigCwd: cwd }); }); @@ -1435,7 +1449,8 @@ describe("spawn command", () => { args: [], model: DEFAULT_CODEX_MODEL, cwd: "/tmp/workspaces/poe-code", - mode: undefined + mode: undefined, + runtimeConfigCwd: cwd }); expect(cleanup).toHaveBeenCalledTimes(1); }); @@ -1468,7 +1483,8 @@ describe("spawn command", () => { model: DEFAULT_CODEX_MODEL, mode: undefined, cwd: undefined, - activityTimeoutMs: 600_000 + activityTimeoutMs: 600_000, + runtimeConfigCwd: cwd }); }); @@ -1500,7 +1516,8 @@ describe("spawn command", () => { model: DEFAULT_CODEX_MODEL, mode: undefined, cwd: undefined, - activityTimeoutMs: 600_000 + activityTimeoutMs: 600_000, + runtimeConfigCwd: cwd }); }); @@ -1757,7 +1774,9 @@ describe("spawn command", () => { prompt: "hello", args: [], model: DEFAULT_CLAUDE_CODE_MODEL, - cwd: undefined + cwd: undefined, + mode: undefined, + runtimeConfigCwd: cwd }); expect(sdkSpawn).not.toHaveBeenCalled(); }); @@ -1850,7 +1869,9 @@ describe("spawn command", () => { prompt: "hello", args: [], model: DEFAULT_GOOSE_MODEL, - cwd: undefined + cwd: undefined, + mode: undefined, + runtimeConfigCwd: cwd }); }); @@ -1908,7 +1929,9 @@ describe("spawn command", () => { prompt: "", args: [], model: DEFAULT_CLAUDE_CODE_MODEL, - cwd: undefined + cwd: undefined, + mode: undefined, + runtimeConfigCwd: cwd }); expect(sdkSpawn).not.toHaveBeenCalled(); }); @@ -1941,7 +1964,9 @@ describe("spawn command", () => { prompt: "hello", args: [], model: "anthropic/claude-opus-4.7", - cwd: undefined + cwd: undefined, + mode: undefined, + runtimeConfigCwd: cwd }); }); @@ -1978,7 +2003,9 @@ describe("spawn command", () => { prompt: "hello", args: [], model: "gpt-4", - cwd: "/projects/demo" + cwd: "/projects/demo", + mode: undefined, + runtimeConfigCwd: cwd }); }); }); diff --git a/src/cli/commands/spawn.ts b/src/cli/commands/spawn.ts index 22c3996042..915ff470d7 100644 --- a/src/cli/commands/spawn.ts +++ b/src/cli/commands/spawn.ts @@ -187,6 +187,7 @@ export function registerSpawnCommand( args: forwardedArgs, model, mode: commandOptions.mode as SpawnMode | undefined, + runtimeConfigCwd: container.env.cwd, ...runtimeOptions, ...(mcpServers ? { mcpServers } : {}), cwd: cwdOverride @@ -207,6 +208,7 @@ export function registerSpawnCommand( ...(integrations?.spawnMiddleware ? { middlewares: [integrations.spawnMiddleware] } : {}), + runtimeConfigCwd: container.env.cwd, ...runtimeOptions, useStdin: shouldReadFromStdin }; @@ -306,6 +308,7 @@ export function registerSpawnCommand( ? { activityTimeoutMs: spawnOptions.activityTimeoutMs } : {}), ...(spawnOptions.middlewares ? { middlewares: spawnOptions.middlewares } : {}), + runtimeConfigCwd: container.env.cwd, ...runtimeOptions }) ); diff --git a/src/providers/spawn-options.ts b/src/providers/spawn-options.ts index 237aea01bd..324429655d 100644 --- a/src/providers/spawn-options.ts +++ b/src/providers/spawn-options.ts @@ -16,6 +16,7 @@ export interface SpawnCommandOptions { runtime?: RuntimeOverrideOptions["runtime"]; runtimeImage?: string; runtimeTemplate?: string; + runtimeConfigCwd?: string; detach?: boolean; mountPoeCode?: boolean; } diff --git a/src/sdk/spawn.ts b/src/sdk/spawn.ts index 54ea948051..76cde84500 100644 --- a/src/sdk/spawn.ts +++ b/src/sdk/spawn.ts @@ -144,6 +144,7 @@ export function spawn( mode: options.mode, signal: options.signal, args: options.args, + runtimeConfigCwd: options.runtimeConfigCwd, ...runtimeOverrides, ...(resolvedMcpServers ? { mcpServers: resolvedMcpServers } : {}) }); @@ -223,6 +224,7 @@ export function spawn( mode: options.mode, args: options.args, signal: options.signal, + runtimeConfigCwd: options.runtimeConfigCwd, ...runtimeOverrides, ...(resolvedMcpServers ? { mcpServers: resolvedMcpServers } : {}), ...(options.tee ? { tee: options.tee } : {}), @@ -281,6 +283,7 @@ export function spawn( mode: options.mode, args: options.args, signal: options.signal, + runtimeConfigCwd: options.runtimeConfigCwd, ...runtimeOverrides, ...(resolvedMcpServers ? { mcpServers: resolvedMcpServers } : {}), ...(options.tee ? { tee: options.tee } : {}), diff --git a/src/sdk/types.ts b/src/sdk/types.ts index 23c7396f9d..7ad244bcd3 100644 --- a/src/sdk/types.ts +++ b/src/sdk/types.ts @@ -52,6 +52,8 @@ export interface SpawnOptions { runtimeImage?: string; /** E2B template id override for e2b runtime */ runtimeTemplate?: string; + /** Directory used to load runtime config/templates when different from cwd */ + runtimeConfigCwd?: string; /** Run as a detached runtime job when supported */ detach?: boolean; /** Mount the local poe-code checkout into the runtime for development */ From 5156edf2c7756a7fec712c4c2c1fa50a01418b93 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 02:53:42 -0500 Subject: [PATCH 065/111] fix: reuse e2b runtime for ralph --- docs/plans/e2b-runtime-spawn-fixes.md | 6 +- docs/plans/e2b-runtime-spawn-fixes.md.lock | 2 +- packages/agent-harness-tools/src/index.ts | 6 +- .../src/run-poe-command.test.ts | 127 +++++++++--- .../src/run-poe-command.ts | 123 ++++++++++- packages/ralph/README.md | 8 +- packages/ralph/src/ralph.test.ts | 42 ++++ packages/ralph/src/run/ralph.ts | 92 ++------- packages/ralph/src/types.ts | 14 +- .../__snapshots__/runtime-help.test.ts.snap | 1 + src/cli/commands/experiment-ralph.test.ts | 39 ++-- src/cli/commands/ralph.ts | 195 ++++++++++-------- src/sdk/ralph.test.ts | 110 ++++++++++ src/sdk/ralph.ts | 123 ++++++++++- 14 files changed, 648 insertions(+), 240 deletions(-) diff --git a/docs/plans/e2b-runtime-spawn-fixes.md b/docs/plans/e2b-runtime-spawn-fixes.md index 31f0ffedf8..1c0bcceecc 100644 --- a/docs/plans/e2b-runtime-spawn-fixes.md +++ b/docs/plans/e2b-runtime-spawn-fixes.md @@ -138,7 +138,7 @@ tasks: status: implement: done test: done - commit: open + commit: done - id: e2b-ralph-end-to-end title: Make `ralph run --runtime e2b` work end-to-end on a fake plan @@ -170,8 +170,8 @@ tasks: packages/ralph/README.md so future contributors don't aim ralph at the parent repo. status: - implement: open - test: open + implement: done + test: done commit: open - id: runner-sync-flag diff --git a/docs/plans/e2b-runtime-spawn-fixes.md.lock b/docs/plans/e2b-runtime-spawn-fixes.md.lock index 8b2b6559d6..1b04f9fc9f 100644 --- a/docs/plans/e2b-runtime-spawn-fixes.md.lock +++ b/docs/plans/e2b-runtime-spawn-fixes.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T07:27:31.200Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T07:52:23.734Z"} \ No newline at end of file diff --git a/packages/agent-harness-tools/src/index.ts b/packages/agent-harness-tools/src/index.ts index 7f7f140d5f..02df75e678 100644 --- a/packages/agent-harness-tools/src/index.ts +++ b/packages/agent-harness-tools/src/index.ts @@ -47,7 +47,11 @@ export { type LogStreamEnv, type LogStreamFs } from "./log-stream.js"; -export { runPoeCommand } from "./run-poe-command.js"; +export { + createPoeCommandSession, + runPoeCommand, + type PoeCommandSession +} from "./run-poe-command.js"; export { createBinaryExistsDetectors, type BinaryExistsDetector, diff --git a/packages/agent-harness-tools/src/run-poe-command.test.ts b/packages/agent-harness-tools/src/run-poe-command.test.ts index c08b15134c..6a769caff5 100644 --- a/packages/agent-harness-tools/src/run-poe-command.test.ts +++ b/packages/agent-harness-tools/src/run-poe-command.test.ts @@ -16,7 +16,7 @@ import type { UploadResult } from "./execution-env.js"; import type { LogStreamFs } from "./log-stream.js"; -import { runPoeCommand } from "./run-poe-command.js"; +import { createPoeCommandSession, runPoeCommand } from "./run-poe-command.js"; interface RecordingState { state: StateManager; @@ -317,6 +317,103 @@ describe("runPoeCommand", () => { expect(execStarted).toBe(true); }); + it("reuses an opened environment across session commands and downloads after each command", async () => { + const { state } = createRecordingState(); + const env = createMockEnv(); + let opens = 0; + const factory: ExecutionEnvFactory = { + type: "e2b", + async open() { + opens += 1; + return env; + }, + async attach() { + return env; + } + }; + const session = createPoeCommandSession({ factory, state }); + + const first = await session.run( + createOpenSpec({ + jobLabel: { tool: "poe-code", argv: ["poe-code", "--version"] } + }) + ); + const second = await session.run( + createOpenSpec({ + jobLabel: { tool: "poe-code", argv: ["poe-code", "--help"] } + }) + ); + + expect(first).toMatchObject({ kind: "sync", exitCode: 0 }); + expect(second).toMatchObject({ kind: "sync", exitCode: 0 }); + expect(opens).toBe(1); + expect(env.uploads).toBe(1); + expect(env.downloads).toEqual([{ conflictPolicy: "refuse" }, { conflictPolicy: "refuse" }]); + expect(env.closed).toBe(false); + + await session.close(); + expect(env.closed).toBe(true); + }); + + it("syncs a reused session workspace back after each command while keeping remote state for the next command", async () => { + const { state } = createRecordingState(); + const env = createMockEnv(); + let localIterations = ""; + let remoteIterations = ""; + + env.uploadWorkspace = async () => { + env.uploads += 1; + remoteIterations = localIterations; + return { files: 1, bytes: Buffer.byteLength(localIterations), skipped: [] }; + }; + env.downloadWorkspace = async (call) => { + env.downloads.push(call); + localIterations = remoteIterations; + return { files: 1, bytes: Buffer.byteLength(localIterations), conflicts: [] }; + }; + env.exec = (spec): RunHandle => { + env.execSpecs.push(spec); + const nextIteration = remoteIterations.trim().length === 0 + ? 1 + : remoteIterations.trim().split("\n").length + 1; + remoteIterations += `${nextIteration}\n`; + return { + pid: 123, + stdout: null, + stderr: null, + stdin: null, + result: Promise.resolve({ exitCode: 0 }), + kill() {} + }; + }; + + const session = createPoeCommandSession({ factory: createE2bFactory(env), state }); + const openSpec = createOpenSpec({ + execution: { wrapForLogTee: false }, + jobLabel: { tool: "append-iteration", argv: ["append-iteration"] }, + runner: { + detach: false, + upload_max_file_mb: 100, + download_conflict: "overwrite" + } + }); + + await session.run(openSpec); + expect(localIterations).toBe("1\n"); + + await session.run(openSpec); + expect(localIterations).toBe("1\n2\n"); + expect(remoteIterations).toBe("1\n2\n"); + expect(env.uploads).toBe(1); + expect(env.downloads).toEqual([ + { conflictPolicy: "overwrite" }, + { conflictPolicy: "overwrite" } + ]); + expect(env.execSpecs).toHaveLength(2); + + await session.close(); + }); + it("configures the spawned E2B agent after upload and before the agent command", async () => { const { state } = createRecordingState(); const env = createMockEnv(); @@ -346,14 +443,7 @@ describe("runPoeCommand", () => { expect(env.execSpecs.map((spec) => [spec.command, ...(spec.args ?? [])])).toEqual([ ["which", "claude"], - [ - "poe-code", - "configure", - "--yes", - "--provider", - "poe", - "claude-code" - ], + ["poe-code", "configure", "--yes", "--provider", "poe", "claude-code"], ["sh", "-c", expect.stringContaining("'claude' '-p' 'hello'")] ]); expect(env.execSpecs[1]).toMatchObject({ @@ -375,9 +465,7 @@ describe("runPoeCommand", () => { const isBinaryCheck = spec.command === "which" || spec.command === "where" || - (spec.command === "sh" && - spec.args?.[0] === "-c" && - spec.args[1]?.includes("test -f")); + (spec.command === "sh" && spec.args?.[0] === "-c" && spec.args[1]?.includes("test -f")); if (isBinaryCheck) { return { pid: 123, @@ -442,11 +530,7 @@ describe("runPoeCommand", () => { kill() {} }; } - if ( - spec.command === "sh" && - spec.args?.[0] === "-c" && - spec.args[1]?.includes("test -f") - ) { + if (spec.command === "sh" && spec.args?.[0] === "-c" && spec.args[1]?.includes("test -f")) { return { pid: 123, stdout: null, @@ -536,14 +620,7 @@ describe("runPoeCommand", () => { expect(env.execSpecs.map((spec) => [spec.command, ...(spec.args ?? [])])).toEqual([ ["which", "claude"], - [ - "poe-code", - "configure", - "--yes", - "--provider", - "poe", - "claude-code" - ] + ["poe-code", "configure", "--yes", "--provider", "poe", "claude-code"] ]); }); diff --git a/packages/agent-harness-tools/src/run-poe-command.ts b/packages/agent-harness-tools/src/run-poe-command.ts index 6eed5ab327..2762cfcb1a 100644 --- a/packages/agent-harness-tools/src/run-poe-command.ts +++ b/packages/agent-harness-tools/src/run-poe-command.ts @@ -121,6 +121,124 @@ export async function runPoeCommand(opts: { } } +export interface PoeCommandSession { + run( + openSpec: OpenSpec, + signal?: AbortSignal + ): Promise<{ + kind: "sync"; + exitCode: number; + download: DownloadResult; + stdout?: string; + stderr?: string; + }>; + close(): Promise; +} + +export function createPoeCommandSession(opts: { + factory: ExecutionEnvFactory; + state: StateManager; +}): PoeCommandSession { + let env: OpenedEnv | null = null; + let closed = false; + + async function getEnv(openSpec: OpenSpec): Promise { + if (closed) { + throw new Error("Cannot run command after Poe command session is closed."); + } + + if (env !== null) { + return env; + } + + const opened = opts.factory.open(openSpec); + env = isPromiseLike(opened) ? await opened : opened; + await env.uploadWorkspace(); + return env; + } + + return { + async run(openSpec, signal) { + const jobId = createUlid(); + const pendingJob = opts.state.jobs.put({ + id: jobId, + env_id: "", + env_kind: opts.factory.type, + tool: openSpec.jobLabel.tool, + argv: openSpec.jobLabel.argv, + cwd: openSpec.cwd, + started_at: "", + status: "pending" + }); + const currentEnv = await getEnv(openSpec); + await pendingJob; + await configureE2bSpawnAgentIfAvailable({ + env: currentEnv, + openSpec, + factoryType: opts.factory.type + }); + const wrapCommand = openSpec.execution?.wrapForLogTee !== false; + const argv = wrapCommand + ? wrapForLogTee(openSpec.jobLabel.argv, jobId) + : openSpec.jobLabel.argv; + const handle = openSpec.execution?.tty + ? currentEnv.shell() + : currentEnv.exec({ + command: argv[0], + args: argv.slice(1), + cwd: openSpec.cwd, + env: resolveExecutionEnv(openSpec), + stdin: openSpec.execution?.stdin ?? "inherit", + stdout: openSpec.execution?.stdout ?? "pipe", + stderr: openSpec.execution?.stderr ?? "pipe", + signal + }); + + if (openSpec.execution?.input !== undefined) { + handle.stdin?.setDefaultEncoding("utf8"); + handle.stdin?.end(openSpec.execution.input); + } + + await opts.state.jobs.update(jobId, { + status: "running", + env_id: currentEnv.id, + started_at: new Date().toISOString() + }); + + const result = await runSync({ + env: currentEnv, + handle, + jobId, + openSpec, + signal, + wrapCommand, + closeAfterDownload: false + }); + + await opts.state.jobs.update(jobId, { + status: "exited", + exit_code: result.exitCode, + exited_at: new Date().toISOString() + }); + + return { + kind: "sync", + exitCode: result.exitCode, + download: result.download, + ...(result.stdout !== undefined ? { stdout: result.stdout } : {}), + ...(result.stderr !== undefined ? { stderr: result.stderr } : {}) + }; + }, + async close() { + if (closed) { + return; + } + closed = true; + await env?.close(); + } + }; +} + async function configureE2bSpawnAgentIfAvailable(opts: { env: OpenedEnv; openSpec: OpenSpec; @@ -243,6 +361,7 @@ async function runSync(opts: { openSpec: OpenSpec; signal?: AbortSignal; wrapCommand: boolean; + closeAfterDownload?: boolean; }): Promise<{ exitCode: number; download: DownloadResult; stdout?: string; stderr?: string }> { const execution = opts.openSpec.execution; const capture = execution?.captureOutput === true; @@ -259,7 +378,9 @@ async function runSync(opts: { const download = await opts.env.downloadWorkspace({ conflictPolicy: opts.openSpec.runner?.download_conflict ?? "refuse" }); - await opts.env.close(); + if (opts.closeAfterDownload !== false) { + await opts.env.close(); + } return { exitCode, download, diff --git a/packages/ralph/README.md b/packages/ralph/README.md index 4ccbffa579..8834a03b04 100644 --- a/packages/ralph/README.md +++ b/packages/ralph/README.md @@ -57,6 +57,8 @@ Ralph supports `{{ variable }}` syntax in doc bodies. Variables are interpolated | Variable | Resolves to | |---|---| | `{{ current_file }}` | Absolute path of the Ralph doc being run | +| `{{ current_iteration }}` | Current one-based Ralph iteration number | +| `{{ max_iterations }}` | Configured maximum Ralph iterations | ```markdown --- @@ -92,6 +94,10 @@ POE_RALPH_PLAN_DIRECTORY=docs/plans poe-code ralph run poe-code ralph run docs/plans/refactor-auth.md ``` +## Runtime Workspaces + +When validating Ralph against a remote runtime such as E2B, create a fresh temporary workspace with `mkdtemp`, put only the Ralph plan and intended test files in that directory, pass the plan path directly, and run with `--cwd `. Do not aim Ralph runtime tests at the poe-code checkout or a parent repository; Ralph agents are expected to edit their working directory across iterations, and remote runtime downloads overwrite the tmpdir copy after each iteration so the next iteration sees the prior edits. + ## Dashboard Configuration Ralph runs can render the live dashboard in terminal TTY mode. @@ -112,7 +118,7 @@ POE_RALPH_TUI=true poe-code ralph run ```bash poe-code ralph init [doc] [--agent ] [--iterations ] -poe-code ralph run [doc] [--agent ] [--iterations ] [--tui|--no-tui] +poe-code ralph run [doc] [--agent ] [--iterations ] [--cwd ] [--tui|--no-tui] ``` ## Package API diff --git a/packages/ralph/src/ralph.test.ts b/packages/ralph/src/ralph.test.ts index 7a5738e022..97c51a85cc 100644 --- a/packages/ralph/src/ralph.test.ts +++ b/packages/ralph/src/ralph.test.ts @@ -854,6 +854,18 @@ describe("createRalphSimulation", () => { expect(prompts[0]).toBe("Fix issues in /repo/.poe-code/ralph/plans/plan.md"); }); + it("interpolates iteration variables for each prompt sent to the agent", async () => { + const sim = createRalphSimulation({ + docContent: "Append {{ current_iteration }} of {{ max_iterations }}", + maxIterations: 2, + turns: [successTurn(), successTurn()] + }); + + const { prompts } = await sim.run(); + + expect(prompts).toEqual(["Append 1 of 2", "Append 2 of 2"]); + }); + it("preserves {{ current_file }} template in the file after run", async () => { const sim = createRalphSimulation({ docContent: "Fix {{ current_file }}", @@ -982,6 +994,36 @@ describe("createRalphSimulation", () => { }); }); + it("passes runtime config cwd through to the agent runner", async () => { + const { fs } = createRunFs({ + "/repo/docs/plan.md": "# Runtime plan" + }); + const runAgent = vi.fn(async () => ({ + stdout: "", + stderr: "", + exitCode: 0 + })); + + await runRalph({ + cwd: "/tmp/ralph-work", + homeDir: "/home/test", + docPath: "/repo/docs/plan.md", + maxIterations: 1, + runtime: "e2b", + runtimeConfigCwd: "/repo", + fs, + runAgent + }); + + expect(runAgent).toHaveBeenCalledWith( + expect.objectContaining({ + cwd: "/tmp/ralph-work", + runtime: "e2b", + runtimeConfigCwd: "/repo" + }) + ); + }); + it("stops on first failed iteration", async () => { const sim = createRalphSimulation({ docContent: "Keep trying", diff --git a/packages/ralph/src/run/ralph.ts b/packages/ralph/src/run/ralph.ts index ccad131ce5..4fc9503e4c 100644 --- a/packages/ralph/src/run/ralph.ts +++ b/packages/ralph/src/run/ralph.ts @@ -18,12 +18,7 @@ import { writeFrontmatter, type RalphPlanStatus } from "../frontmatter/frontmatter.js"; -import type { - RalphFileStat, - RalphFileSystem, - RalphRunOptions, - RalphRunResult -} from "../types.js"; +import type { RalphFileStat, RalphFileSystem, RalphRunOptions, RalphRunResult } from "../types.js"; import { interpolateVariables } from "../variables/variables.js"; class RalphWorkflowStopError extends Error { @@ -33,20 +28,14 @@ class RalphWorkflowStopError extends Error { } } -export async function runRalph( - options: RalphRunOptions -): Promise { +export async function runRalph(options: RalphRunOptions): Promise { const fs = options.fs ?? createDefaultFs(); const runAgent = options.runAgent; if (!runAgent) { throw new Error("runRalph requires a runAgent implementation."); } - const absoluteDocPath = resolveWorkflowPath( - options.docPath, - options.cwd, - options.homeDir - ); + const absoluteDocPath = resolveWorkflowPath(options.docPath, options.cwd, options.homeDir); const runLogDir = resolveRunLogDir({ planPath: absoluteDocPath, runner: "ralph", @@ -56,6 +45,7 @@ export async function runRalph( const startTime = Date.now(); let iterationsCompleted = 0; let currentIterationStart = 0; + let currentIterationNumber = 0; let stopReason: RalphRunResult["stopReason"] = "max_iterations"; let archived = false; let fatalError: unknown; @@ -74,18 +64,9 @@ export async function runRalph( fs, signal: options.signal, readConfig: async (content) => { - const fresh = await resolveDocumentConfigFromContent( - options, - fs, - absoluteDocPath, - content - ); + const fresh = await resolveDocumentConfigFromContent(options, fs, absoluteDocPath, content); return { - frontmatter: createWorkflowFrontmatter( - fresh.agents, - fresh.maxIterations, - fresh.prompt - ), + frontmatter: createWorkflowFrontmatter(fresh.agents, fresh.maxIterations, fresh.prompt), body: fresh.prompt }; }, @@ -95,18 +76,20 @@ export async function runRalph( try { const result = await runAgent({ agent: specifier.agent, - prompt: input.prompt, + prompt: interpolateVariables(input.prompt, { + current_iteration: String(currentIterationNumber), + max_iterations: String(config.maxIterations) + }), cwd: input.cwd, logDir: runLogDir, logFileName: makeRunLogFileName(specifier.agent), ...(options.runtime ? { runtime: options.runtime } : {}), ...(options.runtimeImage ? { runtimeImage: options.runtimeImage } : {}), ...(options.runtimeTemplate ? { runtimeTemplate: options.runtimeTemplate } : {}), + ...(options.runtimeConfigCwd ? { runtimeConfigCwd: options.runtimeConfigCwd } : {}), ...(options.detach ? { detach: options.detach } : {}), ...(options.mountPoeCode ? { mountPoeCode: options.mountPoeCode } : {}), - ...(specifier.model ?? input.model - ? { model: specifier.model ?? input.model } - : {}), + ...((specifier.model ?? input.model) ? { model: specifier.model ?? input.model } : {}), ...(input.signal ? { signal: input.signal } : {}) }); @@ -134,17 +117,14 @@ export async function runRalph( }, onIterationStart: async (iteration) => { currentIterationStart = Date.now(); + currentIterationNumber = iteration + 1; if (iteration === 0) { await updateFrontmatter(fs, absoluteDocPath, "in_progress", 0); } const currentSpecifier = config.agents[iteration % config.agents.length]!; - options.onIterationStart?.( - iteration + 1, - config.maxIterations, - currentSpecifier.agent - ); + options.onIterationStart?.(iteration + 1, config.maxIterations, currentSpecifier.agent); }, onIterationEnd: async (iteration, result) => { const iterationNumber = iteration + 1; @@ -154,12 +134,7 @@ export async function runRalph( if (lastStopKind === "failed") { iterationsCompleted = iterationNumber; stopReason = "failed"; - await updateFrontmatter( - fs, - absoluteDocPath, - "failed", - iterationsCompleted - ); + await updateFrontmatter(fs, absoluteDocPath, "failed", iterationsCompleted); options.onIterationComplete?.(iterationNumber, durationMs, false); return; } @@ -192,24 +167,14 @@ export async function runRalph( } if (iterationNumber === config.maxIterations) { - await updateFrontmatter( - fs, - absoluteDocPath, - "completed", - iterationsCompleted - ); + await updateFrontmatter(fs, absoluteDocPath, "completed", iterationsCompleted); await archivePlan(fs, absoluteDocPath); archived = true; stopReason = "max_iterations"; return; } - await updateFrontmatter( - fs, - absoluteDocPath, - "in_progress", - iterationsCompleted - ); + await updateFrontmatter(fs, absoluteDocPath, "in_progress", iterationsCompleted); } }); } catch (error) { @@ -238,12 +203,7 @@ export async function runRalph( await updateFrontmatter(fs, absoluteDocPath, "open", iterationsCompleted); } - return createRunResult( - options.docPath, - startTime, - iterationsCompleted, - stopReason - ); + return createRunResult(options.docPath, startTime, iterationsCompleted, stopReason); } function createRunResult( @@ -470,16 +430,11 @@ async function updateFrontmatter( iteration: number ): Promise { const currentContent = await fs.readFile(absoluteDocPath, "utf8"); - const { data: currentFrontmatter, body: currentBody } = - parseFrontmatter(currentContent); + const { data: currentFrontmatter, body: currentBody } = parseFrontmatter(currentContent); const content = writeFrontmatter( { - ...(currentFrontmatter.agent !== undefined - ? { agent: currentFrontmatter.agent } - : {}), - ...(currentFrontmatter.extends !== undefined - ? { extends: currentFrontmatter.extends } - : {}), + ...(currentFrontmatter.agent !== undefined ? { agent: currentFrontmatter.agent } : {}), + ...(currentFrontmatter.extends !== undefined ? { extends: currentFrontmatter.extends } : {}), ...(currentFrontmatter.iterations !== undefined ? { iterations: currentFrontmatter.iterations } : {}), @@ -493,10 +448,7 @@ async function updateFrontmatter( await fs.writeFile(absoluteDocPath, content); } -async function archivePlan( - fs: RalphFileSystem, - absoluteDocPath: string -): Promise { +async function archivePlan(fs: RalphFileSystem, absoluteDocPath: string): Promise { const dir = path.dirname(absoluteDocPath); const archiveDir = path.join(dir, "archive"); const archivePath = path.join(archiveDir, path.basename(absoluteDocPath)); diff --git a/packages/ralph/src/types.ts b/packages/ralph/src/types.ts index f15cef521a..bc15a87958 100644 --- a/packages/ralph/src/types.ts +++ b/packages/ralph/src/types.ts @@ -22,6 +22,7 @@ export interface AgentRunInput { runtime?: "host" | "docker" | "e2b"; runtimeImage?: string; runtimeTemplate?: string; + runtimeConfigCwd?: string; detach?: boolean; mountPoeCode?: boolean; signal?: AbortSignal; @@ -53,19 +54,12 @@ export interface RalphRunOptions { runtime?: "host" | "docker" | "e2b"; runtimeImage?: string; runtimeTemplate?: string; + runtimeConfigCwd?: string; detach?: boolean; mountPoeCode?: boolean; fs?: RalphFileSystem; runAgent?: (input: AgentRunInput) => Promise; - onIterationStart?: ( - iteration: number, - maxIterations: number, - agent: string - ) => void; - onIterationComplete?: ( - iteration: number, - durationMs: number, - success: boolean - ) => void; + onIterationStart?: (iteration: number, maxIterations: number, agent: string) => void; + onIterationComplete?: (iteration: number, durationMs: number, success: boolean) => void; signal?: AbortSignal; } diff --git a/src/cli/commands/__snapshots__/runtime-help.test.ts.snap b/src/cli/commands/__snapshots__/runtime-help.test.ts.snap index c5c6450e3e..fd823363cc 100644 --- a/src/cli/commands/__snapshots__/runtime-help.test.ts.snap +++ b/src/cli/commands/__snapshots__/runtime-help.test.ts.snap @@ -38,6 +38,7 @@ Arguments: Options: --agent Override the agent from frontmatter --iterations Override iterations from frontmatter + -C, --cwd Working directory for the Ralph agent loop --tui Show a live dashboard while Ralph is running --no-tui Disable the live dashboard for this Ralph run --runtime Override runtime backend: host | docker | e2b diff --git a/src/cli/commands/experiment-ralph.test.ts b/src/cli/commands/experiment-ralph.test.ts index 280c593fee..88ee363c36 100644 --- a/src/cli/commands/experiment-ralph.test.ts +++ b/src/cli/commands/experiment-ralph.test.ts @@ -470,14 +470,9 @@ describe("experiment run command", () => { it("preserves multi-agent frontmatter arrays for experiment run", async () => { const container = createCliContainer({ fs: createMemFs({ - "/repo/docs/loop.md": [ - "---", - "agent:", - " - claude", - " - codex", - "---", - "# Loop" - ].join("\n") + "/repo/docs/loop.md": ["---", "agent:", " - claude", " - codex", "---", "# Loop"].join( + "\n" + ) }), prompts: vi.fn().mockResolvedValue({}), env: { cwd, homeDir }, @@ -559,12 +554,7 @@ describe("experiment run command", () => { it("fails fast on unknown single frontmatter agents", async () => { const container = createCliContainer({ fs: createMemFs({ - "/repo/docs/loop.md": [ - "---", - "agent: mystery-agent", - "---", - "# Loop" - ].join("\n") + "/repo/docs/loop.md": ["---", "agent: mystery-agent", "---", "# Loop"].join("\n") }), prompts: vi.fn().mockResolvedValue({}), env: { cwd, homeDir }, @@ -1720,16 +1710,19 @@ describe("ralph run command", () => { "--agent", "claude", "--iterations", - "5" + "5", + "--cwd", + "/tmp/ralph-work" ]); expect(vi.mocked(sdkRunRalph)).toHaveBeenCalledWith( expect.objectContaining({ agent: "claude-code", - cwd, + cwd: "/tmp/ralph-work", homeDir, docPath: "docs/loop.md", - maxIterations: 5 + maxIterations: 5, + runtimeConfigCwd: cwd }) ); }); @@ -2119,15 +2112,7 @@ describe("ralph run command", () => { const program = createBaseProgram(); registerRalphCommand(program, container); - await program.parseAsync([ - "node", - "cli", - "ralph", - "run", - "docs/loop.md", - "--agent", - "goose" - ]); + await program.parseAsync(["node", "cli", "ralph", "run", "docs/loop.md", "--agent", "goose"]); expect(selectMock).not.toHaveBeenCalled(); expect(promptTextMock).not.toHaveBeenCalled(); @@ -2301,7 +2286,7 @@ describe("ralph run command", () => { expect(dashboardMock.appendOutput.mock.calls.map(([item]) => item)).toEqual([ { kind: "info", - text: `${expectedTimestamp} Config · Agent: claude-code · Iterations: 5 · Doc: docs/loop.md`, + text: `${expectedTimestamp} Config · Agent: claude-code · Iterations: 5 · Cwd: /repo · Doc: docs/loop.md`, ts: 0 }, { diff --git a/src/cli/commands/ralph.ts b/src/cli/commands/ralph.ts index f4c8262458..ec065b1caf 100644 --- a/src/cli/commands/ralph.ts +++ b/src/cli/commands/ralph.ts @@ -40,7 +40,11 @@ import { registerDashboardQuitCommands, shouldUseInteractiveDashboard } from "./dashboard-loop-shared.js"; -import { addRuntimeOptions, pickRuntimeOptions, type RuntimeCliOptions } from "./runtime-options.js"; +import { + addRuntimeOptions, + pickRuntimeOptions, + type RuntimeCliOptions +} from "./runtime-options.js"; const DEFAULT_RALPH_AGENT = "claude-code"; const DEFAULT_RALPH_ITERATIONS = 3; @@ -48,6 +52,7 @@ const DEFAULT_RALPH_ITERATIONS = 3; type RalphDashboardRunOptions = { agent: string | string[]; docPath: string; + cwd: string; maxIterations: number; runOptions: RalphRunOptions; runtimeOptions: RuntimeCliOptions; @@ -60,11 +65,13 @@ function formatRalphAgentSummary(agent: string | string[]): string { function formatRalphConfigSummary(options: { agent: string | string[]; docPath: string; + cwd: string; maxIterations: number; }): string { return [ `Agent: ${formatRalphAgentSummary(options.agent)}`, `Iterations: ${options.maxIterations}`, + `Cwd: ${options.cwd}`, `Doc: ${options.docPath}` ].join(" · "); } @@ -103,6 +110,7 @@ function createRalphDashboardRunAgent(options: { model: input.model, mode: "yolo", ...options.runtimeOptions, + ...(input.runtimeConfigCwd ? { runtimeConfigCwd: input.runtimeConfigCwd } : {}), ...(input.signal ? { signal: input.signal } : {}), useStdin: true, tee: { @@ -678,108 +686,115 @@ export function registerRalphCommand(program: Command, container: CliContainer): .argument("[doc]", "Markdown doc path") .option("--agent ", "Override the agent from frontmatter") .option("--iterations ", "Override iterations from frontmatter") + .option("-C, --cwd ", "Working directory for the Ralph agent loop") .option("--tui", "Show a live dashboard while Ralph is running") .option("--no-tui", "Disable the live dashboard for this Ralph run"); - addRuntimeOptions(run) - .action(async function (this: Command, docArg?: string) { - const flags = resolveCommandFlags(program); - const resources = createExecutionResources(container, flags, "ralph:run"); - const options = this.opts<{ + addRuntimeOptions(run).action(async function (this: Command, docArg?: string) { + const flags = resolveCommandFlags(program); + const resources = createExecutionResources(container, flags, "ralph:run"); + const options = this.opts< + { agent?: string; iterations?: string; + cwd?: string; tui?: boolean; - } & RuntimeCliOptions>(); - const runtimeOptions = pickRuntimeOptions(options); + } & RuntimeCliOptions + >(); + const runtimeOptions = pickRuntimeOptions(options); - resources.logger.intro("ralph run"); + resources.logger.intro("ralph run"); - try { - const commandConfig = await resolveRalphCommandConfig(container); - const docPath = await resolveDocPath({ - container, - program, - providedDoc: docArg, - planDirectory: commandConfig.planDirectory - }); - if (!docPath) { - return; - } + try { + const commandConfig = await resolveRalphCommandConfig(container); + const docPath = await resolveDocPath({ + container, + program, + providedDoc: docArg, + planDirectory: commandConfig.planDirectory + }); + if (!docPath) { + return; + } - const doc = await readRalphDoc(container, docPath); - const agent = await resolveRunAgent({ - container, - program, - providedAgent: options.agent, - frontmatterAgent: doc.data.agent - }); - if (!agent) { - return; - } + const doc = await readRalphDoc(container, docPath); + const agent = await resolveRunAgent({ + container, + program, + providedAgent: options.agent, + frontmatterAgent: doc.data.agent + }); + if (!agent) { + return; + } - const maxIterations = await resolveRunIterations({ - program, - providedIterations: options.iterations, - frontmatterIterations: doc.data.iterations - }); - if (maxIterations == null) { - return; - } + const maxIterations = await resolveRunIterations({ + program, + providedIterations: options.iterations, + frontmatterIterations: doc.data.iterations + }); + if (maxIterations == null) { + return; + } - const runOptions: RalphRunOptions = { - agent, - cwd: container.env.cwd, - homeDir: container.env.homeDir, - docPath, - maxIterations, - ...runtimeOptions - }; - const useDashboard = shouldUseInteractiveDashboard(options.tui ?? commandConfig.tui); - const result = useDashboard - ? await runRalphWithDashboard({ - agent, - docPath, - maxIterations, - runOptions, - runtimeOptions - }) - : await sdkRunRalph({ - ...runOptions, - onIterationStart(iteration, total, currentAgent) { - resources.logger.info(`Iteration ${iteration}/${total} (${currentAgent})`); - }, - onIterationComplete(iteration, durationMs, success) { - const status = success ? "done" : "failed"; - resources.logger.info( - `Iteration ${iteration} ${status} in ${formatDashboardDuration(durationMs)}` - ); - } - }); - - const summary = [ - `Iterations: ${result.iterationsCompleted}/${maxIterations}`, - `Doc: ${result.docPath}`, - `Duration: ${formatDashboardDuration(result.totalDurationMs)}` - ].join("\n "); - - if (result.stopReason === "cancelled") { - process.exitCode = 130; - resources.logger.warn("Ralph run cancelled."); - resources.logger.resolved("Run summary", summary); - return; - } + const runCwd = options.cwd ? path.resolve(container.env.cwd, options.cwd) : container.env.cwd; + + const runOptions: RalphRunOptions = { + agent, + cwd: runCwd, + homeDir: container.env.homeDir, + docPath, + maxIterations, + runtimeConfigCwd: container.env.cwd, + ...runtimeOptions + }; + const useDashboard = shouldUseInteractiveDashboard(options.tui ?? commandConfig.tui); + const result = useDashboard + ? await runRalphWithDashboard({ + agent, + docPath, + cwd: runCwd, + maxIterations, + runOptions, + runtimeOptions + }) + : await sdkRunRalph({ + ...runOptions, + onIterationStart(iteration, total, currentAgent) { + resources.logger.info(`Iteration ${iteration}/${total} (${currentAgent})`); + }, + onIterationComplete(iteration, durationMs, success) { + const status = success ? "done" : "failed"; + resources.logger.info( + `Iteration ${iteration} ${status} in ${formatDashboardDuration(durationMs)}` + ); + } + }); - if (result.stopReason === "failed") { - process.exitCode = 1; - resources.logger.error("Agent run failed."); - resources.logger.resolved("Run summary", summary); - return; - } + const summary = [ + `Iterations: ${result.iterationsCompleted}/${maxIterations}`, + `Doc: ${result.docPath}`, + `Duration: ${formatDashboardDuration(result.totalDurationMs)}` + ].join("\n "); + if (result.stopReason === "cancelled") { + process.exitCode = 130; + resources.logger.warn("Ralph run cancelled."); resources.logger.resolved("Run summary", summary); - resources.logger.success("Ralph run finished."); - } finally { - resources.context.finalize(); + return; } - }); + + if (result.stopReason === "failed") { + process.exitCode = 1; + resources.logger.error("Agent run failed."); + resources.logger.resolved("Run summary", summary); + return; + } + + resources.logger.resolved("Run summary", summary); + resources.logger.success("Ralph run finished."); + } finally { + resources.context.finalize(); + } + }); } diff --git a/src/sdk/ralph.test.ts b/src/sdk/ralph.test.ts index 2cca1de640..510452a0cf 100644 --- a/src/sdk/ralph.test.ts +++ b/src/sdk/ralph.test.ts @@ -3,6 +3,9 @@ import type { RalphRunOptions } from "@poe-code/ralph"; const runWorkspaceRalphMock = vi.hoisted(() => vi.fn()); const spawnAutonomousMock = vi.hoisted(() => vi.fn()); +const buildSpawnArgsMock = vi.hoisted(() => vi.fn()); +const createPoeCommandSessionMock = vi.hoisted(() => vi.fn()); +const resolvePoeCommandExecutionMock = vi.hoisted(() => vi.fn()); vi.mock("@poe-code/ralph", async (importOriginal) => { const actual = await importOriginal(); @@ -18,12 +21,24 @@ vi.mock("./spawn.js", () => ({ }) })); +vi.mock("@poe-code/agent-spawn", () => ({ + buildSpawnArgs: buildSpawnArgsMock +})); + +vi.mock("@poe-code/agent-harness-tools", () => ({ + createPoeCommandSession: createPoeCommandSessionMock, + resolvePoeCommandExecution: resolvePoeCommandExecutionMock +})); + import { runRalph } from "./ralph.js"; describe("SDK ralph", () => { beforeEach(() => { runWorkspaceRalphMock.mockReset(); spawnAutonomousMock.mockReset(); + buildSpawnArgsMock.mockReset(); + createPoeCommandSessionMock.mockReset(); + resolvePoeCommandExecutionMock.mockReset(); }); it("preserves a caller-provided runAgent", async () => { @@ -116,4 +131,99 @@ describe("SDK ralph", () => { exitCode: 0 }); }); + + it("reuses one e2b command session for the default Ralph runner", async () => { + const run = vi.fn().mockResolvedValue({ + kind: "sync", + stdout: "done", + stderr: "", + exitCode: 0, + download: { files: 1, bytes: 12, conflicts: [] } + }); + const close = vi.fn().mockResolvedValue(undefined); + const factory = { type: "e2b" }; + const state = { jobs: {} }; + let capturedOptions: RalphRunOptions | undefined; + const originalPoeApiKey = process.env.POE_API_KEY; + + process.env.POE_API_KEY = "sk-test"; + buildSpawnArgsMock + .mockReturnValueOnce({ binaryName: "claude", args: ["-p", "first"] }) + .mockReturnValueOnce({ binaryName: "claude", args: ["-p", "second"] }); + resolvePoeCommandExecutionMock.mockReturnValue({ + factory, + state, + detach: false, + openSpec: { + cwd: "/tmp/ralph", + runner: { + detach: false, + upload_max_file_mb: 100, + download_conflict: "refuse" + }, + jobLabel: { tool: "claude-code", argv: ["claude", "-p", "prompt"] } + } + }); + createPoeCommandSessionMock.mockReturnValue({ run, close }); + runWorkspaceRalphMock.mockImplementationOnce(async (options: RalphRunOptions) => { + capturedOptions = options; + await options.runAgent?.({ + agent: "claude-code", + prompt: "first", + cwd: "/tmp/ralph", + model: "sonnet" + }); + await options.runAgent?.({ + agent: "claude-code", + prompt: "second", + cwd: "/tmp/ralph", + model: "sonnet" + }); + return { + stopReason: "max_iterations", + docPath: "/tmp/ralph/plan.md", + iterationsCompleted: 2, + totalDurationMs: 1_000 + }; + }); + + try { + await runRalph({ + cwd: "/tmp/ralph", + homeDir: "/home/test", + docPath: "/tmp/ralph/plan.md", + runtime: "e2b", + runtimeTemplate: "tmpl_test" + }); + } finally { + if (originalPoeApiKey === undefined) { + delete process.env.POE_API_KEY; + } else { + process.env.POE_API_KEY = originalPoeApiKey; + } + } + + expect(capturedOptions?.runAgent).toEqual(expect.any(Function)); + expect(spawnAutonomousMock).not.toHaveBeenCalled(); + expect(createPoeCommandSessionMock).toHaveBeenCalledTimes(1); + expect(createPoeCommandSessionMock).toHaveBeenCalledWith({ factory, state }); + expect(buildSpawnArgsMock).toHaveBeenNthCalledWith(1, "claude-code", { + prompt: "first", + model: "sonnet", + mode: "yolo" + }); + expect(buildSpawnArgsMock).toHaveBeenNthCalledWith(2, "claude-code", { + prompt: "second", + model: "sonnet", + mode: "yolo" + }); + expect(run).toHaveBeenCalledTimes(2); + expect(run.mock.calls[0]?.[0]).toEqual( + expect.objectContaining({ + runner: expect.objectContaining({ download_conflict: "overwrite" }) + }) + ); + expect(resolvePoeCommandExecutionMock).toHaveBeenCalledTimes(2); + expect(close).toHaveBeenCalledTimes(1); + }); }); diff --git a/src/sdk/ralph.ts b/src/sdk/ralph.ts index 1721bc05f0..57b29833d9 100644 --- a/src/sdk/ralph.ts +++ b/src/sdk/ralph.ts @@ -3,7 +3,14 @@ import { type RalphRunOptions, type RalphRunResult } from "@poe-code/ralph"; +import { + createPoeCommandSession, + resolvePoeCommandExecution, + type PoeCommandSession +} from "@poe-code/agent-harness-tools"; +import { buildSpawnArgs } from "@poe-code/agent-spawn"; import { spawn as sdkSpawn } from "./spawn.js"; +import { getPoeApiKey } from "./credentials.js"; export type { AgentRunInput, @@ -13,13 +20,26 @@ export type { RalphStopReason } from "@poe-code/ralph"; -export async function runRalph( +export async function runRalph(options: RalphRunOptions): Promise { + const reusableE2b = options.runtime === "e2b" && options.detach !== true; + const e2bRunner = reusableE2b && !options.runAgent ? createReusableE2bRalphRunner(options) : null; + const runAgent = options.runAgent ?? e2bRunner?.runAgent ?? createDefaultRalphRunAgent(options); + + try { + return await runWorkspaceRalph({ + ...options, + runAgent + }); + } finally { + await e2bRunner?.close(); + } +} + +function createDefaultRalphRunAgent( options: RalphRunOptions -): Promise { - const runAgent = options.runAgent ?? (async ( - input: Parameters>[0] - ) => { - return await sdkSpawn.autonomous(input.agent, { +): NonNullable { + return async (input) => + await sdkSpawn.autonomous(input.agent, { prompt: input.prompt, cwd: input.cwd, model: input.model, @@ -27,14 +47,95 @@ export async function runRalph( ...(options.runtime ? { runtime: options.runtime } : {}), ...(options.runtimeImage ? { runtimeImage: options.runtimeImage } : {}), ...(options.runtimeTemplate ? { runtimeTemplate: options.runtimeTemplate } : {}), + ...(options.runtimeConfigCwd ? { runtimeConfigCwd: options.runtimeConfigCwd } : {}), ...(options.detach ? { detach: options.detach } : {}), ...(options.mountPoeCode ? { mountPoeCode: options.mountPoeCode } : {}), ...(input.signal ? { signal: input.signal } : {}) }); - }); +} + +function createReusableE2bRalphRunner(options: RalphRunOptions): { + runAgent: NonNullable; + close(): Promise; +} { + let session: PoeCommandSession | null = null; + let sessionFactory: unknown; + let sessionState: ReturnType["state"] | undefined; + + return { + async runAgent(input) { + await ensurePoeApiKey(); + const spawnArgs = buildSpawnArgs(input.agent, { + prompt: input.prompt, + model: input.model, + mode: "yolo" + }); + const processEnv = spawnArgs.env ? { ...process.env, ...spawnArgs.env } : process.env; + const execution = resolvePoeCommandExecution({ + cwd: input.cwd, + runtimeConfigCwd: options.runtimeConfigCwd, + env: processEnv as Record, + argv: [spawnArgs.binaryName, ...spawnArgs.args], + tool: input.agent, + runtime: { + runtime: options.runtime, + runtimeImage: options.runtimeImage, + runtimeTemplate: options.runtimeTemplate, + mountPoeCode: options.mountPoeCode + }, + context: { + homeDir: options.homeDir, + ...(sessionState ? { state: sessionState } : {}) + }, + openSpec: { + execution: { + wrapForLogTee: false, + stdin: "inherit", + stdout: "pipe", + stderr: "pipe", + env: processEnv as Record, + captureOutput: true + } + } + }); + + if (session === null) { + sessionFactory = execution.factory; + sessionState = execution.state; + session = createPoeCommandSession({ + factory: execution.factory, + state: execution.state + }); + } else if (execution.factory !== sessionFactory) { + throw new Error("Ralph e2b runtime changed during a reusable session."); + } + + const openSpec = execution.openSpec.runner + ? { + ...execution.openSpec, + runner: { + ...execution.openSpec.runner, + download_conflict: "overwrite" as const + } + } + : execution.openSpec; + const result = await session.run(openSpec, input.signal); + return { + stdout: result.stdout ?? "", + stderr: result.stderr ?? "", + exitCode: result.exitCode + }; + }, + async close() { + await session?.close(); + } + }; +} + +async function ensurePoeApiKey(): Promise { + if (process.env.POE_API_KEY && process.env.POE_API_KEY.trim().length > 0) { + return; + } - return runWorkspaceRalph({ - ...options, - runAgent - }); + process.env.POE_API_KEY = await getPoeApiKey(); } From 63486491a1254ceae14ed75e22846a44694dc2ff Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 03:01:21 -0500 Subject: [PATCH 066/111] feat: add runner sync runtime option --- docs/plans/e2b-runtime-spawn-fixes.md | 60 ++++++++++--------- docs/plans/e2b-runtime-spawn-fixes.md.lock | 2 +- .../src/poe-command-execution.test.ts | 5 +- .../src/poe-command-execution.ts | 5 +- packages/agent-spawn/src/acp/spawn-acp.ts | 1 + packages/agent-spawn/src/acp/spawn.ts | 3 +- packages/agent-spawn/src/spawn-interactive.ts | 3 +- packages/agent-spawn/src/spawn.ts | 3 +- packages/agent-spawn/src/types.ts | 2 + packages/experiment-loop/src/run/loop.ts | 1 + packages/experiment-loop/src/types.ts | 2 + packages/poe-code-config/src/runtime.test.ts | 10 ++++ packages/poe-code-config/src/runtime.ts | 13 ++++ .../src/types.compile-check.ts | 1 + packages/ralph/src/run/ralph.ts | 1 + packages/ralph/src/types.ts | 2 + packages/runner-e2b/src/opened-env.test.ts | 56 +++++++++++++++++ packages/runner-e2b/src/opened-env.ts | 6 ++ .../superintendent/src/commands/run.test.ts | 4 +- packages/superintendent/src/commands/run.ts | 18 ++++-- .../src/runtime/agent-runner.ts | 7 ++- packages/superintendent/src/runtime/loop.ts | 1 + .../__snapshots__/runtime-help.test.ts.snap | 7 +++ src/cli/commands/experiment-ralph.test.ts | 14 +++-- src/cli/commands/runtime-options.ts | 10 +++- src/cli/commands/spawn-command.test.ts | 5 +- src/providers/spawn-options.ts | 1 + src/sdk/experiment.ts | 1 + src/sdk/ralph.ts | 4 +- src/sdk/spawn.ts | 10 +++- src/sdk/types.ts | 2 + 31 files changed, 209 insertions(+), 51 deletions(-) diff --git a/docs/plans/e2b-runtime-spawn-fixes.md b/docs/plans/e2b-runtime-spawn-fixes.md index 1c0bcceecc..c115c68633 100644 --- a/docs/plans/e2b-runtime-spawn-fixes.md +++ b/docs/plans/e2b-runtime-spawn-fixes.md @@ -102,27 +102,27 @@ tasks: commit: done - id: e2b-spawn-end-to-end - title: Make `spawn --runtime e2b` work end-to-end on a tmp workspace + title: Make `spawn --runtime e2b` work end-to-end against an ephemeral + sandbox prompt: | With tasks 1-3 landed, wire and verify the spawn-through-e2b path against a real e2b sandbox. The previous three tasks are the structural fixes; this task is the integration glue and the verification. - Test workspace must be a fresh tmpdir, not the poe-code repo - itself - downloadWorkspace syncs sandbox files back, and - polluting the monorepo on every spawn run is unacceptable. - Create the workspace with `mkdtemp` and seed it with exactly - two files: README.md (one paragraph) and hello.txt (one line). + Smoke-test the path with `--runner-sync none` so sandbox writes + never sync back into the poe-code repo. The image/template should + already contain the tiny fixture files needed by the prompt: + README.md (one paragraph) and hello.txt (one line). The agent's prompt should ask it to read hello.txt and reply - with one short sentence - small enough that any post-run sync - back into the tmpdir is trivial to inspect, and the tmpdir is - removed in a finally block regardless of success or failure. + with one short sentence. Acceptance commands, all green from a clean state: npm run dev -- runtime build --runtime e2b npm run dev -- --yes spawn claude-code "read hello.txt and \ - summarize in one sentence" --runtime e2b --cwd + summarize in one sentence" --runtime e2b --runner-sync none + npm run dev -- --yes spawn claude-code "write SYNC_CHECK.txt \ + containing synced" --runtime e2b --runner-sync both --cwd The spawn must: - Reach the sandbox without permission errors on the upload. @@ -130,7 +130,8 @@ tasks: - Hit api.poe.com (verifiable via the request log or a throwaway POE_API_KEY tied to a fresh account). - Return non-empty stdout with exit code 0. - - Write nothing back to the poe-code repo. + - Write nothing back to the poe-code repo in the smoke-test variant. + - Sync SYNC_CHECK.txt back to the tmpdir in the explicit sync variant. Add a vitest integration test that drives the same flow but against a captured-sandbox fake when E2B_API_KEY is unset, so @@ -146,33 +147,38 @@ tasks: Once basic spawn through e2b works (previous task), verify the ralph iteration loop on top of it. - Use the same tmpdir discipline as the spawn task: mkdtemp, two - files, finally-cleanup. The plan is a one-task ralph markdown - doc whose prompt is intentionally trivial - e.g. "Append the - current iteration number to ITERATIONS.txt and stop after 2 - iterations". This keeps the test cheap (one model call per - iteration) and the diff inspectable. + Use `--runner-sync none` for the smoke test so the run can target + an ephemeral sandbox without tmpdir setup or cleanup. The plan is + a one-task ralph markdown doc whose prompt is intentionally + trivial - e.g. "Report the current iteration number and stop after + 2 iterations". Keep a separate sync assertion for the workspace + write path. Acceptance commands, all green from a clean state: - npm run dev -- ralph init /plan.md \ + npm run dev -- ralph init docs/plans/e2b-ralph-smoke.md \ --agent claude-code --iterations 2 + npm run dev -- --yes ralph run docs/plans/e2b-ralph-smoke.md \ + --runtime e2b --runner-sync none npm run dev -- --yes ralph run /plan.md \ - --runtime e2b --cwd + --runtime e2b --runner-sync both --cwd The run must: - Open one e2b sandbox, reuse it across both iterations. - - Sync the workspace back between iterations so ralph sees - ITERATIONS.txt grow. + - Avoid host workspace writes in the smoke-test variant. + - Sync the workspace back between iterations in the explicit + sync variant so ralph sees ITERATIONS.txt grow. - Stop after 2 iterations as configured. - - Leave the poe-code repo untouched (writes only to tmpdir). + - Leave the poe-code repo untouched except for the smoke plan + doc created by `ralph init`. - Document the tmpdir-or-bust rule in + Document the recommended `--runner-sync none` smoke-test flow + and the separate tmpdir-only sync assertion in packages/ralph/README.md so future contributors don't aim - ralph at the parent repo. + sync-back runs at the parent repo. status: implement: done test: done - commit: open + commit: done - id: runner-sync-flag title: Add a --runner-sync flag to control workspace upload/download @@ -209,8 +215,8 @@ tasks: smoke-test variants, while keeping a separate "with sync" assertion that verifies download still works when requested. status: - implement: open - test: open + implement: done + test: done commit: open --- diff --git a/docs/plans/e2b-runtime-spawn-fixes.md.lock b/docs/plans/e2b-runtime-spawn-fixes.md.lock index 1b04f9fc9f..41637b51f6 100644 --- a/docs/plans/e2b-runtime-spawn-fixes.md.lock +++ b/docs/plans/e2b-runtime-spawn-fixes.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T07:52:23.734Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T08:00:37.870Z"} \ No newline at end of file diff --git a/packages/agent-harness-tools/src/poe-command-execution.test.ts b/packages/agent-harness-tools/src/poe-command-execution.test.ts index 626095056d..217f47e8c8 100644 --- a/packages/agent-harness-tools/src/poe-command-execution.test.ts +++ b/packages/agent-harness-tools/src/poe-command-execution.test.ts @@ -14,6 +14,7 @@ describe("runtime command execution overrides", () => { detach: false, upload_max_file_mb: 100, download_conflict: "refuse", + sync: "both", workspace: { exclude: [".git"] } } }, @@ -21,7 +22,8 @@ describe("runtime command execution overrides", () => { runtime: "docker", runtimeImage: "poe-code:test", detach: true, - mountPoeCode: true + mountPoeCode: true, + runnerSync: "none" }, "/repo" ); @@ -43,6 +45,7 @@ describe("runtime command execution overrides", () => { detach: true, upload_max_file_mb: 100, download_conflict: "refuse", + sync: "none", workspace: { exclude: [".git"] } } }); diff --git a/packages/agent-harness-tools/src/poe-command-execution.ts b/packages/agent-harness-tools/src/poe-command-execution.ts index 1a57b396cb..7aba3e3e3f 100644 --- a/packages/agent-harness-tools/src/poe-command-execution.ts +++ b/packages/agent-harness-tools/src/poe-command-execution.ts @@ -9,6 +9,7 @@ import { resolveRuntime, resolveScope, runtimeConfigScope, + type RunnerScope, type ConfigDocument, type JobEntry, type JobListFilter, @@ -23,6 +24,7 @@ export type RuntimeOverrideOptions = { runtimeTemplate?: string; detach?: boolean; mountPoeCode?: boolean; + runnerSync?: RunnerScope["sync"]; }; export function resolvePoeCommandExecution(input: { @@ -107,7 +109,8 @@ export function applyRuntimeOverrides( runtime, runner: { ...config.runner, - ...(overrides.detach === true ? { detach: true } : {}) + ...(overrides.detach === true ? { detach: true } : {}), + ...(overrides.runnerSync !== undefined ? { sync: overrides.runnerSync } : {}) } }; } diff --git a/packages/agent-spawn/src/acp/spawn-acp.ts b/packages/agent-spawn/src/acp/spawn-acp.ts index 6d8017c070..09422b0a81 100644 --- a/packages/agent-spawn/src/acp/spawn-acp.ts +++ b/packages/agent-spawn/src/acp/spawn-acp.ts @@ -17,6 +17,7 @@ export interface SpawnAcpOptions { runtimeTemplate?: string; detach?: boolean; mountPoeCode?: boolean; + runnerSync?: "both" | "upload" | "none"; signal?: AbortSignal; } diff --git a/packages/agent-spawn/src/acp/spawn.ts b/packages/agent-spawn/src/acp/spawn.ts index baf0849f16..91ab0b09fd 100644 --- a/packages/agent-spawn/src/acp/spawn.ts +++ b/packages/agent-spawn/src/acp/spawn.ts @@ -198,7 +198,8 @@ export function spawnStreaming(options: SpawnStreamingOptions): SpawnStreamingRe runtimeImage: options.runtimeImage, runtimeTemplate: options.runtimeTemplate, detach: options.detach, - mountPoeCode: options.mountPoeCode + mountPoeCode: options.mountPoeCode, + runnerSync: options.runnerSync }, openSpec: { execution: { diff --git a/packages/agent-spawn/src/spawn-interactive.ts b/packages/agent-spawn/src/spawn-interactive.ts index 2bedff159e..35425ffd5b 100644 --- a/packages/agent-spawn/src/spawn-interactive.ts +++ b/packages/agent-spawn/src/spawn-interactive.ts @@ -79,7 +79,8 @@ export async function spawnInteractive( runtimeImage: options.runtimeImage, runtimeTemplate: options.runtimeTemplate, detach: options.detach, - mountPoeCode: options.mountPoeCode + mountPoeCode: options.mountPoeCode, + runnerSync: options.runnerSync }, openSpec: { execution: { diff --git a/packages/agent-spawn/src/spawn.ts b/packages/agent-spawn/src/spawn.ts index 559503f0d0..ed84ab31cb 100644 --- a/packages/agent-spawn/src/spawn.ts +++ b/packages/agent-spawn/src/spawn.ts @@ -183,7 +183,8 @@ export async function spawn( runtimeImage: options.runtimeImage, runtimeTemplate: options.runtimeTemplate, detach: options.detach, - mountPoeCode: options.mountPoeCode + mountPoeCode: options.mountPoeCode, + runnerSync: options.runnerSync }, context, openSpec: { diff --git a/packages/agent-spawn/src/types.ts b/packages/agent-spawn/src/types.ts index 180ead8734..4970c8e0c6 100644 --- a/packages/agent-spawn/src/types.ts +++ b/packages/agent-spawn/src/types.ts @@ -77,6 +77,8 @@ export interface SpawnOptions { detach?: boolean; /** Mount the local poe-code checkout into the runtime for development. */ mountPoeCode?: boolean; + /** Override runner workspace sync behavior. */ + runnerSync?: RuntimeOverrideOptions["runnerSync"]; } export interface SpawnUsage { diff --git a/packages/experiment-loop/src/run/loop.ts b/packages/experiment-loop/src/run/loop.ts index cbdd01e0f6..c6823c6e6b 100644 --- a/packages/experiment-loop/src/run/loop.ts +++ b/packages/experiment-loop/src/run/loop.ts @@ -445,6 +445,7 @@ export async function runExperimentLoop( ...(options.runtimeTemplate ? { runtimeTemplate: options.runtimeTemplate } : {}), ...(options.detach ? { detach: options.detach } : {}), ...(options.mountPoeCode ? { mountPoeCode: options.mountPoeCode } : {}), + ...(options.runnerSync ? { runnerSync: options.runnerSync } : {}), ...(model ? { model } : {}), ...(options.signal ? { signal: options.signal } : {}) }); diff --git a/packages/experiment-loop/src/types.ts b/packages/experiment-loop/src/types.ts index a7b3a732ad..597b2b67c0 100644 --- a/packages/experiment-loop/src/types.ts +++ b/packages/experiment-loop/src/types.ts @@ -45,6 +45,7 @@ export interface AgentRunInput { runtimeTemplate?: string; detach?: boolean; mountPoeCode?: boolean; + runnerSync?: "both" | "upload" | "none"; signal?: AbortSignal; logDir?: string; logFileName?: string; @@ -66,6 +67,7 @@ export interface ExperimentRunOptions { runtimeTemplate?: string; detach?: boolean; mountPoeCode?: boolean; + runnerSync?: "both" | "upload" | "none"; maxExperiments?: number; fs?: ExperimentFileSystem; git?: ExperimentGit; diff --git a/packages/poe-code-config/src/runtime.test.ts b/packages/poe-code-config/src/runtime.test.ts index 0167a5a7da..6b86bb7745 100644 --- a/packages/poe-code-config/src/runtime.test.ts +++ b/packages/poe-code-config/src/runtime.test.ts @@ -32,6 +32,7 @@ describe("runtime config", () => { detach: false, upload_max_file_mb: 100, download_conflict: "refuse", + sync: "both", workspace: { exclude: [".git", "node_modules", "dist", ".turbo", ".next", ".poe-code/state.json"] } @@ -44,6 +45,7 @@ describe("runtime config", () => { detach: true, upload_max_file_mb: 250, download_conflict: "overwrite", + sync: "upload", workspace: { exclude: ["coverage", "tmp"] } @@ -52,6 +54,7 @@ describe("runtime config", () => { detach: true, upload_max_file_mb: 250, download_conflict: "overwrite", + sync: "upload", workspace: { exclude: ["coverage", "tmp"] } @@ -63,6 +66,7 @@ describe("runtime config", () => { detach: false, upload_max_file_mb: 100, download_conflict: "refuse", + sync: "both", workspace: { exclude: [".git", "node_modules", "dist", ".turbo", ".next", ".poe-code/state.json"] } @@ -72,6 +76,7 @@ describe("runtime config", () => { detach: false, upload_max_file_mb: 100, download_conflict: "refuse", + sync: "both", workspace: { exclude: [".git", "node_modules", "dist", ".turbo", ".next", ".poe-code/state.json"] } @@ -87,6 +92,7 @@ describe("runtime config", () => { detach: true, upload_max_file_mb: 1, download_conflict: "overwrite", + sync: "none", workspace: { exclude: [] } }) }, @@ -96,6 +102,7 @@ describe("runtime config", () => { detach: true, upload_max_file_mb: 1, download_conflict: "overwrite", + sync: "none", workspace: { exclude: [] } @@ -114,6 +121,9 @@ describe("runtime config", () => { expect(() => parseRunner({ download_conflict: "merge" })).toThrow( 'runner.download_conflict: expected "refuse" or "overwrite".' ); + expect(() => parseRunner({ sync: "download" })).toThrow( + 'runner.sync: expected "both", "upload", or "none".' + ); expect(() => parseRunner({ workspace: [] })).toThrow("runner.workspace: expected an object."); expect(() => parseRunner({ workspace: { exclude: [".git", 42] } })).toThrow( "runner.workspace.exclude[1]: expected a string." diff --git a/packages/poe-code-config/src/runtime.ts b/packages/poe-code-config/src/runtime.ts index 01c122605b..5bf9069abd 100644 --- a/packages/poe-code-config/src/runtime.ts +++ b/packages/poe-code-config/src/runtime.ts @@ -12,6 +12,7 @@ export interface RunnerScope { detach: boolean; upload_max_file_mb: number; download_conflict: "refuse" | "overwrite"; + sync: "both" | "upload" | "none"; workspace?: { exclude?: string[]; }; @@ -194,6 +195,7 @@ export function parseRunner(raw: unknown): RunnerScope { detach: parseOptionalBoolean(record.detach, "runner.detach") ?? false, upload_max_file_mb: uploadMaxFileMb, download_conflict: parseDownloadConflict(record.download_conflict), + sync: parseRunnerSync(record.sync), workspace: parseRunnerWorkspace(record.workspace) }); } @@ -364,6 +366,7 @@ function createDefaultRunnerScope(): RunnerScope { detach: false, upload_max_file_mb: 100, download_conflict: "refuse", + sync: "both", workspace: { exclude: [...defaultWorkspaceExclude] } @@ -398,6 +401,16 @@ function parseDownloadConflict(value: unknown): RunnerScope["download_conflict"] throw new Error('runner.download_conflict: expected "refuse" or "overwrite".'); } +function parseRunnerSync(value: unknown): RunnerScope["sync"] { + if (value === undefined) { + return "both"; + } + if (value === "both" || value === "upload" || value === "none") { + return value; + } + throw new Error('runner.sync: expected "both", "upload", or "none".'); +} + function parseBuildArgs(value: unknown): Record { if (value === undefined) { return {}; diff --git a/packages/poe-code-config/src/types.compile-check.ts b/packages/poe-code-config/src/types.compile-check.ts index a4898aa02d..bdf5103113 100644 --- a/packages/poe-code-config/src/types.compile-check.ts +++ b/packages/poe-code-config/src/types.compile-check.ts @@ -103,6 +103,7 @@ type ignoredResolvedConfigRuntime = AssertAssignable< detach: boolean; upload_max_file_mb: number; download_conflict: "refuse" | "overwrite"; + sync: "both" | "upload" | "none"; workspace?: { exclude?: string[]; }; diff --git a/packages/ralph/src/run/ralph.ts b/packages/ralph/src/run/ralph.ts index 4fc9503e4c..4e4dd0ffce 100644 --- a/packages/ralph/src/run/ralph.ts +++ b/packages/ralph/src/run/ralph.ts @@ -89,6 +89,7 @@ export async function runRalph(options: RalphRunOptions): Promise Promise; onIterationStart?: (iteration: number, maxIterations: number, agent: string) => void; diff --git a/packages/runner-e2b/src/opened-env.test.ts b/packages/runner-e2b/src/opened-env.test.ts index 4cbbab840e..b725e3e91e 100644 --- a/packages/runner-e2b/src/opened-env.test.ts +++ b/packages/runner-e2b/src/opened-env.test.ts @@ -271,6 +271,32 @@ describe("createOpenedE2bEnv", () => { ); }); + it("skips workspace upload when runner sync is none", async () => { + const hostRunner = createHostRunnerMock(); + const sandbox = createSandboxMock(); + const env = createOpenedE2bEnv({ + sandbox, + runtime: { ...createRuntime(), workspace_dir: "/sandbox/workspace" }, + spec: { + ...createSpec(), + hostRunner, + runner: { + detach: false, + upload_max_file_mb: 100, + download_conflict: "refuse", + sync: "none" + } + } + }); + + await expect(env.uploadWorkspace()).resolves.toEqual({ files: 0, bytes: 0, skipped: [] }); + + expect(hostRunner.exec).not.toHaveBeenCalled(); + expect(sandbox.files.write).not.toHaveBeenCalled(); + expect(sandbox.commands.run).not.toHaveBeenCalled(); + expect(fsMocks.mkdtempSync).not.toHaveBeenCalled(); + }); + it("decorates remote command exit errors with the command and stderr tail", async () => { const hostRunner = createHostRunnerMock(); const sandbox = createSandboxMock(); @@ -376,6 +402,36 @@ describe("createOpenedE2bEnv", () => { }); }); + it("skips workspace download when runner sync is upload-only", async () => { + const hostRunner = createHostRunnerMock(); + const sandbox = createSandboxMock(); + const env = createOpenedE2bEnv({ + sandbox, + runtime: { ...createRuntime(), workspace_dir: "/sandbox/workspace" }, + spec: { + ...createSpec(), + hostRunner, + runner: { + detach: false, + upload_max_file_mb: 100, + download_conflict: "refuse", + sync: "upload" + } + } + }); + + await expect(env.downloadWorkspace({ conflictPolicy: "overwrite" })).resolves.toEqual({ + files: 0, + bytes: 0, + conflicts: [] + }); + + expect(hostRunner.exec).not.toHaveBeenCalled(); + expect(sandbox.files.read).not.toHaveBeenCalled(); + expect(sandbox.commands.run).not.toHaveBeenCalled(); + expect(fsMocks.mkdtempSync).not.toHaveBeenCalled(); + }); + it("creates a job handle for the last running command and preserves sandbox timeout on wait", async () => { const commandHandle = { pid: 321, diff --git a/packages/runner-e2b/src/opened-env.ts b/packages/runner-e2b/src/opened-env.ts index a10f43e6b8..e1e3e927d3 100644 --- a/packages/runner-e2b/src/opened-env.ts +++ b/packages/runner-e2b/src/opened-env.ts @@ -72,6 +72,9 @@ export function createOpenedE2bEnv(input: { detachedJobContext = context; }, async uploadWorkspace() { + if (input.spec.runner?.sync === "none") { + return { files: 0, bytes: 0, skipped: [] }; + } const tempDir = mkdtempSync(path.join(tmpdir(), "poe-e2b-upload-")); const archivePath = path.join(tempDir, "workspace.tar"); try { @@ -102,6 +105,9 @@ export function createOpenedE2bEnv(input: { } }, async downloadWorkspace(opts) { + if (input.spec.runner?.sync === "upload" || input.spec.runner?.sync === "none") { + return { files: 0, bytes: 0, conflicts: [] }; + } const tempDir = mkdtempSync(path.join(tmpdir(), "poe-e2b-download-")); const archivePath = path.join(tempDir, "workspace.tar"); try { diff --git a/packages/superintendent/src/commands/run.test.ts b/packages/superintendent/src/commands/run.test.ts index bb6524ff69..f4881ebd2d 100644 --- a/packages/superintendent/src/commands/run.test.ts +++ b/packages/superintendent/src/commands/run.test.ts @@ -301,6 +301,7 @@ describe("superintendent run command", () => { runtimeTemplate: "tpl_123", detach: true, mountPoeCode: true, + runnerSync: "none", env: {} }); @@ -310,7 +311,8 @@ describe("superintendent run command", () => { runtime: "e2b", runtimeTemplate: "tpl_123", detach: true, - mountPoeCode: true + mountPoeCode: true, + runnerSync: "none" }) ); }); diff --git a/packages/superintendent/src/commands/run.ts b/packages/superintendent/src/commands/run.ts index 052c739be0..3e22bfedd2 100644 --- a/packages/superintendent/src/commands/run.ts +++ b/packages/superintendent/src/commands/run.ts @@ -4,7 +4,8 @@ import { spawn as nodeSpawn, spawnSync as nodeSpawnSync } from "node:child_proce import { resolveLoopAgent, resolveRunLogDir, - resolveWorkflowPath + resolveWorkflowPath, + type RuntimeOverrideOptions } from "@poe-code/agent-harness-tools"; import { applyMiddlewares, @@ -70,6 +71,7 @@ export type RunCommandOptions = { runtimeTemplate?: string; detach?: boolean; mountPoeCode?: boolean; + runnerSync?: RuntimeOverrideOptions["runnerSync"]; configuredDefaultAgent?: string | null; planDirectory?: string; assumeYes?: boolean; @@ -143,6 +145,9 @@ const runParams = S.Object({ mountPoeCode: S.Optional(S.Boolean({ description: "Mount the local poe-code checkout into the runtime" })), + runnerSync: S.Optional(S.Enum(["both", "upload", "none"] as const, { + description: "Override runner workspace sync: both, upload, or none" + })), tui: S.Optional(S.Boolean({ description: "Show a live dashboard while Superintendent is running" })) }); @@ -170,6 +175,7 @@ export const runCommand = defineCommand({ ...(params.runtimeTemplate ? { runtimeTemplate: params.runtimeTemplate } : {}), ...(params.detach ? { detach: params.detach } : {}), ...(params.mountPoeCode ? { mountPoeCode: params.mountPoeCode } : {}), + ...(params.runnerSync ? { runnerSync: params.runnerSync } : {}), configuredDefaultAgent: commandConfig.configuredDefaultAgent, assumeYes: process.argv.includes("--yes"), interactive: Boolean(process.stdin.isTTY), @@ -486,7 +492,8 @@ export async function runSuperintendentCommand( runtimeImage: options.runtimeImage, runtimeTemplate: options.runtimeTemplate, detach: options.detach, - mountPoeCode: options.mountPoeCode + mountPoeCode: options.mountPoeCode, + runnerSync: options.runnerSync }, activeStage: () => activeStage, now, @@ -756,7 +763,8 @@ export async function runSuperintendentCommand( runtimeImage: options.runtimeImage, runtimeTemplate: options.runtimeTemplate, detach: options.detach, - mountPoeCode: options.mountPoeCode + mountPoeCode: options.mountPoeCode, + runnerSync: options.runnerSync }, activeStage: () => session.activeStage, now, @@ -956,7 +964,7 @@ function createAgentRunner(options: { integrations: Integrations | null; runtime: Pick< RunCommandOptions, - "runtime" | "runtimeImage" | "runtimeTemplate" | "detach" | "mountPoeCode" + "runtime" | "runtimeImage" | "runtimeTemplate" | "detach" | "mountPoeCode" | "runnerSync" >; activeStage: () => RunSession["activeStage"]; now: () => number; @@ -1087,6 +1095,7 @@ async function executeSpawnAgent( ...(input.runtimeTemplate ? { runtimeTemplate: input.runtimeTemplate } : {}), ...(input.detach ? { detach: input.detach } : {}), ...(input.mountPoeCode ? { mountPoeCode: input.mountPoeCode } : {}), + ...(input.runnerSync ? { runnerSync: input.runnerSync } : {}), ...(tee ? { tee } : {}) }); @@ -1130,6 +1139,7 @@ async function executeSpawnAgentStreaming( ...(input.runtimeTemplate ? { runtimeTemplate: input.runtimeTemplate } : {}), ...(input.detach ? { detach: input.detach } : {}), ...(input.mountPoeCode ? { mountPoeCode: input.mountPoeCode } : {}), + ...(input.runnerSync ? { runnerSync: input.runnerSync } : {}), ...(input.onStderr ? { tee: { stderr: { write: input.onStderr } } } : {}) }); diff --git a/packages/superintendent/src/runtime/agent-runner.ts b/packages/superintendent/src/runtime/agent-runner.ts index 5d73436adc..137551f865 100644 --- a/packages/superintendent/src/runtime/agent-runner.ts +++ b/packages/superintendent/src/runtime/agent-runner.ts @@ -26,6 +26,7 @@ export type AutonomousInput = { runtimeTemplate?: string; detach?: boolean; mountPoeCode?: boolean; + runnerSync?: RuntimeOverrideOptions["runnerSync"]; }; export type AutonomousOutput = @@ -73,7 +74,8 @@ export async function runAutonomousAgent(input: AutonomousInput): Promise void; diff --git a/src/cli/commands/__snapshots__/runtime-help.test.ts.snap b/src/cli/commands/__snapshots__/runtime-help.test.ts.snap index fd823363cc..4235f95832 100644 --- a/src/cli/commands/__snapshots__/runtime-help.test.ts.snap +++ b/src/cli/commands/__snapshots__/runtime-help.test.ts.snap @@ -21,6 +21,8 @@ Options: --runtime-template Override E2B runtime template id --detach Run as a detached runtime job --mount-poe-code Mount the local poe-code checkout into the runtime + --runner-sync Override runner workspace sync: both | upload | none + (choices: "both", "upload", "none") -h, --help Display help for command " `; @@ -47,6 +49,8 @@ Options: --runtime-template Override E2B runtime template id --detach Run as a detached runtime job --mount-poe-code Mount the local poe-code checkout into the runtime + --runner-sync Override runner workspace sync: both | upload | none + (choices: "both", "upload", "none") -h, --help Display help for command " `; @@ -83,6 +87,8 @@ Options: --runtime-template Override E2B runtime template id --detach Run as a detached runtime job --mount-poe-code Mount the local poe-code checkout into the runtime + --runner-sync Override runner workspace sync: both | upload | + none (choices: "both", "upload", "none") -h, --help Display help for command " `; @@ -102,6 +108,7 @@ Options: --runtime-template Override E2B runtime template id --detach [value] Run as a detached runtime job --mount-poe-code [value] Mount the local poe-code checkout into the runtime + --runner-sync Override runner workspace sync: both, upload, or none --tui [value] Show a live dashboard while Superintendent is running Global options: diff --git a/src/cli/commands/experiment-ralph.test.ts b/src/cli/commands/experiment-ralph.test.ts index 88ee363c36..8fe5f3916c 100644 --- a/src/cli/commands/experiment-ralph.test.ts +++ b/src/cli/commands/experiment-ralph.test.ts @@ -262,7 +262,9 @@ describe("experiment run command", () => { "--runtime-template", "tpl_123", "--detach", - "--mount-poe-code" + "--mount-poe-code", + "--runner-sync", + "none" ]); expect(vi.mocked(sdkRunExperiment)).toHaveBeenCalledWith( @@ -270,7 +272,8 @@ describe("experiment run command", () => { runtime: "e2b", runtimeTemplate: "tpl_123", detach: true, - mountPoeCode: true + mountPoeCode: true, + runnerSync: "none" }) ); }); @@ -1753,14 +1756,17 @@ describe("ralph run command", () => { "docker", "--runtime-image", "poe-code:test", - "--detach" + "--detach", + "--runner-sync", + "upload" ]); expect(vi.mocked(sdkRunRalph)).toHaveBeenCalledWith( expect.objectContaining({ runtime: "docker", runtimeImage: "poe-code:test", - detach: true + detach: true, + runnerSync: "upload" }) ); }); diff --git a/src/cli/commands/runtime-options.ts b/src/cli/commands/runtime-options.ts index 9ce256a368..32f4953247 100644 --- a/src/cli/commands/runtime-options.ts +++ b/src/cli/commands/runtime-options.ts @@ -7,6 +7,7 @@ export type RuntimeCliOptions = { runtimeTemplate?: string; detach?: boolean; mountPoeCode?: boolean; + runnerSync?: "both" | "upload" | "none"; }; export function addRuntimeOptions(command: TCommand): TCommand { @@ -21,7 +22,11 @@ export function addRuntimeOptions(command: TCommand): .option("--runtime-image ", "Override Docker runtime image") .option("--runtime-template ", "Override E2B runtime template id") .option("--detach", "Run as a detached runtime job") - .option("--mount-poe-code", "Mount the local poe-code checkout into the runtime"); + .option("--mount-poe-code", "Mount the local poe-code checkout into the runtime") + .addOption( + new Option("--runner-sync ", "Override runner workspace sync: both | upload | none") + .choices(["both", "upload", "none"]) + ); } export function pickRuntimeOptions(options: RuntimeCliOptions): RuntimeCliOptions { @@ -30,6 +35,7 @@ export function pickRuntimeOptions(options: RuntimeCliOptions): RuntimeCliOption ...(options.runtimeImage ? { runtimeImage: options.runtimeImage } : {}), ...(options.runtimeTemplate ? { runtimeTemplate: options.runtimeTemplate } : {}), ...(options.detach ? { detach: true } : {}), - ...(options.mountPoeCode ? { mountPoeCode: true } : {}) + ...(options.mountPoeCode ? { mountPoeCode: true } : {}), + ...(options.runnerSync ? { runnerSync: options.runnerSync } : {}) }; } diff --git a/src/cli/commands/spawn-command.test.ts b/src/cli/commands/spawn-command.test.ts index a1dadaaae7..29eb3a7b5f 100644 --- a/src/cli/commands/spawn-command.test.ts +++ b/src/cli/commands/spawn-command.test.ts @@ -333,6 +333,8 @@ describe("spawn command", () => { "poe-code:test", "--detach", "--mount-poe-code", + "--runner-sync", + "upload", "hello" ]); @@ -342,7 +344,8 @@ describe("spawn command", () => { runtime: "docker", runtimeImage: "poe-code:test", detach: true, - mountPoeCode: true + mountPoeCode: true, + runnerSync: "upload" }) ); }); diff --git a/src/providers/spawn-options.ts b/src/providers/spawn-options.ts index 324429655d..0b04048641 100644 --- a/src/providers/spawn-options.ts +++ b/src/providers/spawn-options.ts @@ -19,6 +19,7 @@ export interface SpawnCommandOptions { runtimeConfigCwd?: string; detach?: boolean; mountPoeCode?: boolean; + runnerSync?: RuntimeOverrideOptions["runnerSync"]; } export type ProviderSpawnOptions< diff --git a/src/sdk/experiment.ts b/src/sdk/experiment.ts index 1d991a14e1..9f62047396 100644 --- a/src/sdk/experiment.ts +++ b/src/sdk/experiment.ts @@ -80,6 +80,7 @@ export async function runExperiment(options: ExperimentRunOptions): Promise -): Pick { +): Pick< + SpawnOptions, + "runtime" | "runtimeImage" | "runtimeTemplate" | "detach" | "mountPoeCode" | "runnerSync" +> { return { ...(options.runtime ? { runtime: options.runtime } : {}), ...(options.runtimeImage ? { runtimeImage: options.runtimeImage } : {}), ...(options.runtimeTemplate ? { runtimeTemplate: options.runtimeTemplate } : {}), ...(options.detach ? { detach: options.detach } : {}), - ...(options.mountPoeCode ? { mountPoeCode: options.mountPoeCode } : {}) + ...(options.mountPoeCode ? { mountPoeCode: options.mountPoeCode } : {}), + ...(options.runnerSync ? { runnerSync: options.runnerSync } : {}) }; } diff --git a/src/sdk/types.ts b/src/sdk/types.ts index 7ad244bcd3..1b4e4daf24 100644 --- a/src/sdk/types.ts +++ b/src/sdk/types.ts @@ -58,6 +58,8 @@ export interface SpawnOptions { detach?: boolean; /** Mount the local poe-code checkout into the runtime for development */ mountPoeCode?: boolean; + /** Runner workspace sync override: both, upload, or none */ + runnerSync?: RuntimeOverrideOptions["runnerSync"]; } /** From fb3459e931d6883cbd79329adcd7971a075ae96b Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 03:02:03 -0500 Subject: [PATCH 067/111] docs: archive e2b runtime spawn plan --- docs/plans/{ => archive}/e2b-runtime-spawn-fixes.md | 2 +- docs/plans/e2b-runtime-spawn-fixes.md.lock | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename docs/plans/{ => archive}/e2b-runtime-spawn-fixes.md (99%) diff --git a/docs/plans/e2b-runtime-spawn-fixes.md b/docs/plans/archive/e2b-runtime-spawn-fixes.md similarity index 99% rename from docs/plans/e2b-runtime-spawn-fixes.md rename to docs/plans/archive/e2b-runtime-spawn-fixes.md index c115c68633..3c7838ba1c 100644 --- a/docs/plans/e2b-runtime-spawn-fixes.md +++ b/docs/plans/archive/e2b-runtime-spawn-fixes.md @@ -217,7 +217,7 @@ tasks: status: implement: done test: done - commit: open + commit: done --- # Context diff --git a/docs/plans/e2b-runtime-spawn-fixes.md.lock b/docs/plans/e2b-runtime-spawn-fixes.md.lock index 41637b51f6..d472f1b1e6 100644 --- a/docs/plans/e2b-runtime-spawn-fixes.md.lock +++ b/docs/plans/e2b-runtime-spawn-fixes.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T08:00:37.870Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T08:01:36.394Z"} \ No newline at end of file From b074071396cf93ef35bc4b315c0995255cbc91a6 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 03:05:56 -0500 Subject: [PATCH 068/111] feat(task-list): add gh issues open options --- docs/plans/e2b-runtime-spawn-fixes.md.lock | 1 - .../plans/task-list-ordering-and-gh-issues.md | 7 +++-- .../task-list-ordering-and-gh-issues.md.lock | 1 + .../src/backends/conformance.test.ts | 11 +++++++ .../task-list/src/backends/markdown-dir.ts | 7 +++++ packages/task-list/src/backends/yaml-file.ts | 7 +++++ packages/task-list/src/index.ts | 3 ++ packages/task-list/src/open-task-list.test.ts | 13 ++++++++ packages/task-list/src/open.ts | 21 ++++++++++--- packages/task-list/src/types.ts | 31 +++++++++++++++++-- 10 files changed, 90 insertions(+), 12 deletions(-) delete mode 100644 docs/plans/e2b-runtime-spawn-fixes.md.lock create mode 100644 docs/plans/task-list-ordering-and-gh-issues.md.lock diff --git a/docs/plans/e2b-runtime-spawn-fixes.md.lock b/docs/plans/e2b-runtime-spawn-fixes.md.lock deleted file mode 100644 index d472f1b1e6..0000000000 --- a/docs/plans/e2b-runtime-spawn-fixes.md.lock +++ /dev/null @@ -1 +0,0 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T08:01:36.394Z"} \ No newline at end of file diff --git a/docs/plans/task-list-ordering-and-gh-issues.md b/docs/plans/task-list-ordering-and-gh-issues.md index ba94adee6c..94a4814fc3 100644 --- a/docs/plans/task-list-ordering-and-gh-issues.md +++ b/docs/plans/task-list-ordering-and-gh-issues.md @@ -5,7 +5,8 @@ version: 1 tasks: - id: gh-issues-types - title: Make TaskCreate.id optional + add OpenGhIssuesOptions to discriminated union + title: Make TaskCreate.id optional + add OpenGhIssuesOptions to discriminated + union prompt: | In `packages/task-list/src/types.ts`, do two things: @@ -65,8 +66,8 @@ tasks: - No `if/case` on `type` outside of `open.ts`. - Keep existing tests passing. status: - implement: open - test: open + implement: done + test: done commit: open - id: gh-issues-client diff --git a/docs/plans/task-list-ordering-and-gh-issues.md.lock b/docs/plans/task-list-ordering-and-gh-issues.md.lock new file mode 100644 index 0000000000..282db521bf --- /dev/null +++ b/docs/plans/task-list-ordering-and-gh-issues.md.lock @@ -0,0 +1 @@ +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T08:04:54.980Z"} \ No newline at end of file diff --git a/packages/task-list/src/backends/conformance.test.ts b/packages/task-list/src/backends/conformance.test.ts index af90d74265..2c3d09cdf9 100644 --- a/packages/task-list/src/backends/conformance.test.ts +++ b/packages/task-list/src/backends/conformance.test.ts @@ -252,6 +252,17 @@ function describeBackendConformance( expect(createInput.id).toBe("typed-create"); }); + it("requires id at the backend boundary", async () => { + const { taskList } = await openBackend(factory, { path: rootPath }); + const tasks = taskList.list("planning"); + + await expect( + tasks.create({ + name: "Missing id" + }) + ).rejects.toThrow(`id is required for ${name.replace(" backend", "")} backend`); + }); + it("rejects state mutations outside fire()", async () => { const { taskList } = await openBackend(factory, { path: rootPath }); const tasks = taskList.list("planning"); diff --git a/packages/task-list/src/backends/markdown-dir.ts b/packages/task-list/src/backends/markdown-dir.ts index fb957e92ab..b2416cb7d5 100644 --- a/packages/task-list/src/backends/markdown-dir.ts +++ b/packages/task-list/src/backends/markdown-dir.ts @@ -459,6 +459,12 @@ function assertCreateDoesNotSetState(input: TaskCreate): void { } } +function assertCreateHasId(input: TaskCreate): asserts input is TaskCreate & { id: string } { + if (input.id === undefined) { + throw new Error("id is required for markdown-dir backend"); + } +} + function assertUpdateDoesNotSetState(patch: TaskUpdate): void { if (Object.prototype.hasOwnProperty.call(patch, "state")) { throw new Error('Tasks.update() does not accept "state"; use fire() to change task state.'); @@ -634,6 +640,7 @@ function createTasksView(deps: BackendDeps, list: string): Tasks { }, async create(input: TaskCreate): Promise { assertCreateDoesNotSetState(input); + assertCreateHasId(input); validateTaskId(input.id); await deps.fs.mkdir(listDirectoryPath, { recursive: true }); diff --git a/packages/task-list/src/backends/yaml-file.ts b/packages/task-list/src/backends/yaml-file.ts index 7881136d98..1e6b77adf3 100644 --- a/packages/task-list/src/backends/yaml-file.ts +++ b/packages/task-list/src/backends/yaml-file.ts @@ -168,6 +168,12 @@ function assertCreateDoesNotSetState(input: TaskCreate): void { } } +function assertCreateHasId(input: TaskCreate): asserts input is TaskCreate & { id: string } { + if (input.id === undefined) { + throw new Error("id is required for yaml-file backend"); + } +} + function assertUpdateDoesNotSetState(patch: TaskUpdate): void { if (Object.prototype.hasOwnProperty.call(patch, "state")) { throw new Error('Tasks.update() does not accept "state"; use fire() to change task state.'); @@ -523,6 +529,7 @@ function createTasksView(deps: BackendDeps, list: string): Tasks { }, async create(input: TaskCreate): Promise { assertCreateDoesNotSetState(input); + assertCreateHasId(input); validateTaskId(input.id); return withStoreLock(deps, async () => { diff --git a/packages/task-list/src/index.ts b/packages/task-list/src/index.ts index 44357bab1c..a4fa0951da 100644 --- a/packages/task-list/src/index.ts +++ b/packages/task-list/src/index.ts @@ -16,7 +16,10 @@ export { TaskNotFoundError, type ListFilter, type MoveAnchor, + type OpenGhIssuesOptions, + type OpenMarkdownDirOptions, type OpenTaskListOptions, + type OpenYamlFileOptions, type Task, type TaskCreate, type TaskDefaults, diff --git a/packages/task-list/src/open-task-list.test.ts b/packages/task-list/src/open-task-list.test.ts index 48676862af..22dce112b5 100644 --- a/packages/task-list/src/open-task-list.test.ts +++ b/packages/task-list/src/open-task-list.test.ts @@ -113,6 +113,19 @@ describe("openTaskList", () => { ).rejects.toThrow('Unknown task list backend type "sqlite".'); }); + it('throws the placeholder error for "gh-issues"', async () => { + await expect( + openTaskList({ + type: "gh-issues", + repo: "owner/name", + project: { + owner: "owner", + number: 1 + } + }) + ).rejects.toThrow("gh-issues backend not yet implemented"); + }); + it("normalizes missing defaults", async () => { const taskList = createTaskList(); const { fs } = createFs(); diff --git a/packages/task-list/src/open.ts b/packages/task-list/src/open.ts index 7e4415a152..23907117ac 100644 --- a/packages/task-list/src/open.ts +++ b/packages/task-list/src/open.ts @@ -6,7 +6,9 @@ import { resolveStateMachine } from "./state.js"; import type { BackendFactory, BackendDeps, + OpenMarkdownDirOptions, OpenTaskListOptions, + OpenYamlFileOptions, TaskList, TaskListFs } from "./types.js"; @@ -14,7 +16,9 @@ import type { const DEFAULT_LOCK_STALE_MS = 30_000; const DEFAULT_LOCK_RETRIES = 20; -export const backendFactories: Record = { +type FileBackendOptions = OpenMarkdownDirOptions | OpenYamlFileOptions; + +export const backendFactories: Record = { "markdown-dir": markdownDirBackend, "yaml-file": yamlFileBackend }; @@ -24,12 +28,19 @@ function createDefaultFs(): TaskListFs { } export async function openTaskList(options: OpenTaskListOptions): Promise { - const factory = (backendFactories as Record)[options.type]; - - if (factory === undefined) { - throw new Error(`Unknown task list backend type "${options.type}".`); + switch (options.type) { + case "markdown-dir": + case "yaml-file": + return openFileBackend(options); + case "gh-issues": + throw new Error("gh-issues backend not yet implemented"); + default: + throw new Error(`Unknown task list backend type "${(options as { type: string }).type}".`); } +} +async function openFileBackend(options: FileBackendOptions): Promise { + const factory = backendFactories[options.type]; const stateMachine = resolveStateMachine(options.stateMachine); validateMachine(stateMachine); diff --git a/packages/task-list/src/types.ts b/packages/task-list/src/types.ts index 3d45315133..e375e29fb1 100644 --- a/packages/task-list/src/types.ts +++ b/packages/task-list/src/types.ts @@ -13,7 +13,7 @@ export interface Task { } export interface TaskCreate { - id: string; + id?: string; name: string; description?: string; metadata?: Record; @@ -95,8 +95,24 @@ export interface TaskListFs { ): Promise; } -export interface OpenTaskListOptions { - type: "markdown-dir" | "yaml-file"; +export type OpenTaskListOptions = + | OpenMarkdownDirOptions + | OpenYamlFileOptions + | OpenGhIssuesOptions; + +export interface OpenMarkdownDirOptions { + type: "markdown-dir"; + path: string; + defaults?: TaskDefaults; + create?: boolean; + lockStaleMs?: number; + lockRetries?: number; + fs?: TaskListFs; + stateMachine?: StateMachineDef; +} + +export interface OpenYamlFileOptions { + type: "yaml-file"; path: string; defaults?: TaskDefaults; create?: boolean; @@ -106,6 +122,15 @@ export interface OpenTaskListOptions { stateMachine?: StateMachineDef; } +export interface OpenGhIssuesOptions { + type: "gh-issues"; + repo: string; + project: { owner: string; number: number }; + defaults?: TaskDefaults; + auth?: { token: string }; + fetch?: typeof fetch; +} + export interface BackendDeps { path: string; defaults: Required; From f5a2d32b88883a8b8509158628a1f98e345970d4 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 03:11:49 -0500 Subject: [PATCH 069/111] feat(task-list): add github issues client --- .../plans/task-list-ordering-and-gh-issues.md | 8 +- .../task-list-ordering-and-gh-issues.md.lock | 2 +- package-lock.json | 1 + packages/task-list/package.json | 1 + .../src/backends/gh-issues-client.test.ts | 195 ++++++++++++++++++ .../src/backends/gh-issues-client.ts | 98 +++++++++ packages/task-list/src/index.ts | 9 + 7 files changed, 309 insertions(+), 5 deletions(-) create mode 100644 packages/task-list/src/backends/gh-issues-client.test.ts create mode 100644 packages/task-list/src/backends/gh-issues-client.ts diff --git a/docs/plans/task-list-ordering-and-gh-issues.md b/docs/plans/task-list-ordering-and-gh-issues.md index 94a4814fc3..660001b706 100644 --- a/docs/plans/task-list-ordering-and-gh-issues.md +++ b/docs/plans/task-list-ordering-and-gh-issues.md @@ -68,7 +68,7 @@ tasks: status: implement: done test: done - commit: open + commit: done - id: gh-issues-client title: GitHub GraphQL client + auth (gh auth token via @poe-code/process-runner) @@ -133,9 +133,9 @@ tasks: - No `@modelcontextprotocol/sdk`. - Tests mock fetch + runner; no live network. status: - implement: open - test: open - commit: open + implement: done + test: done + commit: done - id: gh-issues-skeleton title: gh-issues backend skeleton — open, fetch Status field, build state machine diff --git a/docs/plans/task-list-ordering-and-gh-issues.md.lock b/docs/plans/task-list-ordering-and-gh-issues.md.lock index 282db521bf..14e7acff9a 100644 --- a/docs/plans/task-list-ordering-and-gh-issues.md.lock +++ b/docs/plans/task-list-ordering-and-gh-issues.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T08:04:54.980Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T08:10:38.523Z"} \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 9d02d148d4..d5d717a3e1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7629,6 +7629,7 @@ "version": "0.0.1", "dependencies": { "@poe-code/file-lock": "*", + "@poe-code/process-runner": "*", "yaml": "*" } }, diff --git a/packages/task-list/package.json b/packages/task-list/package.json index 5e4e1c73e2..22307971bd 100644 --- a/packages/task-list/package.json +++ b/packages/task-list/package.json @@ -21,6 +21,7 @@ ], "dependencies": { "@poe-code/file-lock": "*", + "@poe-code/process-runner": "*", "yaml": "*" } } diff --git a/packages/task-list/src/backends/gh-issues-client.test.ts b/packages/task-list/src/backends/gh-issues-client.test.ts new file mode 100644 index 0000000000..d4154b0f67 --- /dev/null +++ b/packages/task-list/src/backends/gh-issues-client.test.ts @@ -0,0 +1,195 @@ +import { Readable } from "node:stream"; +import { describe, expect, it, vi } from "vitest"; +import type { RunHandle, Runner, RunSpec } from "@poe-code/process-runner"; +import { createGhClient, resolveAuth, resolveEndpoint } from "./gh-issues-client.js"; + +describe("resolveAuth", () => { + it("returns explicit token without invoking runner", async () => { + const runner = createStubRunner({ exitCode: 0, stdout: "from-gh\n" }); + + await expect(resolveAuth({ explicitToken: "explicit", runner })).resolves.toBe("explicit"); + + expect(runner.calls).toEqual([]); + }); + + it("shells out to gh auth token and trims output", async () => { + const runner = createStubRunner({ exitCode: 0, stdout: " gh-token\n" }); + + await expect(resolveAuth({ runner })).resolves.toBe("gh-token"); + + expect(runner.calls).toEqual([ + { + command: "gh", + args: ["auth", "token"], + stdout: "pipe", + stderr: "pipe" + } + ]); + }); + + it("throws when runner exit code is non-zero", async () => { + const runner = createStubRunner({ exitCode: 1, stdout: "token\n", stderr: "no auth\n" }); + + await expect(resolveAuth({ runner })).rejects.toThrow( + "gh auth token failed; install gh, run 'gh auth login', or pass auth: { token }" + ); + }); + + it("throws when runner stdout is empty", async () => { + const runner = createStubRunner({ exitCode: 0, stdout: " \n" }); + + await expect(resolveAuth({ runner })).rejects.toThrow( + "gh auth token failed; install gh, run 'gh auth login', or pass auth: { token }" + ); + }); +}); + +describe("resolveEndpoint", () => { + it("honors GH_HOST", () => { + expect(resolveEndpoint({ env: { GH_HOST: "github.example.test" } })).toBe( + "https://github.example.test/api/graphql" + ); + }); + + it("uses github.com GraphQL endpoint by default", () => { + expect(resolveEndpoint({ env: { GH_HOST: "github.com" } })).toBe( + "https://api.github.com/graphql" + ); + expect(resolveEndpoint({ env: {} })).toBe("https://api.github.com/graphql"); + }); +}); + +describe("createGhClient", () => { + it("injects auth header, posts the query, and returns data", async () => { + const fetchMock = vi.fn(async () => + createJsonResponse({ data: { viewer: { login: "octo" } } }) + ); + const client = createGhClient({ + token: "secret", + endpoint: "https://github.example.test/api/graphql", + fetch: fetchMock + }); + + await expect( + client.graphql<{ viewer: { login: string } }>( + "query Viewer($first: Int!) { viewer { login } }", + { + first: 1 + } + ) + ).resolves.toEqual({ viewer: { login: "octo" } }); + + expect(fetchMock).toHaveBeenCalledWith("https://github.example.test/api/graphql", { + method: "POST", + headers: { + Authorization: "Bearer secret", + "Content-Type": "application/json", + "User-Agent": "poe-code-task-list/0.0.1" + }, + body: JSON.stringify({ + query: "query Viewer($first: Int!) { viewer { login } }", + variables: { first: 1 } + }) + }); + }); + + it("uses the default github.com GraphQL endpoint when endpoint is omitted", async () => { + const fetchMock = vi.fn(async () => createJsonResponse({ data: { ok: true } })); + const client = createGhClient({ + token: "secret", + fetch: fetchMock + }); + + await expect( + client.graphql<{ ok: boolean }>("query { viewer { login } }", {}) + ).resolves.toEqual({ ok: true }); + + expect(fetchMock).toHaveBeenCalledWith( + "https://api.github.com/graphql", + expect.objectContaining({ + method: "POST" + }) + ); + }); + + it("throws on GraphQL errors", async () => { + const fetchMock = vi.fn(async () => + createJsonResponse({ errors: [{ message: "Could not resolve project" }] }) + ); + const client = createGhClient({ + token: "secret", + endpoint: "https://api.github.com/graphql", + fetch: fetchMock + }); + + await expect(client.graphql("query { viewer { login } }", {})).rejects.toThrow( + "Could not resolve project" + ); + }); + + it("throws a fallback message when a GraphQL error has no message", async () => { + const fetchMock = vi.fn(async () => createJsonResponse({ errors: [{}] })); + const client = createGhClient({ + token: "secret", + endpoint: "https://api.github.com/graphql", + fetch: fetchMock + }); + + await expect(client.graphql("query { viewer { login } }", {})).rejects.toThrow( + "GitHub GraphQL request failed" + ); + }); + + it("throws on non-200 responses with status and body", async () => { + const fetchMock = vi.fn(async () => + createJsonResponse({ message: "rate limited" }, { status: 403 }) + ); + const client = createGhClient({ + token: "secret", + endpoint: "https://api.github.com/graphql", + fetch: fetchMock + }); + + await expect(client.graphql("query { viewer { login } }", {})).rejects.toThrow( + 'GitHub GraphQL request failed with status 403: {"message":"rate limited"}' + ); + }); +}); + +function createJsonResponse(body: unknown, init: { status?: number } = {}): Response { + return new Response(JSON.stringify(body), { + status: init.status ?? 200, + headers: { "Content-Type": "application/json" } + }); +} + +function createStubRunner(behavior: { + exitCode: number; + stdout?: string; + stderr?: string; +}): Runner & { + calls: RunSpec[]; +} { + const calls: RunSpec[] = []; + + return { + name: "stub", + calls, + exec(spec) { + calls.push(spec); + + return { + pid: null, + stdout: streamFromString(behavior.stdout ?? ""), + stderr: streamFromString(behavior.stderr ?? ""), + stdin: null, + result: Promise.resolve({ exitCode: behavior.exitCode }), + kill() {} + } satisfies RunHandle; + } + }; +} + +function streamFromString(value: string): Readable { + return Readable.from([value]); +} diff --git a/packages/task-list/src/backends/gh-issues-client.ts b/packages/task-list/src/backends/gh-issues-client.ts new file mode 100644 index 0000000000..90a4cbefec --- /dev/null +++ b/packages/task-list/src/backends/gh-issues-client.ts @@ -0,0 +1,98 @@ +import { text } from "node:stream/consumers"; +import { createHostRunner, type Runner } from "@poe-code/process-runner"; + +const DEFAULT_ENDPOINT = "https://api.github.com/graphql"; +const USER_AGENT = "poe-code-task-list/0.0.1"; +const AUTH_ERROR = "gh auth token failed; install gh, run 'gh auth login', or pass auth: { token }"; + +export interface GhClientOptions { + token: string; + endpoint?: string; + fetch?: typeof fetch; +} + +export interface GhClient { + graphql(query: string, variables: Record): Promise; +} + +export function createGhClient(options: GhClientOptions): GhClient { + const fetchImpl = options.fetch ?? fetch; + const endpoint = options.endpoint || DEFAULT_ENDPOINT; + + return { + async graphql(query: string, variables: Record) { + const response = await fetchImpl(endpoint, { + method: "POST", + headers: { + Authorization: `Bearer ${options.token}`, + "Content-Type": "application/json", + "User-Agent": USER_AGENT + }, + body: JSON.stringify({ query, variables }) + }); + + const body = await response.text(); + if (response.status !== 200) { + throw new Error(`GitHub GraphQL request failed with status ${response.status}: ${body}`); + } + + const parsed = JSON.parse(body) as { + data?: T; + errors?: { message?: string }[]; + }; + const firstError = parsed.errors?.[0]; + if (firstError !== undefined) { + throw new Error(firstError.message ?? "GitHub GraphQL request failed"); + } + + return parsed.data as T; + } + }; +} + +export interface ResolveAuthOptions { + explicitToken?: string; + runner?: Runner; +} + +export async function resolveAuth(options: ResolveAuthOptions): Promise { + if (options.explicitToken !== undefined) { + return options.explicitToken; + } + + const runner = options.runner ?? createHostRunner(); + const handle = runner.exec({ + command: "gh", + args: ["auth", "token"], + stdout: "pipe", + stderr: "pipe" + }); + + const [stdout, , result] = await Promise.all([ + handle.stdout === null ? Promise.resolve("") : text(handle.stdout), + handle.stderr === null ? Promise.resolve("") : text(handle.stderr), + handle.result + ]); + const token = stdout.trim(); + + if (result.exitCode !== 0 || token.length === 0) { + throw new Error(AUTH_ERROR); + } + + return token; +} + +export interface ResolveEndpointOptions { + env?: Record; +} + +export function resolveEndpoint(options: ResolveEndpointOptions = {}): string { + const env = options.env ?? process.env; + const host = env.GH_HOST; + + if (host !== undefined && host !== "" && host !== "github.com") { + return `https://${host}/api/graphql`; + } + + return DEFAULT_ENDPOINT; +} diff --git a/packages/task-list/src/index.ts b/packages/task-list/src/index.ts index a4fa0951da..dd2ebde52d 100644 --- a/packages/task-list/src/index.ts +++ b/packages/task-list/src/index.ts @@ -31,3 +31,12 @@ export { type Tasks, type TaskUpdate } from "./types.js"; +export { + createGhClient, + resolveAuth, + resolveEndpoint, + type GhClient, + type GhClientOptions, + type ResolveAuthOptions, + type ResolveEndpointOptions +} from "./backends/gh-issues-client.js"; From 864d2849d41de0ef00e4c03d3e58f3cbd7f99a90 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 03:17:35 -0500 Subject: [PATCH 070/111] feat(task-list): add gh issues backend skeleton --- .../plans/task-list-ordering-and-gh-issues.md | 4 +- .../task-list-ordering-and-gh-issues.md.lock | 2 +- .../__snapshots__/gh-issues.test.ts.snap | 24 ++ .../task-list/src/backends/gh-issues.test.ts | 311 ++++++++++++++++++ packages/task-list/src/backends/gh-issues.ts | 245 ++++++++++++++ packages/task-list/src/index.ts | 1 + 6 files changed, 584 insertions(+), 3 deletions(-) create mode 100644 packages/task-list/src/backends/__snapshots__/gh-issues.test.ts.snap create mode 100644 packages/task-list/src/backends/gh-issues.test.ts create mode 100644 packages/task-list/src/backends/gh-issues.ts diff --git a/docs/plans/task-list-ordering-and-gh-issues.md b/docs/plans/task-list-ordering-and-gh-issues.md index 660001b706..20b5d29219 100644 --- a/docs/plans/task-list-ordering-and-gh-issues.md +++ b/docs/plans/task-list-ordering-and-gh-issues.md @@ -231,8 +231,8 @@ tasks: - Tests inject `fetch` via the deps; no live API. - Use `memfs` if any filesystem touches sneak in (none expected). status: - implement: open - test: open + implement: done + test: done commit: open - id: gh-issues-read diff --git a/docs/plans/task-list-ordering-and-gh-issues.md.lock b/docs/plans/task-list-ordering-and-gh-issues.md.lock index 14e7acff9a..de87264942 100644 --- a/docs/plans/task-list-ordering-and-gh-issues.md.lock +++ b/docs/plans/task-list-ordering-and-gh-issues.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T08:10:38.523Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T08:16:29.439Z"} \ No newline at end of file diff --git a/packages/task-list/src/backends/__snapshots__/gh-issues.test.ts.snap b/packages/task-list/src/backends/__snapshots__/gh-issues.test.ts.snap new file mode 100644 index 0000000000..38c6bba45b --- /dev/null +++ b/packages/task-list/src/backends/__snapshots__/gh-issues.test.ts.snap @@ -0,0 +1,24 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`ghIssuesBackend > keeps the project GraphQL request wire shape stable 1`] = ` +{ + "query": "query Project($owner: String!, $number: Int!) { + organization(login: $owner) { + projectV2(number: $number) { + id + title + field(name: "Status") { + ... on ProjectV2SingleSelectField { + id + options { id name } + } + } + } + } +}", + "variables": { + "number": 7, + "owner": "octo-org", + }, +} +`; diff --git a/packages/task-list/src/backends/gh-issues.test.ts b/packages/task-list/src/backends/gh-issues.test.ts new file mode 100644 index 0000000000..e2e666860d --- /dev/null +++ b/packages/task-list/src/backends/gh-issues.test.ts @@ -0,0 +1,311 @@ +import { describe, expect, it, vi } from "vitest"; +import { ghIssuesBackend, type GhIssuesBackendDeps } from "./gh-issues.js"; + +const DEFAULT_DEPS = { + repo: "octo/repo", + project: { + owner: "octo-org", + number: 7 + }, + defaults: { + metadata: {} + }, + token: "secret", + endpoint: "https://github.example.test/api/graphql" +} satisfies Omit; + +describe("ghIssuesBackend", () => { + it("fetches the project Status field and builds a state machine from display ordered options", async () => { + const fetchMock = createFetchMock([ + projectResponse({ + organization: { + projectV2: project({ + options: [ + { id: "status-todo", name: "Todo" }, + { id: "status-doing", name: "Doing" }, + { id: "status-done", name: "Done" } + ] + }) + }, + user: null + }) + ]); + + const taskList = await ghIssuesBackend({ + ...DEFAULT_DEPS, + fetch: fetchMock + }); + + expect(taskList.list("octo-org/7").stateMachine).toEqual({ + states: ["Todo", "Doing", "Done"], + initial: "Todo", + events: { + Todo: { from: "*", to: "Todo" }, + Doing: { from: "*", to: "Doing" }, + Done: { from: "*", to: "Done" } + } + }); + }); + + it("throws when the project has no Status field", async () => { + const fetchMock = createFetchMock([ + projectResponse({ + organization: { + projectV2: project({ + field: null + }) + }, + user: null + }) + ]); + + await expect( + ghIssuesBackend({ + ...DEFAULT_DEPS, + fetch: fetchMock + }) + ).rejects.toThrow("Project octo-org/7 has no Status field; gh-issues requires one."); + }); + + it("throws when Status is not a single-select field", async () => { + const fetchMock = createFetchMock([ + projectResponse({ + organization: { + projectV2: project({ + field: {} + }) + }, + user: null + }) + ]); + + await expect( + ghIssuesBackend({ + ...DEFAULT_DEPS, + fetch: fetchMock + }) + ).rejects.toThrow("Project octo-org/7 has no Status field; gh-issues requires one."); + }); + + it("throws when the Status field has no options", async () => { + const fetchMock = createFetchMock([ + projectResponse({ + organization: { + projectV2: project({ + options: [] + }) + }, + user: null + }) + ]); + + await expect( + ghIssuesBackend({ + ...DEFAULT_DEPS, + fetch: fetchMock + }) + ).rejects.toThrow("Project octo-org/7 Status field has no options."); + }); + + it("throws when the project is not found", async () => { + const fetchMock = createFetchMock([ + projectResponse({ + organization: null, + user: null + }), + projectResponse({ + organization: null, + user: null + }) + ]); + + await expect( + ghIssuesBackend({ + ...DEFAULT_DEPS, + fetch: fetchMock + }) + ).rejects.toThrow("Project octo-org/7 not found or inaccessible."); + }); + + it("falls back from organization to user for personal projects", async () => { + const fetchMock = createFetchMock([ + projectResponse({ + organization: null, + user: null + }), + projectResponse({ + organization: null, + user: { + projectV2: project({ + id: "user-project" + }) + } + }) + ]); + + const taskList = await ghIssuesBackend({ + ...DEFAULT_DEPS, + fetch: fetchMock + }); + + expect(taskList.list("octo-org/7").stateMachine.initial).toBe("Todo"); + expect(fetchMock).toHaveBeenCalledTimes(2); + }); + + it("does not query the user project when the organization project is found", async () => { + const fetchMock = createFetchMock([projectResponse()]); + + await ghIssuesBackend({ + ...DEFAULT_DEPS, + fetch: fetchMock + }); + + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it("returns the single project name from lists", async () => { + const taskList = await ghIssuesBackend({ + ...DEFAULT_DEPS, + fetch: createFetchMock([projectResponse()]) + }); + + await expect(taskList.lists()).resolves.toEqual(["octo-org/7"]); + }); + + it("throws when requesting any other list name", async () => { + const taskList = await ghIssuesBackend({ + ...DEFAULT_DEPS, + fetch: createFetchMock([projectResponse()]) + }); + + expect(() => taskList.list("wrong-name")).toThrow( + "gh-issues backend has a single list octo-org/7" + ); + }); + + it("delegates allTasks and get through the single project list", async () => { + const taskList = await ghIssuesBackend({ + ...DEFAULT_DEPS, + fetch: createFetchMock([projectResponse()]) + }); + + await expect(taskList.allTasks({ state: "Todo" })).rejects.toThrow("not yet implemented"); + await expect(taskList.get("octo-org/7/123")).rejects.toThrow("not yet implemented"); + }); + + it("uses the cached state machine for events and canFire without refetching", async () => { + const fetchMock = createFetchMock([projectResponse()]); + const taskList = await ghIssuesBackend({ + ...DEFAULT_DEPS, + fetch: fetchMock + }); + const tasks = taskList.list("octo-org/7"); + + await expect(tasks.events("Todo")).resolves.toEqual(["Done"]); + await expect(tasks.canFire("Todo", "Done")).resolves.toBe(true); + await expect(tasks.canFire("Done", "Done")).resolves.toBe(false); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it("freezes the derived state machine at open time", async () => { + const taskList = await ghIssuesBackend({ + ...DEFAULT_DEPS, + fetch: createFetchMock([projectResponse()]) + }); + const tasks = taskList.list("octo-org/7"); + + expect(Object.isFrozen(tasks.stateMachine)).toBe(true); + expect(Object.isFrozen(tasks.stateMachine.states)).toBe(true); + expect(Object.isFrozen(tasks.stateMachine.events)).toBe(true); + expect(Object.isFrozen(tasks.stateMachine.events.Todo)).toBe(true); + }); + + it("throws the single-list error when moving between lists", async () => { + const taskList = await ghIssuesBackend({ + ...DEFAULT_DEPS, + fetch: createFetchMock([projectResponse()]) + }); + + await expect(taskList.moveBetweenLists("octo-org/7/123", "octo-org/7")).rejects.toThrow( + "gh-issues backend has a single list octo-org/7" + ); + }); + + it("keeps the project GraphQL request wire shape stable", async () => { + const fetchMock = createFetchMock([projectResponse()]); + + await ghIssuesBackend({ + ...DEFAULT_DEPS, + fetch: fetchMock + }); + + expect(readGraphqlCall(fetchMock, 0)).toMatchSnapshot(); + }); +}); + +function projectResponse(data = defaultProjectData()): Response { + return new Response(JSON.stringify({ data }), { + status: 200, + headers: { "Content-Type": "application/json" } + }); +} + +function defaultProjectData() { + return { + organization: { + projectV2: project() + }, + user: null + }; +} + +function project( + overrides: Partial<{ + id: string; + title: string; + field: null | Record | { + id: string; + options: Array<{ id: string; name: string }>; + }; + options: Array<{ id: string; name: string }>; + }> = {} +) { + return { + id: overrides.id ?? "project-id", + title: overrides.title ?? "Roadmap", + field: + "field" in overrides + ? overrides.field + : { + id: "status-field", + options: overrides.options ?? [ + { id: "status-todo", name: "Todo" }, + { id: "status-done", name: "Done" } + ] + } + }; +} + +function createFetchMock(responses: Response[]): typeof fetch { + return vi.fn(async () => { + const response = responses.shift(); + if (response === undefined) { + throw new Error("Unexpected fetch call."); + } + return response; + }) as unknown as typeof fetch; +} + +function readGraphqlCall(fetchMock: typeof fetch, callIndex: number): unknown { + const call = vi.mocked(fetchMock).mock.calls[callIndex]; + if (call === undefined) { + throw new Error(`Missing fetch call ${callIndex}.`); + } + + const [, init] = call; + if (init === undefined || typeof init.body !== "string") { + throw new Error(`Fetch call ${callIndex} did not include a JSON body.`); + } + + return JSON.parse(init.body); +} diff --git a/packages/task-list/src/backends/gh-issues.ts b/packages/task-list/src/backends/gh-issues.ts new file mode 100644 index 0000000000..e4bfa09aef --- /dev/null +++ b/packages/task-list/src/backends/gh-issues.ts @@ -0,0 +1,245 @@ +import { eventsFromState, findEvent, type StateMachineDef } from "../state-machine.js"; +import type { + ListFilter, + MoveAnchor, + Task, + TaskCreate, + TaskDefaults, + TaskFireOptions, + TaskList, + Tasks, + TaskUpdate +} from "../types.js"; +import { createGhClient } from "./gh-issues-client.js"; + +const PROJECT_ORGANIZATION_QUERY = `query Project($owner: String!, $number: Int!) { + organization(login: $owner) { + projectV2(number: $number) { + id + title + field(name: "Status") { + ... on ProjectV2SingleSelectField { + id + options { id name } + } + } + } + } +}`; + +const PROJECT_USER_QUERY = `query Project($owner: String!, $number: Int!) { + user(login: $owner) { + projectV2(number: $number) { + id + title + field(name: "Status") { + ... on ProjectV2SingleSelectField { + id + options { id name } + } + } + } + } +}`; + +const NOT_IMPLEMENTED = "not yet implemented"; + +export interface GhIssuesBackendDeps { + repo: string; + project: { owner: string; number: number }; + defaults: Required; + token: string; + endpoint: string; + fetch?: typeof fetch; +} + +interface ProjectResponse { + organization?: ProjectOwner | null; + user?: ProjectOwner | null; +} + +interface ProjectOwner { + projectV2?: ProjectV2 | null; +} + +interface ProjectV2 { + id: string; + title: string; + field?: unknown; +} + +interface StatusField { + id: string; + options: StatusOption[]; +} + +interface StatusOption { + id: string; + name: string; +} + +interface GhIssuesSession { + projectId: string; + statusFieldId: string; + statusOptions: ReadonlyMap; + stateMachine: StateMachineDef; +} + +export async function ghIssuesBackend(deps: GhIssuesBackendDeps): Promise { + const client = createGhClient({ + token: deps.token, + endpoint: deps.endpoint, + fetch: deps.fetch + }); + const listName = `${deps.project.owner}/${deps.project.number}`; + const variables = { + owner: deps.project.owner, + number: deps.project.number + }; + + const organizationResult = await client.graphql( + PROJECT_ORGANIZATION_QUERY, + variables + ); + let project = organizationResult.organization?.projectV2 ?? null; + + if (project === null) { + const userResult = await client.graphql(PROJECT_USER_QUERY, variables); + project = userResult.user?.projectV2 ?? null; + } + + if (project === null) { + throw new Error(`Project ${listName} not found or inaccessible.`); + } + + const field = project.field; + if (!isStatusField(field)) { + throw new Error(`Project ${listName} has no Status field; gh-issues requires one.`); + } + + if (field.options.length === 0) { + throw new Error(`Project ${listName} Status field has no options.`); + } + + const session = createSession(project, field); + + function list(name: string): Tasks { + assertSingleList(name, listName); + return createTasksView(listName, session); + } + + return { + list, + async lists(): Promise { + return [listName]; + }, + async allTasks(filter?: ListFilter): Promise { + return list(listName).all(filter); + }, + async get(qualifiedId: string): Promise { + const id = parseQualifiedId(qualifiedId, listName); + return list(listName).get(id); + }, + async moveBetweenLists(_qualifiedId: string, _targetList: string): Promise { + throw singleListError(listName); + } + }; +} + +function createSession(project: ProjectV2, field: StatusField): GhIssuesSession { + const statusOptions = new Map(field.options.map((option) => [option.name, option.id])); + const states = field.options.map((option) => option.name); + const events = Object.fromEntries( + states.map((state) => [state, Object.freeze({ from: "*" as const, to: state })]) + ); + const stateMachine = Object.freeze({ + states: Object.freeze([...states]), + initial: states[0], + events: Object.freeze(events) + }) satisfies StateMachineDef; + + return Object.freeze({ + projectId: project.id, + statusFieldId: field.id, + statusOptions, + stateMachine + }); +} + +function createTasksView(name: string, session: GhIssuesSession): Tasks { + return { + name, + stateMachine: session.stateMachine, + async all(_filter?: ListFilter): Promise { + throw new Error(NOT_IMPLEMENTED); + }, + async get(_id: string): Promise { + throw new Error(NOT_IMPLEMENTED); + }, + async create(_input: TaskCreate): Promise { + throw new Error(NOT_IMPLEMENTED); + }, + async update(_id: string, _patch: TaskUpdate): Promise { + throw new Error(NOT_IMPLEMENTED); + }, + async fire(_id: string, _event: string, _opts?: TaskFireOptions): Promise { + throw new Error(NOT_IMPLEMENTED); + }, + async canFire(id: string, event: string): Promise { + return findEvent(session.stateMachine, id, event) !== undefined; + }, + async events(id: string): Promise { + return eventsFromState(session.stateMachine, id); + }, + async delete(_id: string): Promise { + throw new Error(NOT_IMPLEMENTED); + }, + async move(_id: string, _anchor: MoveAnchor): Promise { + throw new Error(NOT_IMPLEMENTED); + }, + async reorder(_ids: readonly string[]): Promise { + throw new Error(NOT_IMPLEMENTED); + } + }; +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function isStatusOption(value: unknown): value is StatusOption { + return ( + isRecord(value) && + typeof value.id === "string" && + typeof value.name === "string" + ); +} + +function isStatusField(value: unknown): value is StatusField { + return ( + isRecord(value) && + typeof value.id === "string" && + Array.isArray(value.options) && + value.options.every(isStatusOption) + ); +} + +function assertSingleList(name: string, listName: string): void { + if (name !== listName) { + throw singleListError(listName); + } +} + +function singleListError(listName: string): Error { + return new Error(`gh-issues backend has a single list ${listName}`); +} + +function parseQualifiedId(qualifiedId: string, listName: string): string { + const prefix = `${listName}/`; + + if (!qualifiedId.startsWith(prefix) || qualifiedId.length === prefix.length) { + throw new Error(`Invalid qualified task id "${qualifiedId}".`); + } + + return qualifiedId.slice(prefix.length); +} diff --git a/packages/task-list/src/index.ts b/packages/task-list/src/index.ts index dd2ebde52d..704cc29622 100644 --- a/packages/task-list/src/index.ts +++ b/packages/task-list/src/index.ts @@ -40,3 +40,4 @@ export { type ResolveAuthOptions, type ResolveEndpointOptions } from "./backends/gh-issues-client.js"; +export { ghIssuesBackend, type GhIssuesBackendDeps } from "./backends/gh-issues.js"; From 33de9d74d8d83621ead19acf14b906a09ad20c64 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 03:22:50 -0500 Subject: [PATCH 071/111] feat(task-list): add GitHub issues read path --- .../plans/task-list-ordering-and-gh-issues.md | 8 +- .../task-list-ordering-and-gh-issues.md.lock | 2 +- .../__snapshots__/gh-issues.test.ts.snap | 339 ++++++++++++++ .../task-list/src/backends/gh-issues.test.ts | 423 +++++++++++++++++- packages/task-list/src/backends/gh-issues.ts | 323 ++++++++++++- 5 files changed, 1071 insertions(+), 24 deletions(-) diff --git a/docs/plans/task-list-ordering-and-gh-issues.md b/docs/plans/task-list-ordering-and-gh-issues.md index 20b5d29219..82611c17e0 100644 --- a/docs/plans/task-list-ordering-and-gh-issues.md +++ b/docs/plans/task-list-ordering-and-gh-issues.md @@ -233,7 +233,7 @@ tasks: status: implement: done test: done - commit: open + commit: done - id: gh-issues-read title: gh-issues read path — Tasks.all() and Tasks.get() @@ -341,9 +341,9 @@ tasks: - No `child_process.spawn`. - Tests inject `fetch`; no live API. status: - implement: open - test: open - commit: open + implement: done + test: done + commit: done - id: gh-issues-create-update-fire title: gh-issues write path — create, update, fire diff --git a/docs/plans/task-list-ordering-and-gh-issues.md.lock b/docs/plans/task-list-ordering-and-gh-issues.md.lock index de87264942..83199d6498 100644 --- a/docs/plans/task-list-ordering-and-gh-issues.md.lock +++ b/docs/plans/task-list-ordering-and-gh-issues.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T08:16:29.439Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T08:21:27.853Z"} \ No newline at end of file diff --git a/packages/task-list/src/backends/__snapshots__/gh-issues.test.ts.snap b/packages/task-list/src/backends/__snapshots__/gh-issues.test.ts.snap index 38c6bba45b..55d8259e7e 100644 --- a/packages/task-list/src/backends/__snapshots__/gh-issues.test.ts.snap +++ b/packages/task-list/src/backends/__snapshots__/gh-issues.test.ts.snap @@ -1,5 +1,344 @@ // Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html +exports[`ghIssuesBackend > all merges paginated project items in project view order 1`] = ` +{ + "query": "query Items($projectId: ID!, $after: String) { + node(id: $projectId) { + ... on ProjectV2 { + items(first: 100, after: $after) { + nodes { + id + content { + __typename + ... on Issue { + number + title + body + url + createdAt + labels(first: 50) { nodes { name } } + assignees(first: 20) { nodes { login } } + milestone { title } + } + } + fieldValueByName(name: "Status") { + ... on ProjectV2ItemFieldSingleSelectValue { + name + } + } + } + pageInfo { hasNextPage endCursor } + } + } + } +}", + "variables": { + "after": null, + "projectId": "project-id", + }, +} +`; + +exports[`ghIssuesBackend > all merges paginated project items in project view order 2`] = ` +{ + "query": "query Items($projectId: ID!, $after: String) { + node(id: $projectId) { + ... on ProjectV2 { + items(first: 100, after: $after) { + nodes { + id + content { + __typename + ... on Issue { + number + title + body + url + createdAt + labels(first: 50) { nodes { name } } + assignees(first: 20) { nodes { login } } + milestone { title } + } + } + fieldValueByName(name: "Status") { + ... on ProjectV2ItemFieldSingleSelectValue { + name + } + } + } + pageInfo { hasNextPage endCursor } + } + } + } +}", + "variables": { + "after": "cursor-one", + "projectId": "project-id", + }, +} +`; + +exports[`ghIssuesBackend > all returns project issue items in project view order 1`] = ` +{ + "query": "query Items($projectId: ID!, $after: String) { + node(id: $projectId) { + ... on ProjectV2 { + items(first: 100, after: $after) { + nodes { + id + content { + __typename + ... on Issue { + number + title + body + url + createdAt + labels(first: 50) { nodes { name } } + assignees(first: 20) { nodes { login } } + milestone { title } + } + } + fieldValueByName(name: "Status") { + ... on ProjectV2ItemFieldSingleSelectValue { + name + } + } + } + pageInfo { hasNextPage endCursor } + } + } + } +}", + "variables": { + "after": null, + "projectId": "project-id", + }, +} +`; + +exports[`ghIssuesBackend > all({ order: 'alphabetical' }) sorts by qualifiedId 1`] = ` +{ + "query": "query Items($projectId: ID!, $after: String) { + node(id: $projectId) { + ... on ProjectV2 { + items(first: 100, after: $after) { + nodes { + id + content { + __typename + ... on Issue { + number + title + body + url + createdAt + labels(first: 50) { nodes { name } } + assignees(first: 20) { nodes { login } } + milestone { title } + } + } + fieldValueByName(name: "Status") { + ... on ProjectV2ItemFieldSingleSelectValue { + name + } + } + } + pageInfo { hasNextPage endCursor } + } + } + } +}", + "variables": { + "after": null, + "projectId": "project-id", + }, +} +`; + +exports[`ghIssuesBackend > all({ order: 'created' }) sorts by createdAt 1`] = ` +{ + "query": "query Items($projectId: ID!, $after: String) { + node(id: $projectId) { + ... on ProjectV2 { + items(first: 100, after: $after) { + nodes { + id + content { + __typename + ... on Issue { + number + title + body + url + createdAt + labels(first: 50) { nodes { name } } + assignees(first: 20) { nodes { login } } + milestone { title } + } + } + fieldValueByName(name: "Status") { + ... on ProjectV2ItemFieldSingleSelectValue { + name + } + } + } + pageInfo { hasNextPage endCursor } + } + } + } +}", + "variables": { + "after": null, + "projectId": "project-id", + }, +} +`; + +exports[`ghIssuesBackend > all({ state }) filters by Status name 1`] = ` +{ + "query": "query Items($projectId: ID!, $after: String) { + node(id: $projectId) { + ... on ProjectV2 { + items(first: 100, after: $after) { + nodes { + id + content { + __typename + ... on Issue { + number + title + body + url + createdAt + labels(first: 50) { nodes { name } } + assignees(first: 20) { nodes { login } } + milestone { title } + } + } + fieldValueByName(name: "Status") { + ... on ProjectV2ItemFieldSingleSelectValue { + name + } + } + } + pageInfo { hasNextPage endCursor } + } + } + } +}", + "variables": { + "after": null, + "projectId": "project-id", + }, +} +`; + +exports[`ghIssuesBackend > get("404") throws TaskNotFoundError when the issue does not exist 1`] = ` +{ + "query": "query Issue($owner: String!, $repo: String!, $number: Int!) { + repository(owner: $owner, name: $repo) { + issue(number: $number) { + number + title + body + url + createdAt + labels(first: 50) { nodes { name } } + assignees(first: 20) { nodes { login } } + milestone { title } + projectItems(first: 10) { + nodes { + id + project { id } + fieldValueByName(name: "Status") { + ... on ProjectV2ItemFieldSingleSelectValue { + name + } + } + } + } + } + } +}", + "variables": { + "number": 404, + "owner": "octo", + "repo": "repo", + }, +} +`; + +exports[`ghIssuesBackend > get("482") returns the mapped task 1`] = ` +{ + "query": "query Issue($owner: String!, $repo: String!, $number: Int!) { + repository(owner: $owner, name: $repo) { + issue(number: $number) { + number + title + body + url + createdAt + labels(first: 50) { nodes { name } } + assignees(first: 20) { nodes { login } } + milestone { title } + projectItems(first: 10) { + nodes { + id + project { id } + fieldValueByName(name: "Status") { + ... on ProjectV2ItemFieldSingleSelectValue { + name + } + } + } + } + } + } +}", + "variables": { + "number": 482, + "owner": "octo", + "repo": "repo", + }, +} +`; + +exports[`ghIssuesBackend > get("999") throws TaskNotFoundError when the issue is not in this project 1`] = ` +{ + "query": "query Issue($owner: String!, $repo: String!, $number: Int!) { + repository(owner: $owner, name: $repo) { + issue(number: $number) { + number + title + body + url + createdAt + labels(first: 50) { nodes { name } } + assignees(first: 20) { nodes { login } } + milestone { title } + projectItems(first: 10) { + nodes { + id + project { id } + fieldValueByName(name: "Status") { + ... on ProjectV2ItemFieldSingleSelectValue { + name + } + } + } + } + } + } +}", + "variables": { + "number": 999, + "owner": "octo", + "repo": "repo", + }, +} +`; + exports[`ghIssuesBackend > keeps the project GraphQL request wire shape stable 1`] = ` { "query": "query Project($owner: String!, $number: Int!) { diff --git a/packages/task-list/src/backends/gh-issues.test.ts b/packages/task-list/src/backends/gh-issues.test.ts index e2e666860d..dc31f4c6bc 100644 --- a/packages/task-list/src/backends/gh-issues.test.ts +++ b/packages/task-list/src/backends/gh-issues.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it, vi } from "vitest"; +import { TaskNotFoundError } from "../types.js"; import { ghIssuesBackend, type GhIssuesBackendDeps } from "./gh-issues.js"; const DEFAULT_DEPS = { @@ -186,11 +187,33 @@ describe("ghIssuesBackend", () => { it("delegates allTasks and get through the single project list", async () => { const taskList = await ghIssuesBackend({ ...DEFAULT_DEPS, - fetch: createFetchMock([projectResponse()]) + fetch: createFetchMock([ + projectResponse(), + itemsResponse({ + nodes: [ + projectIssueItem({ + id: "item-482", + issue: issue({ + number: 482, + title: "Ship GitHub issue backend" + }), + status: "Todo" + }) + ] + }), + issueResponse({ + number: 482, + title: "Ship GitHub issue backend", + status: "Todo" + }) + ]) }); - await expect(taskList.allTasks({ state: "Todo" })).rejects.toThrow("not yet implemented"); - await expect(taskList.get("octo-org/7/123")).rejects.toThrow("not yet implemented"); + await expect(taskList.allTasks({ state: "Todo" }).then(ids)).resolves.toEqual(["482"]); + await expect(taskList.get("octo-org/7/482")).resolves.toMatchObject({ + qualifiedId: "octo-org/7/482", + name: "Ship GitHub issue backend" + }); }); it("uses the cached state machine for events and canFire without refetching", async () => { @@ -241,8 +264,219 @@ describe("ghIssuesBackend", () => { expect(readGraphqlCall(fetchMock, 0)).toMatchSnapshot(); }); + + it("all returns project issue items in project view order", async () => { + const fetchMock = createFetchMock([ + projectResponse(), + itemsResponse({ + nodes: projectItemsFixture() + }) + ]); + const taskList = await ghIssuesBackend({ ...DEFAULT_DEPS, fetch: fetchMock }); + + await expect(taskList.list("octo-org/7").all()).resolves.toEqual([ + { + list: "octo-org/7", + id: "482", + qualifiedId: "octo-org/7/482", + name: "Write backend", + description: "Implement GitHub issues.", + state: "In progress", + metadata: { + url: "https://github.example.test/octo/repo/issues/482", + labels: ["backend", "task-list"], + assignees: ["mona"], + milestone: "v1", + projectItemId: "item-482", + created: "2026-01-03T00:00:00Z" + } + }, + { + list: "octo-org/7", + id: "17", + qualifiedId: "octo-org/7/17", + name: "Document workflow", + description: "", + state: "Todo", + metadata: { + url: "https://github.example.test/octo/repo/issues/17", + labels: [], + assignees: [], + milestone: null, + projectItemId: "item-17", + created: "2026-01-01T00:00:00Z" + } + }, + { + list: "octo-org/7", + id: "88", + qualifiedId: "octo-org/7/88", + name: "Close loop", + description: "Finalize.", + state: "Done", + metadata: { + url: "https://github.example.test/octo/repo/issues/88", + labels: ["release"], + assignees: ["hubot", "octocat"], + milestone: null, + projectItemId: "item-88", + created: "2026-01-02T00:00:00Z" + } + } + ]); + expect(readGraphqlCall(fetchMock, 1)).toMatchSnapshot(); + }); + + it("all({ order: 'alphabetical' }) sorts by qualifiedId", async () => { + const fetchMock = createFetchMock([ + projectResponse(), + itemsResponse({ + nodes: projectItemsFixture() + }) + ]); + const taskList = await ghIssuesBackend({ ...DEFAULT_DEPS, fetch: fetchMock }); + + await expect( + taskList.list("octo-org/7").all({ order: "alphabetical" }).then(ids) + ).resolves.toEqual(["17", "482", "88"]); + expect(readGraphqlCall(fetchMock, 1)).toMatchSnapshot(); + }); + + it("all({ order: 'created' }) sorts by createdAt", async () => { + const fetchMock = createFetchMock([ + projectResponse(), + itemsResponse({ + nodes: projectItemsFixture() + }) + ]); + const taskList = await ghIssuesBackend({ ...DEFAULT_DEPS, fetch: fetchMock }); + + await expect(taskList.list("octo-org/7").all({ order: "created" }).then(ids)).resolves.toEqual([ + "17", + "88", + "482" + ]); + expect(readGraphqlCall(fetchMock, 1)).toMatchSnapshot(); + }); + + it("all({ state }) filters by Status name", async () => { + const fetchMock = createFetchMock([ + projectResponse(), + itemsResponse({ + nodes: projectItemsFixture() + }) + ]); + const taskList = await ghIssuesBackend({ ...DEFAULT_DEPS, fetch: fetchMock }); + + await expect( + taskList.list("octo-org/7").all({ state: "In progress" }).then(ids) + ).resolves.toEqual(["482"]); + expect(readGraphqlCall(fetchMock, 1)).toMatchSnapshot(); + }); + + it("all({ includeArchived: true }) returns empty without querying items", async () => { + const fetchMock = createFetchMock([projectResponse()]); + const taskList = await ghIssuesBackend({ ...DEFAULT_DEPS, fetch: fetchMock }); + + await expect(taskList.list("octo-org/7").all({ includeArchived: true })).resolves.toEqual([]); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it("all merges paginated project items in project view order", async () => { + const fetchMock = createFetchMock([ + projectResponse(), + itemsResponse({ + nodes: [ + projectIssueItem({ + id: "item-482", + issue: issue({ number: 482, title: "First page" }) + }) + ], + hasNextPage: true, + endCursor: "cursor-one" + }), + itemsResponse({ + nodes: [ + projectIssueItem({ + id: "item-17", + issue: issue({ number: 17, title: "Second page" }) + }) + ], + hasNextPage: false, + endCursor: null + }) + ]); + const taskList = await ghIssuesBackend({ ...DEFAULT_DEPS, fetch: fetchMock }); + + await expect(taskList.list("octo-org/7").all().then(ids)).resolves.toEqual(["482", "17"]); + expect(readGraphqlCall(fetchMock, 1)).toMatchSnapshot(); + expect(readGraphqlCall(fetchMock, 2)).toMatchSnapshot(); + }); + + it('get("482") returns the mapped task', async () => { + const fetchMock = createFetchMock([ + projectResponse(), + issueResponse({ + number: 482, + title: "Write backend", + body: "Implement GitHub issues.", + status: "In progress", + labels: ["backend", "task-list"], + assignees: ["mona"], + milestone: "v1", + projectItemId: "item-482", + createdAt: "2026-01-03T00:00:00Z" + }) + ]); + const taskList = await ghIssuesBackend({ ...DEFAULT_DEPS, fetch: fetchMock }); + + await expect(taskList.list("octo-org/7").get("482")).resolves.toEqual({ + list: "octo-org/7", + id: "482", + qualifiedId: "octo-org/7/482", + name: "Write backend", + description: "Implement GitHub issues.", + state: "In progress", + metadata: { + url: "https://github.example.test/octo/repo/issues/482", + labels: ["backend", "task-list"], + assignees: ["mona"], + milestone: "v1", + projectItemId: "item-482", + created: "2026-01-03T00:00:00Z" + } + }); + expect(readGraphqlCall(fetchMock, 1)).toMatchSnapshot(); + }); + + it('get("999") throws TaskNotFoundError when the issue is not in this project', async () => { + const fetchMock = createFetchMock([ + projectResponse(), + issueResponse({ + number: 999, + projectId: "other-project", + projectItemId: "other-item" + }) + ]); + const taskList = await ghIssuesBackend({ ...DEFAULT_DEPS, fetch: fetchMock }); + + await expect(taskList.list("octo-org/7").get("999")).rejects.toBeInstanceOf(TaskNotFoundError); + expect(readGraphqlCall(fetchMock, 1)).toMatchSnapshot(); + }); + + it('get("404") throws TaskNotFoundError when the issue does not exist', async () => { + const fetchMock = createFetchMock([projectResponse(), missingIssueResponse()]); + const taskList = await ghIssuesBackend({ ...DEFAULT_DEPS, fetch: fetchMock }); + + await expect(taskList.list("octo-org/7").get("404")).rejects.toBeInstanceOf(TaskNotFoundError); + expect(readGraphqlCall(fetchMock, 1)).toMatchSnapshot(); + }); }); +function ids(tasks: { id: string }[]): string[] { + return tasks.map((task) => task.id); +} + function projectResponse(data = defaultProjectData()): Response { return new Response(JSON.stringify({ data }), { status: 200, @@ -263,10 +497,13 @@ function project( overrides: Partial<{ id: string; title: string; - field: null | Record | { - id: string; - options: Array<{ id: string; name: string }>; - }; + field: + | null + | Record + | { + id: string; + options: Array<{ id: string; name: string }>; + }; options: Array<{ id: string; name: string }>; }> = {} ) { @@ -296,6 +533,178 @@ function createFetchMock(responses: Response[]): typeof fetch { }) as unknown as typeof fetch; } +function itemsResponse(options: { + nodes: unknown[]; + hasNextPage?: boolean; + endCursor?: string | null; +}): Response { + return graphqlResponse({ + node: { + items: { + nodes: options.nodes, + pageInfo: { + hasNextPage: options.hasNextPage ?? false, + endCursor: options.endCursor ?? null + } + } + } + }); +} + +function issueResponse(options: { + number: number; + title?: string; + body?: string | null; + status?: string | null; + labels?: string[]; + assignees?: string[]; + milestone?: string | null; + projectId?: string; + projectItemId?: string; + createdAt?: string; +}): Response { + return graphqlResponse({ + repository: { + issue: { + ...issue(options), + projectItems: { + nodes: [ + { + id: options.projectItemId ?? `item-${options.number}`, + project: { + id: options.projectId ?? "project-id" + }, + fieldValueByName: + options.status === null + ? null + : { + name: options.status ?? "Todo" + } + } + ] + } + } + } + }); +} + +function missingIssueResponse(): Response { + return graphqlResponse({ + repository: { + issue: null + } + }); +} + +function graphqlResponse(data: unknown): Response { + return new Response(JSON.stringify({ data }), { + status: 200, + headers: { "Content-Type": "application/json" } + }); +} + +function projectItemsFixture(): unknown[] { + return [ + projectIssueItem({ + id: "item-482", + issue: issue({ + number: 482, + title: "Write backend", + body: "Implement GitHub issues.", + labels: ["backend", "task-list"], + assignees: ["mona"], + milestone: "v1", + createdAt: "2026-01-03T00:00:00Z" + }), + status: "In progress" + }), + { + id: "draft-item", + content: { + __typename: "DraftIssue", + title: "Draft item" + }, + fieldValueByName: { + name: "Todo" + } + }, + projectIssueItem({ + id: "item-17", + issue: issue({ + number: 17, + title: "Document workflow", + body: null, + labels: [], + assignees: [], + milestone: null, + createdAt: "2026-01-01T00:00:00Z" + }), + status: null + }), + projectIssueItem({ + id: "item-88", + issue: issue({ + number: 88, + title: "Close loop", + body: "Finalize.", + labels: ["release"], + assignees: ["hubot", "octocat"], + milestone: null, + createdAt: "2026-01-02T00:00:00Z" + }), + status: "Done" + }) + ]; +} + +function projectIssueItem(options: { + id: string; + issue: unknown; + status?: string | null; +}): unknown { + return { + id: options.id, + content: options.issue, + fieldValueByName: + options.status === null + ? null + : { + name: options.status ?? "Todo" + } + }; +} + +function issue(options: { + number: number; + title?: string; + body?: string | null; + labels?: string[]; + assignees?: string[]; + milestone?: string | null; + createdAt?: string; +}) { + return { + __typename: "Issue", + number: options.number, + title: options.title ?? `Issue ${options.number}`, + body: options.body ?? "", + url: `https://github.example.test/octo/repo/issues/${options.number}`, + createdAt: options.createdAt ?? "2026-01-01T00:00:00Z", + labels: { + nodes: (options.labels ?? []).map((name) => ({ name })) + }, + assignees: { + nodes: (options.assignees ?? []).map((login) => ({ login })) + }, + milestone: + options.milestone === undefined + ? null + : options.milestone === null + ? null + : { title: options.milestone } + }; +} + function readGraphqlCall(fetchMock: typeof fetch, callIndex: number): unknown { const call = vi.mocked(fetchMock).mock.calls[callIndex]; if (call === undefined) { diff --git a/packages/task-list/src/backends/gh-issues.ts b/packages/task-list/src/backends/gh-issues.ts index e4bfa09aef..946b8cffcf 100644 --- a/packages/task-list/src/backends/gh-issues.ts +++ b/packages/task-list/src/backends/gh-issues.ts @@ -10,7 +10,9 @@ import type { Tasks, TaskUpdate } from "../types.js"; -import { createGhClient } from "./gh-issues-client.js"; +import { TaskNotFoundError } from "../types.js"; +import { createGhClient, type GhClient } from "./gh-issues-client.js"; +import { applyOrder, sortTasks } from "./utils.js"; const PROJECT_ORGANIZATION_QUERY = `query Project($owner: String!, $number: Int!) { organization(login: $owner) { @@ -42,6 +44,63 @@ const PROJECT_USER_QUERY = `query Project($owner: String!, $number: Int!) { } }`; +const PROJECT_ITEMS_QUERY = `query Items($projectId: ID!, $after: String) { + node(id: $projectId) { + ... on ProjectV2 { + items(first: 100, after: $after) { + nodes { + id + content { + __typename + ... on Issue { + number + title + body + url + createdAt + labels(first: 50) { nodes { name } } + assignees(first: 20) { nodes { login } } + milestone { title } + } + } + fieldValueByName(name: "Status") { + ... on ProjectV2ItemFieldSingleSelectValue { + name + } + } + } + pageInfo { hasNextPage endCursor } + } + } + } +}`; + +const ISSUE_QUERY = `query Issue($owner: String!, $repo: String!, $number: Int!) { + repository(owner: $owner, name: $repo) { + issue(number: $number) { + number + title + body + url + createdAt + labels(first: 50) { nodes { name } } + assignees(first: 20) { nodes { login } } + milestone { title } + projectItems(first: 10) { + nodes { + id + project { id } + fieldValueByName(name: "Status") { + ... on ProjectV2ItemFieldSingleSelectValue { + name + } + } + } + } + } + } +}`; + const NOT_IMPLEMENTED = "not yet implemented"; export interface GhIssuesBackendDeps { @@ -85,6 +144,74 @@ interface GhIssuesSession { stateMachine: StateMachineDef; } +interface GhIssuesTasksContext { + client: GhClient; + repoOwner: string; + repoName: string; +} + +interface ProjectItemsResponse { + node?: { + items?: ProjectItemsConnection | null; + } | null; +} + +interface ProjectItemsConnection { + nodes?: ProjectItemNode[]; + pageInfo?: { + hasNextPage?: boolean; + endCursor?: string | null; + }; +} + +interface ProjectItemNode { + id: string; + content?: IssueNode | { __typename?: string } | null; + fieldValueByName?: StatusValue | null; +} + +interface IssueResponse { + repository?: { + issue?: IssueNodeWithProjectItems | null; + } | null; +} + +interface IssueNode { + __typename?: "Issue"; + number: number; + title: string; + body?: string | null; + url: string; + createdAt: string; + labels?: { + nodes?: Array<{ name: string } | null>; + } | null; + assignees?: { + nodes?: Array<{ login: string } | null>; + } | null; + milestone?: { + title: string; + } | null; +} + +interface IssueNodeWithProjectItems extends IssueNode { + projectItems?: { + nodes?: ProjectItemMembership[]; + } | null; +} + +interface ProjectItemMembership { + id: string; + project?: { + id?: string; + } | null; + fieldValueByName?: StatusValue | null; +} + +interface StatusValue { + name?: string | null; +} + export async function ghIssuesBackend(deps: GhIssuesBackendDeps): Promise { const client = createGhClient({ token: deps.token, @@ -122,10 +249,16 @@ export async function ghIssuesBackend(deps: GhIssuesBackendDeps): Promise { - throw new Error(NOT_IMPLEMENTED); + async all(filter?: ListFilter): Promise { + if (filter?.includeArchived === true) { + return []; + } + + const tasks = await fetchProjectTasks(name, session, context); + const filteredTasks = + filter?.state === undefined ? tasks : tasks.filter((task) => task.state === filter.state); + + if (filter?.order === "alphabetical") { + return sortTasks(filteredTasks); + } + + if (filter?.order === "created") { + return applyOrder( + filteredTasks.map((task) => ({ + task, + raw: { + created: task.metadata.created + } + })), + "created" + ); + } + + return filteredTasks; }, - async get(_id: string): Promise { - throw new Error(NOT_IMPLEMENTED); + async get(id: string): Promise { + return fetchIssueTask(id, name, session, context); }, async create(_input: TaskCreate): Promise { throw new Error(NOT_IMPLEMENTED); @@ -203,18 +364,156 @@ function createTasksView(name: string, session: GhIssuesSession): Tasks { }; } -function isRecord(value: unknown): value is Record { - return typeof value === "object" && value !== null && !Array.isArray(value); +async function fetchProjectTasks( + listName: string, + session: GhIssuesSession, + context: GhIssuesTasksContext +): Promise { + const tasks: Task[] = []; + let after: string | null = null; + + do { + const result: ProjectItemsResponse = await context.client.graphql( + PROJECT_ITEMS_QUERY, + { + projectId: session.projectId, + after + } + ); + const items: ProjectItemsConnection | null | undefined = result.node?.items; + + for (const item of items?.nodes ?? []) { + const task = mapProjectItemToTask(item, listName, session); + if (task !== null) { + tasks.push(task); + } + } + + after = items?.pageInfo?.hasNextPage === true ? (items.pageInfo.endCursor ?? null) : null; + } while (after !== null); + + return tasks; } -function isStatusOption(value: unknown): value is StatusOption { +async function fetchIssueTask( + id: string, + listName: string, + session: GhIssuesSession, + context: GhIssuesTasksContext +): Promise { + const issueNumber = Number(id); + if (!Number.isInteger(issueNumber) || issueNumber < 1) { + throw new TaskNotFoundError(`Task "${listName}/${id}" not found.`); + } + + const result = await context.client.graphql(ISSUE_QUERY, { + owner: context.repoOwner, + repo: context.repoName, + number: issueNumber + }); + const issue = result.repository?.issue ?? null; + if (issue === null) { + throw new TaskNotFoundError(`Task "${listName}/${id}" not found.`); + } + + const projectItem = + issue.projectItems?.nodes?.find((item) => item.project?.id === session.projectId) ?? null; + if (projectItem === null) { + throw new TaskNotFoundError(`Task "${listName}/${id}" not found.`); + } + + return mapIssueToTask({ + issue, + projectItemId: projectItem.id, + statusName: projectItem.fieldValueByName?.name ?? null, + listName, + initialState: session.stateMachine.initial + }); +} + +function mapProjectItemToTask( + item: ProjectItemNode, + listName: string, + session: GhIssuesSession +): Task | null { + const content = item.content; + if (!isIssueNode(content)) { + return null; + } + + return mapIssueToTask({ + issue: content, + projectItemId: item.id, + statusName: item.fieldValueByName?.name ?? null, + listName, + initialState: session.stateMachine.initial + }); +} + +function isIssueNode(value: unknown): value is IssueNode { return ( isRecord(value) && - typeof value.id === "string" && - typeof value.name === "string" + value.__typename === "Issue" && + typeof value.number === "number" && + typeof value.title === "string" && + typeof value.url === "string" && + typeof value.createdAt === "string" ); } +function mapIssueToTask(options: { + issue: IssueNode; + projectItemId: string; + statusName: string | null; + listName: string; + initialState: string; +}): Task { + const id = String(options.issue.number); + const labels = (options.issue.labels?.nodes ?? []) + .filter((node): node is { name: string } => node !== null) + .map((node) => node.name); + const assignees = (options.issue.assignees?.nodes ?? []) + .filter((node): node is { login: string } => node !== null) + .map((node) => node.login); + + return { + list: options.listName, + id, + qualifiedId: `${options.listName}/${id}`, + name: options.issue.title, + description: options.issue.body ?? "", + state: options.statusName ?? options.initialState, + metadata: { + url: options.issue.url, + labels, + assignees, + milestone: options.issue.milestone?.title ?? null, + projectItemId: options.projectItemId, + created: options.issue.createdAt + } + }; +} + +function parseRepo(repo: string): { owner: string; name: string } { + const parts = repo.split("/"); + if (parts.length !== 2 || parts[0] === "" || parts[1] === "") { + throw new Error(`Invalid GitHub repository "${repo}". Expected "owner/name".`); + } + + return { + owner: parts[0], + name: parts[1] + }; +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function isStatusOption(value: unknown): value is StatusOption { + return isRecord(value) && typeof value.id === "string" && typeof value.name === "string"; +} + function isStatusField(value: unknown): value is StatusField { return ( isRecord(value) && From 56a6971a3da6012b7f93e8e5b4681b7d7a71d999 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 03:29:09 -0500 Subject: [PATCH 072/111] feat(task-list): support GitHub issue mutations --- .../plans/task-list-ordering-and-gh-issues.md | 4 +- .../task-list-ordering-and-gh-issues.md.lock | 2 +- .../__snapshots__/gh-issues.test.ts.snap | 378 ++++++++++++++++++ .../task-list/src/backends/gh-issues.test.ts | 376 ++++++++++++++++- packages/task-list/src/backends/gh-issues.ts | 300 +++++++++++++- 5 files changed, 1044 insertions(+), 16 deletions(-) diff --git a/docs/plans/task-list-ordering-and-gh-issues.md b/docs/plans/task-list-ordering-and-gh-issues.md index 82611c17e0..809acc828b 100644 --- a/docs/plans/task-list-ordering-and-gh-issues.md +++ b/docs/plans/task-list-ordering-and-gh-issues.md @@ -406,8 +406,8 @@ tasks: - State machine override (`OpenTaskListOptions.stateMachine`) does not apply to gh-issues; if a caller passed one, ignore it (documented in plan 5c). status: - implement: open - test: open + implement: done + test: done commit: open - id: gh-issues-reorder-delete diff --git a/docs/plans/task-list-ordering-and-gh-issues.md.lock b/docs/plans/task-list-ordering-and-gh-issues.md.lock index 83199d6498..b3e0310d44 100644 --- a/docs/plans/task-list-ordering-and-gh-issues.md.lock +++ b/docs/plans/task-list-ordering-and-gh-issues.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T08:21:27.853Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T08:28:14.856Z"} \ No newline at end of file diff --git a/packages/task-list/src/backends/__snapshots__/gh-issues.test.ts.snap b/packages/task-list/src/backends/__snapshots__/gh-issues.test.ts.snap index 55d8259e7e..e5227facca 100644 --- a/packages/task-list/src/backends/__snapshots__/gh-issues.test.ts.snap +++ b/packages/task-list/src/backends/__snapshots__/gh-issues.test.ts.snap @@ -234,6 +234,273 @@ exports[`ghIssuesBackend > all({ state }) filters by Status name 1`] = ` } `; +exports[`ghIssuesBackend > create fetches the repository id lazily and caches it for later creates 1`] = ` +[ + { + "query": "mutation CreateIssue($input: CreateIssueInput!) { + createIssue(input: $input) { + issue { + id + number + } + } +}", + "variables": { + "input": { + "body": "", + "repositoryId": "repo-node", + "title": "First issue", + }, + }, + }, + { + "query": "mutation AddProjectItem($input: AddProjectV2ItemByIdInput!) { + addProjectV2ItemById(input: $input) { + item { + id + } + } +}", + "variables": { + "input": { + "contentId": "issue-node-101", + "projectId": "project-id", + }, + }, + }, + { + "query": "mutation UpdateProjectItemStatus($input: UpdateProjectV2ItemFieldValueInput!) { + updateProjectV2ItemFieldValue(input: $input) { + projectV2Item { + id + } + } +}", + "variables": { + "input": { + "fieldId": "status-field", + "itemId": "item-101", + "projectId": "project-id", + "value": { + "singleSelectOptionId": "status-todo", + }, + }, + }, + }, + { + "query": "mutation CreateIssue($input: CreateIssueInput!) { + createIssue(input: $input) { + issue { + id + number + } + } +}", + "variables": { + "input": { + "body": "", + "repositoryId": "repo-node", + "title": "Second issue", + }, + }, + }, + { + "query": "mutation AddProjectItem($input: AddProjectV2ItemByIdInput!) { + addProjectV2ItemById(input: $input) { + item { + id + } + } +}", + "variables": { + "input": { + "contentId": "issue-node-102", + "projectId": "project-id", + }, + }, + }, + { + "query": "mutation UpdateProjectItemStatus($input: UpdateProjectV2ItemFieldValueInput!) { + updateProjectV2ItemFieldValue(input: $input) { + projectV2Item { + id + } + } +}", + "variables": { + "input": { + "fieldId": "status-field", + "itemId": "item-102", + "projectId": "project-id", + "value": { + "singleSelectOptionId": "status-todo", + }, + }, + }, + }, +] +`; + +exports[`ghIssuesBackend > create ignores a passed id and uses the GitHub-assigned issue number 1`] = ` +[ + { + "query": "mutation CreateIssue($input: CreateIssueInput!) { + createIssue(input: $input) { + issue { + id + number + } + } +}", + "variables": { + "input": { + "body": "", + "repositoryId": "repo-node", + "title": "Server id wins", + }, + }, + }, + { + "query": "mutation AddProjectItem($input: AddProjectV2ItemByIdInput!) { + addProjectV2ItemById(input: $input) { + item { + id + } + } +}", + "variables": { + "input": { + "contentId": "issue-node-914", + "projectId": "project-id", + }, + }, + }, + { + "query": "mutation UpdateProjectItemStatus($input: UpdateProjectV2ItemFieldValueInput!) { + updateProjectV2ItemFieldValue(input: $input) { + projectV2Item { + id + } + } +}", + "variables": { + "input": { + "fieldId": "status-field", + "itemId": "item-914", + "projectId": "project-id", + "value": { + "singleSelectOptionId": "status-todo", + }, + }, + }, + }, +] +`; + +exports[`ghIssuesBackend > create({ name, description }) issues the GitHub issue and project mutations 1`] = ` +[ + { + "query": "mutation CreateIssue($input: CreateIssueInput!) { + createIssue(input: $input) { + issue { + id + number + } + } +}", + "variables": { + "input": { + "body": "Created from task-list.", + "repositoryId": "repo-node", + "title": "New issue", + }, + }, + }, + { + "query": "mutation AddProjectItem($input: AddProjectV2ItemByIdInput!) { + addProjectV2ItemById(input: $input) { + item { + id + } + } +}", + "variables": { + "input": { + "contentId": "issue-node-573", + "projectId": "project-id", + }, + }, + }, + { + "query": "mutation UpdateProjectItemStatus($input: UpdateProjectV2ItemFieldValueInput!) { + updateProjectV2ItemFieldValue(input: $input) { + projectV2Item { + id + } + } +}", + "variables": { + "input": { + "fieldId": "status-field", + "itemId": "item-573", + "projectId": "project-id", + "value": { + "singleSelectOptionId": "status-todo", + }, + }, + }, + }, +] +`; + +exports[`ghIssuesBackend > fire ignores metadataPatch and only writes the Status field 1`] = ` +[ + { + "query": "mutation UpdateProjectItemStatus($input: UpdateProjectV2ItemFieldValueInput!) { + updateProjectV2ItemFieldValue(input: $input) { + projectV2Item { + id + } + } +}", + "variables": { + "input": { + "fieldId": "status-field", + "itemId": "item-482", + "projectId": "project-id", + "value": { + "singleSelectOptionId": "status-done", + }, + }, + }, + }, +] +`; + +exports[`ghIssuesBackend > fire("482", "") sets the matching Status option 1`] = ` +[ + { + "query": "mutation UpdateProjectItemStatus($input: UpdateProjectV2ItemFieldValueInput!) { + updateProjectV2ItemFieldValue(input: $input) { + projectV2Item { + id + } + } +}", + "variables": { + "input": { + "fieldId": "status-field", + "itemId": "item-482", + "projectId": "project-id", + "value": { + "singleSelectOptionId": "status-done", + }, + }, + }, + }, +] +`; + exports[`ghIssuesBackend > get("404") throws TaskNotFoundError when the issue does not exist 1`] = ` { "query": "query Issue($owner: String!, $repo: String!, $number: Int!) { @@ -361,3 +628,114 @@ exports[`ghIssuesBackend > keeps the project GraphQL request wire shape stable 1 }, } `; + +exports[`ghIssuesBackend > update uses the issue id cached by create 1`] = ` +[ + { + "query": "mutation CreateIssue($input: CreateIssueInput!) { + createIssue(input: $input) { + issue { + id + number + } + } +}", + "variables": { + "input": { + "body": "", + "repositoryId": "repo-node", + "title": "Original", + }, + }, + }, + { + "query": "mutation AddProjectItem($input: AddProjectV2ItemByIdInput!) { + addProjectV2ItemById(input: $input) { + item { + id + } + } +}", + "variables": { + "input": { + "contentId": "issue-node-573", + "projectId": "project-id", + }, + }, + }, + { + "query": "mutation UpdateProjectItemStatus($input: UpdateProjectV2ItemFieldValueInput!) { + updateProjectV2ItemFieldValue(input: $input) { + projectV2Item { + id + } + } +}", + "variables": { + "input": { + "fieldId": "status-field", + "itemId": "item-573", + "projectId": "project-id", + "value": { + "singleSelectOptionId": "status-todo", + }, + }, + }, + }, + { + "query": "mutation UpdateIssue($input: UpdateIssueInput!) { + updateIssue(input: $input) { + issue { + id + } + } +}", + "variables": { + "input": { + "id": "issue-node-573", + "title": "Renamed", + }, + }, + }, +] +`; + +exports[`ghIssuesBackend > update("482", { description: "new body" }) issues only updateIssue with body 1`] = ` +[ + { + "query": "mutation UpdateIssue($input: UpdateIssueInput!) { + updateIssue(input: $input) { + issue { + id + } + } +}", + "variables": { + "input": { + "body": "new body", + "id": "issue-node-482", + }, + }, + }, +] +`; + +exports[`ghIssuesBackend > update("482", { name: "new" }) issues only updateIssue with title 1`] = ` +[ + { + "query": "mutation UpdateIssue($input: UpdateIssueInput!) { + updateIssue(input: $input) { + issue { + id + } + } +}", + "variables": { + "input": { + "id": "issue-node-482", + "title": "new", + }, + }, + }, +] +`; diff --git a/packages/task-list/src/backends/gh-issues.test.ts b/packages/task-list/src/backends/gh-issues.test.ts index dc31f4c6bc..7528233ead 100644 --- a/packages/task-list/src/backends/gh-issues.test.ts +++ b/packages/task-list/src/backends/gh-issues.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi } from "vitest"; -import { TaskNotFoundError } from "../types.js"; +import { InvalidTransitionError, TaskNotFoundError } from "../types.js"; import { ghIssuesBackend, type GhIssuesBackendDeps } from "./gh-issues.js"; const DEFAULT_DEPS = { @@ -471,6 +471,273 @@ describe("ghIssuesBackend", () => { await expect(taskList.list("octo-org/7").get("404")).rejects.toBeInstanceOf(TaskNotFoundError); expect(readGraphqlCall(fetchMock, 1)).toMatchSnapshot(); }); + + it("create({ name, description }) issues the GitHub issue and project mutations", async () => { + const fetchMock = createFetchMock([ + projectResponse(), + repositoryResponse("repo-node"), + createIssueResponse({ + issueId: "issue-node-573", + number: 573 + }), + addProjectItemResponse("item-573"), + updateStatusResponse(), + issueResponse({ + number: 573, + title: "New issue", + body: "Created from task-list.", + status: "Todo", + projectItemId: "item-573" + }) + ]); + const taskList = await ghIssuesBackend({ ...DEFAULT_DEPS, fetch: fetchMock }); + + const task = await taskList.list("octo-org/7").create({ + name: "New issue", + description: "Created from task-list." + }); + + expect(task).toMatchObject({ + id: "573", + name: "New issue", + description: "Created from task-list.", + state: "Todo" + }); + expect(readMutationCalls(fetchMock)).toMatchSnapshot(); + }); + + it("create ignores a passed id and uses the GitHub-assigned issue number", async () => { + const fetchMock = createFetchMock([ + projectResponse(), + repositoryResponse("repo-node"), + createIssueResponse({ + issueId: "issue-node-914", + number: 914 + }), + addProjectItemResponse("item-914"), + updateStatusResponse(), + issueResponse({ + number: 914, + title: "Server id wins", + status: "Todo", + projectItemId: "item-914" + }) + ]); + const taskList = await ghIssuesBackend({ ...DEFAULT_DEPS, fetch: fetchMock }); + + const task = await taskList.list("octo-org/7").create({ + id: "client-id", + name: "Server id wins" + }); + + expect(task.id).toBe("914"); + expect(readMutationCalls(fetchMock)).toMatchSnapshot(); + }); + + it("create fetches the repository id lazily and caches it for later creates", async () => { + const fetchMock = createFetchMock([ + projectResponse(), + repositoryResponse("repo-node"), + createIssueResponse({ + issueId: "issue-node-101", + number: 101 + }), + addProjectItemResponse("item-101"), + updateStatusResponse(), + issueResponse({ + number: 101, + title: "First issue", + status: "Todo", + projectItemId: "item-101" + }), + createIssueResponse({ + issueId: "issue-node-102", + number: 102 + }), + addProjectItemResponse("item-102"), + updateStatusResponse(), + issueResponse({ + number: 102, + title: "Second issue", + status: "Todo", + projectItemId: "item-102" + }) + ]); + const taskList = await ghIssuesBackend({ ...DEFAULT_DEPS, fetch: fetchMock }); + const tasks = taskList.list("octo-org/7"); + + await expect(tasks.create({ name: "First issue" })).resolves.toMatchObject({ id: "101" }); + await expect(tasks.create({ name: "Second issue" })).resolves.toMatchObject({ id: "102" }); + + expect(readGraphqlCalls(fetchMock).filter(isRepositoryQuery)).toHaveLength(1); + expect(readMutationCalls(fetchMock)).toMatchSnapshot(); + }); + + it("update uses the issue id cached by create", async () => { + const fetchMock = createFetchMock([ + projectResponse(), + repositoryResponse("repo-node"), + createIssueResponse({ + issueId: "issue-node-573", + number: 573 + }), + addProjectItemResponse("item-573"), + updateStatusResponse(), + issueResponse({ + number: 573, + title: "Original", + status: "Todo", + projectItemId: "item-573" + }), + updateIssueResponse(), + issueResponse({ + number: 573, + title: "Renamed", + status: "Todo", + projectItemId: "item-573" + }) + ]); + const taskList = await ghIssuesBackend({ ...DEFAULT_DEPS, fetch: fetchMock }); + const tasks = taskList.list("octo-org/7"); + + const created = await tasks.create({ name: "Original" }); + await expect(tasks.update(created.id, { name: "Renamed" })).resolves.toMatchObject({ + id: "573", + name: "Renamed" + }); + + expect(readGraphqlCalls(fetchMock).filter(isIssueIdQuery)).toHaveLength(0); + expect(readMutationCalls(fetchMock)).toMatchSnapshot(); + }); + + it('update("482", { name: "new" }) issues only updateIssue with title', async () => { + const fetchMock = createFetchMock([ + projectResponse(), + issueNodeIdResponse("issue-node-482"), + updateIssueResponse(), + issueResponse({ + number: 482, + title: "new", + status: "Todo" + }) + ]); + const taskList = await ghIssuesBackend({ ...DEFAULT_DEPS, fetch: fetchMock }); + + await expect(taskList.list("octo-org/7").update("482", { name: "new" })).resolves.toMatchObject( + { + id: "482", + name: "new" + } + ); + expect(readMutationCalls(fetchMock)).toMatchSnapshot(); + }); + + it('update("482", { description: "new body" }) issues only updateIssue with body', async () => { + const fetchMock = createFetchMock([ + projectResponse(), + issueNodeIdResponse("issue-node-482"), + updateIssueResponse(), + issueResponse({ + number: 482, + title: "Keep title", + body: "new body", + status: "Todo" + }) + ]); + const taskList = await ghIssuesBackend({ ...DEFAULT_DEPS, fetch: fetchMock }); + + await expect( + taskList.list("octo-org/7").update("482", { description: "new body" }) + ).resolves.toMatchObject({ + id: "482", + name: "Keep title", + description: "new body" + }); + expect(readMutationCalls(fetchMock)).toMatchSnapshot(); + }); + + it('update("482", { metadata: { labels: ["x"] } }) is a no-op mutation', async () => { + const fetchMock = createFetchMock([ + projectResponse(), + issueResponse({ + number: 482, + title: "Read only metadata", + status: "Todo" + }) + ]); + const taskList = await ghIssuesBackend({ ...DEFAULT_DEPS, fetch: fetchMock }); + + // metadata writes are out of scope for v1 on gh-issues, so labels are read-only here. + await expect( + taskList.list("octo-org/7").update("482", { metadata: { labels: ["x"] } }) + ).resolves.toMatchObject({ + id: "482", + name: "Read only metadata" + }); + expect(readMutationCalls(fetchMock)).toEqual([]); + }); + + it('fire("482", "") sets the matching Status option', async () => { + const fetchMock = createFetchMock([ + projectResponse(), + issueProjectItemResponse({ + issueId: "issue-node-482", + projectItemId: "item-482" + }), + updateStatusResponse(), + issueResponse({ + number: 482, + title: "Move me", + status: "Done", + projectItemId: "item-482" + }) + ]); + const taskList = await ghIssuesBackend({ ...DEFAULT_DEPS, fetch: fetchMock }); + + await expect(taskList.list("octo-org/7").fire("482", "Done")).resolves.toMatchObject({ + id: "482", + state: "Done" + }); + expect(readMutationCalls(fetchMock)).toMatchSnapshot(); + }); + + it("fire ignores metadataPatch and only writes the Status field", async () => { + const fetchMock = createFetchMock([ + projectResponse(), + issueProjectItemResponse({ + issueId: "issue-node-482", + projectItemId: "item-482" + }), + updateStatusResponse(), + issueResponse({ + number: 482, + title: "Move without metadata writes", + status: "Done", + projectItemId: "item-482" + }) + ]); + const taskList = await ghIssuesBackend({ ...DEFAULT_DEPS, fetch: fetchMock }); + + await expect( + taskList.list("octo-org/7").fire("482", "Done", { + metadataPatch: { labels: ["x"], milestone: "v2" } + }) + ).resolves.toMatchObject({ + id: "482", + state: "Done" + }); + expect(readMutationCalls(fetchMock)).toMatchSnapshot(); + }); + + it('fire("482", "") throws InvalidTransitionError', async () => { + const fetchMock = createFetchMock([projectResponse()]); + const taskList = await ghIssuesBackend({ ...DEFAULT_DEPS, fetch: fetchMock }); + + await expect(taskList.list("octo-org/7").fire("482", "Blocked")).rejects.toBeInstanceOf( + InvalidTransitionError + ); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); }); function ids(tasks: { id: string }[]): string[] { @@ -596,6 +863,85 @@ function missingIssueResponse(): Response { }); } +function repositoryResponse(id: string): Response { + return graphqlResponse({ + repository: { + id + } + }); +} + +function createIssueResponse(options: { issueId: string; number: number }): Response { + return graphqlResponse({ + createIssue: { + issue: { + id: options.issueId, + number: options.number + } + } + }); +} + +function addProjectItemResponse(projectItemId: string): Response { + return graphqlResponse({ + addProjectV2ItemById: { + item: { + id: projectItemId + } + } + }); +} + +function updateStatusResponse(): Response { + return graphqlResponse({ + updateProjectV2ItemFieldValue: { + projectV2Item: { + id: "updated-item" + } + } + }); +} + +function issueNodeIdResponse(issueId: string): Response { + return graphqlResponse({ + repository: { + issue: { + id: issueId + } + } + }); +} + +function updateIssueResponse(): Response { + return graphqlResponse({ + updateIssue: { + issue: { + id: "updated-issue" + } + } + }); +} + +function issueProjectItemResponse(options: { issueId: string; projectItemId: string }): Response { + return graphqlResponse({ + repository: { + issue: { + id: options.issueId, + projectItems: { + nodes: [ + { + id: options.projectItemId, + project: { + id: "project-id" + } + } + ] + } + } + } + }); +} + function graphqlResponse(data: unknown): Response { return new Response(JSON.stringify({ data }), { status: 200, @@ -718,3 +1064,31 @@ function readGraphqlCall(fetchMock: typeof fetch, callIndex: number): unknown { return JSON.parse(init.body); } + +function readGraphqlCalls(fetchMock: typeof fetch): unknown[] { + return vi.mocked(fetchMock).mock.calls.map((_, index) => readGraphqlCall(fetchMock, index)); +} + +function readMutationCalls(fetchMock: typeof fetch): unknown[] { + return readGraphqlCalls(fetchMock).filter((call): call is { query: string; variables: unknown } => + isGraphqlOperation(call, "mutation") + ); +} + +function isRepositoryQuery(call: unknown): boolean { + return isGraphqlOperation(call, "query Repository"); +} + +function isIssueIdQuery(call: unknown): boolean { + return isGraphqlOperation(call, "query IssueId"); +} + +function isGraphqlOperation(call: unknown, operationStart: string): call is { query: string } { + return ( + typeof call === "object" && + call !== null && + "query" in call && + typeof call.query === "string" && + call.query.trimStart().startsWith(operationStart) + ); +} diff --git a/packages/task-list/src/backends/gh-issues.ts b/packages/task-list/src/backends/gh-issues.ts index 946b8cffcf..0fa3832b98 100644 --- a/packages/task-list/src/backends/gh-issues.ts +++ b/packages/task-list/src/backends/gh-issues.ts @@ -10,7 +10,7 @@ import type { Tasks, TaskUpdate } from "../types.js"; -import { TaskNotFoundError } from "../types.js"; +import { InvalidTransitionError, TaskNotFoundError } from "../types.js"; import { createGhClient, type GhClient } from "./gh-issues-client.js"; import { applyOrder, sortTasks } from "./utils.js"; @@ -101,6 +101,67 @@ const ISSUE_QUERY = `query Issue($owner: String!, $repo: String!, $number: Int!) } }`; +const REPOSITORY_QUERY = `query Repository($owner: String!, $repo: String!) { + repository(owner: $owner, name: $repo) { + id + } +}`; + +const ISSUE_ID_QUERY = `query IssueId($owner: String!, $repo: String!, $number: Int!) { + repository(owner: $owner, name: $repo) { + issue(number: $number) { + id + } + } +}`; + +const ISSUE_PROJECT_ITEM_QUERY = `query IssueProjectItem($owner: String!, $repo: String!, $number: Int!) { + repository(owner: $owner, name: $repo) { + issue(number: $number) { + id + projectItems(first: 10) { + nodes { + id + project { id } + } + } + } + } +}`; + +const CREATE_ISSUE_MUTATION = `mutation CreateIssue($input: CreateIssueInput!) { + createIssue(input: $input) { + issue { + id + number + } + } +}`; + +const ADD_PROJECT_ITEM_MUTATION = `mutation AddProjectItem($input: AddProjectV2ItemByIdInput!) { + addProjectV2ItemById(input: $input) { + item { + id + } + } +}`; + +const UPDATE_STATUS_MUTATION = `mutation UpdateProjectItemStatus($input: UpdateProjectV2ItemFieldValueInput!) { + updateProjectV2ItemFieldValue(input: $input) { + projectV2Item { + id + } + } +}`; + +const UPDATE_ISSUE_MUTATION = `mutation UpdateIssue($input: UpdateIssueInput!) { + updateIssue(input: $input) { + issue { + id + } + } +}`; + const NOT_IMPLEMENTED = "not yet implemented"; export interface GhIssuesBackendDeps { @@ -148,6 +209,8 @@ interface GhIssuesTasksContext { client: GhClient; repoOwner: string; repoName: string; + issueIds: Map; + repositoryId?: string; } interface ProjectItemsResponse { @@ -176,6 +239,48 @@ interface IssueResponse { } | null; } +interface RepositoryResponse { + repository?: { + id?: string | null; + } | null; +} + +interface IssueIdResponse { + repository?: { + issue?: { + id?: string | null; + } | null; + } | null; +} + +interface IssueProjectItemResponse { + repository?: { + issue?: { + id?: string | null; + projectItems?: { + nodes?: ProjectItemMembership[]; + } | null; + } | null; + } | null; +} + +interface CreateIssueResponse { + createIssue?: { + issue?: { + id?: string | null; + number?: number | null; + } | null; + } | null; +} + +interface AddProjectItemResponse { + addProjectV2ItemById?: { + item?: { + id?: string | null; + } | null; + } | null; +} + interface IssueNode { __typename?: "Issue"; number: number; @@ -253,7 +358,8 @@ export async function ghIssuesBackend(deps: GhIssuesBackendDeps): Promise() }; function list(name: string): Tasks { @@ -337,14 +443,77 @@ function createTasksView( async get(id: string): Promise { return fetchIssueTask(id, name, session, context); }, - async create(_input: TaskCreate): Promise { - throw new Error(NOT_IMPLEMENTED); + /** + * GitHub Issues assigns the issue number, so TaskCreate.id is intentionally ignored. + */ + async create(input: TaskCreate): Promise { + const repositoryId = await resolveRepositoryId(context); + const created = await context.client.graphql(CREATE_ISSUE_MUTATION, { + input: { + repositoryId, + title: input.name, + body: input.description ?? "" + } + }); + const issue = created.createIssue?.issue; + const issueId = issue?.id ?? null; + const issueNumber = issue?.number ?? null; + if (issueId === null || issueNumber === null) { + throw new Error("GitHub createIssue response did not include issue id and number."); + } + + context.issueIds.set(issueNumber, issueId); + const added = await context.client.graphql( + ADD_PROJECT_ITEM_MUTATION, + { + input: { + projectId: session.projectId, + contentId: issueId + } + } + ); + const projectItemId = added.addProjectV2ItemById?.item?.id ?? null; + if (projectItemId === null) { + throw new Error("GitHub addProjectV2ItemById response did not include project item id."); + } + + await updateProjectItemStatus(projectItemId, session.stateMachine.initial, session, context); + return fetchIssueTask(String(issueNumber), name, session, context); }, - async update(_id: string, _patch: TaskUpdate): Promise { - throw new Error(NOT_IMPLEMENTED); + async update(id: string, patch: TaskUpdate): Promise { + const input: Record = {}; + + if (patch.name !== undefined) { + input.title = patch.name; + } + + if (patch.description !== undefined) { + input.body = patch.description; + } + + // metadata writes are out of scope for v1 on gh-issues. + if (Object.keys(input).length > 0) { + input.id = await resolveIssueId(id, name, context); + await context.client.graphql(UPDATE_ISSUE_MUTATION, { + input + }); + } + + return fetchIssueTask(id, name, session, context); }, - async fire(_id: string, _event: string, _opts?: TaskFireOptions): Promise { - throw new Error(NOT_IMPLEMENTED); + async fire(id: string, event: string, _opts?: TaskFireOptions): Promise { + if (!session.statusOptions.has(event)) { + throw new InvalidTransitionError({ + event, + to: event, + reason: `Unknown gh-issues Status state "${event}".` + }); + } + + const projectItemId = await resolveProjectItemId(id, name, session, context); + // opts.metadataPatch writes are out of scope for v1 on gh-issues. + await updateProjectItemStatus(projectItemId, event, session, context); + return fetchIssueTask(id, name, session, context); }, async canFire(id: string, event: string): Promise { return findEvent(session.stateMachine, id, event) !== undefined; @@ -364,6 +533,107 @@ function createTasksView( }; } +async function resolveRepositoryId(context: GhIssuesTasksContext): Promise { + if (context.repositoryId !== undefined) { + return context.repositoryId; + } + + const result = await context.client.graphql(REPOSITORY_QUERY, { + owner: context.repoOwner, + repo: context.repoName + }); + const repositoryId = result.repository?.id ?? null; + if (repositoryId === null) { + throw new Error( + `Repository ${context.repoOwner}/${context.repoName} not found or inaccessible.` + ); + } + + context.repositoryId = repositoryId; + return repositoryId; +} + +async function resolveIssueId( + id: string, + listName: string, + context: GhIssuesTasksContext +): Promise { + const issueNumber = parseIssueNumber(id, listName); + const cachedIssueId = context.issueIds.get(issueNumber); + if (cachedIssueId !== undefined) { + return cachedIssueId; + } + + const result = await context.client.graphql(ISSUE_ID_QUERY, { + owner: context.repoOwner, + repo: context.repoName, + number: issueNumber + }); + const issueId = result.repository?.issue?.id ?? null; + if (issueId === null) { + throw new TaskNotFoundError(`Task "${listName}/${id}" not found.`); + } + + context.issueIds.set(issueNumber, issueId); + return issueId; +} + +async function resolveProjectItemId( + id: string, + listName: string, + session: GhIssuesSession, + context: GhIssuesTasksContext +): Promise { + const issueNumber = parseIssueNumber(id, listName); + const result = await context.client.graphql(ISSUE_PROJECT_ITEM_QUERY, { + owner: context.repoOwner, + repo: context.repoName, + number: issueNumber + }); + const issue = result.repository?.issue ?? null; + if (issue === null) { + throw new TaskNotFoundError(`Task "${listName}/${id}" not found.`); + } + + if (issue.id !== undefined && issue.id !== null) { + context.issueIds.set(issueNumber, issue.id); + } + + const projectItem = + issue.projectItems?.nodes?.find((item) => item.project?.id === session.projectId) ?? null; + if (projectItem === null) { + throw new TaskNotFoundError(`Task "${listName}/${id}" not found.`); + } + + return projectItem.id; +} + +async function updateProjectItemStatus( + projectItemId: string, + state: string, + session: GhIssuesSession, + context: GhIssuesTasksContext +): Promise { + const optionId = session.statusOptions.get(state); + if (optionId === undefined) { + throw new InvalidTransitionError({ + to: state, + reason: `Unknown gh-issues Status state "${state}".` + }); + } + + await context.client.graphql(UPDATE_STATUS_MUTATION, { + input: { + projectId: session.projectId, + itemId: projectItemId, + fieldId: session.statusFieldId, + value: { + singleSelectOptionId: optionId + } + } + }); +} + async function fetchProjectTasks( listName: string, session: GhIssuesSession, @@ -401,10 +671,7 @@ async function fetchIssueTask( session: GhIssuesSession, context: GhIssuesTasksContext ): Promise { - const issueNumber = Number(id); - if (!Number.isInteger(issueNumber) || issueNumber < 1) { - throw new TaskNotFoundError(`Task "${listName}/${id}" not found.`); - } + const issueNumber = parseIssueNumber(id, listName); const result = await context.client.graphql(ISSUE_QUERY, { owner: context.repoOwner, @@ -431,6 +698,15 @@ async function fetchIssueTask( }); } +function parseIssueNumber(id: string, listName: string): number { + const issueNumber = Number(id); + if (!Number.isInteger(issueNumber) || issueNumber < 1) { + throw new TaskNotFoundError(`Task "${listName}/${id}" not found.`); + } + + return issueNumber; +} + function mapProjectItemToTask( item: ProjectItemNode, listName: string, From b13c418f87f2a0cfa6603111b64aa35456daf611 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 03:35:15 -0500 Subject: [PATCH 073/111] feat(task-list): support gh issue ordering operations --- .../plans/task-list-ordering-and-gh-issues.md | 6 +- .../task-list-ordering-and-gh-issues.md.lock | 2 +- .../__snapshots__/gh-issues.test.ts.snap | 160 ++++++++++ .../task-list/src/backends/gh-issues.test.ts | 279 +++++++++++++++++- packages/task-list/src/backends/gh-issues.ts | 159 +++++++++- 5 files changed, 591 insertions(+), 15 deletions(-) diff --git a/docs/plans/task-list-ordering-and-gh-issues.md b/docs/plans/task-list-ordering-and-gh-issues.md index 809acc828b..fb153b0375 100644 --- a/docs/plans/task-list-ordering-and-gh-issues.md +++ b/docs/plans/task-list-ordering-and-gh-issues.md @@ -408,7 +408,7 @@ tasks: status: implement: done test: done - commit: open + commit: done - id: gh-issues-reorder-delete title: gh-issues reorder + delete — move, reorder, delete @@ -468,8 +468,8 @@ tasks: - No `child_process.spawn`. - Tests inject `fetch`; no live API. status: - implement: open - test: open + implement: done + test: done commit: open - id: gh-issues-wire diff --git a/docs/plans/task-list-ordering-and-gh-issues.md.lock b/docs/plans/task-list-ordering-and-gh-issues.md.lock index b3e0310d44..c76ac42217 100644 --- a/docs/plans/task-list-ordering-and-gh-issues.md.lock +++ b/docs/plans/task-list-ordering-and-gh-issues.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T08:28:14.856Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T08:34:21.763Z"} \ No newline at end of file diff --git a/packages/task-list/src/backends/__snapshots__/gh-issues.test.ts.snap b/packages/task-list/src/backends/__snapshots__/gh-issues.test.ts.snap index e5227facca..fc3fba8c7c 100644 --- a/packages/task-list/src/backends/__snapshots__/gh-issues.test.ts.snap +++ b/packages/task-list/src/backends/__snapshots__/gh-issues.test.ts.snap @@ -453,6 +453,24 @@ exports[`ghIssuesBackend > create({ name, description }) issues the GitHub issue ] `; +exports[`ghIssuesBackend > delete("482") deletes the project item only 1`] = ` +[ + { + "query": "mutation DeleteProjectItem($input: DeleteProjectV2ItemInput!) { + deleteProjectV2Item(input: $input) { + deletedItemId + } +}", + "variables": { + "input": { + "itemId": "item-482", + "projectId": "project-id", + }, + }, + }, +] +`; + exports[`ghIssuesBackend > fire ignores metadataPatch and only writes the Status field 1`] = ` [ { @@ -629,6 +647,148 @@ exports[`ghIssuesBackend > keeps the project GraphQL request wire shape stable 1 } `; +exports[`ghIssuesBackend > move("482", { after: "100" }) positions after the anchor item 1`] = ` +[ + { + "query": "mutation UpdateProjectItemPosition($input: UpdateProjectV2ItemPositionInput!) { + updateProjectV2ItemPosition(input: $input) { + clientMutationId + } +}", + "variables": { + "input": { + "afterId": "item-100", + "itemId": "item-482", + "projectId": "project-id", + }, + }, + }, +] +`; + +exports[`ghIssuesBackend > move("482", { before: "100" }) positions after the anchor predecessor 1`] = ` +[ + { + "query": "mutation UpdateProjectItemPosition($input: UpdateProjectV2ItemPositionInput!) { + updateProjectV2ItemPosition(input: $input) { + clientMutationId + } +}", + "variables": { + "input": { + "afterId": "item-200", + "itemId": "item-482", + "projectId": "project-id", + }, + }, + }, +] +`; + +exports[`ghIssuesBackend > move("482", { position: "bottom" }) does not position an item after itself 1`] = ` +[ + { + "query": "mutation UpdateProjectItemPosition($input: UpdateProjectV2ItemPositionInput!) { + updateProjectV2ItemPosition(input: $input) { + clientMutationId + } +}", + "variables": { + "input": { + "afterId": "item-100", + "itemId": "item-482", + "projectId": "project-id", + }, + }, + }, +] +`; + +exports[`ghIssuesBackend > move("482", { position: "bottom" }) positions after the last item 1`] = ` +[ + { + "query": "mutation UpdateProjectItemPosition($input: UpdateProjectV2ItemPositionInput!) { + updateProjectV2ItemPosition(input: $input) { + clientMutationId + } +}", + "variables": { + "input": { + "afterId": "item-100", + "itemId": "item-482", + "projectId": "project-id", + }, + }, + }, +] +`; + +exports[`ghIssuesBackend > move("482", { position: "top" }) positions at the top 1`] = ` +[ + { + "query": "mutation UpdateProjectItemPosition($input: UpdateProjectV2ItemPositionInput!) { + updateProjectV2ItemPosition(input: $input) { + clientMutationId + } +}", + "variables": { + "input": { + "afterId": null, + "itemId": "item-482", + "projectId": "project-id", + }, + }, + }, +] +`; + +exports[`ghIssuesBackend > reorder(["100", "200", "482"]) issues sequential position mutations 1`] = ` +[ + { + "query": "mutation UpdateProjectItemPosition($input: UpdateProjectV2ItemPositionInput!) { + updateProjectV2ItemPosition(input: $input) { + clientMutationId + } +}", + "variables": { + "input": { + "afterId": null, + "itemId": "item-100", + "projectId": "project-id", + }, + }, + }, + { + "query": "mutation UpdateProjectItemPosition($input: UpdateProjectV2ItemPositionInput!) { + updateProjectV2ItemPosition(input: $input) { + clientMutationId + } +}", + "variables": { + "input": { + "afterId": "item-100", + "itemId": "item-200", + "projectId": "project-id", + }, + }, + }, + { + "query": "mutation UpdateProjectItemPosition($input: UpdateProjectV2ItemPositionInput!) { + updateProjectV2ItemPosition(input: $input) { + clientMutationId + } +}", + "variables": { + "input": { + "afterId": "item-200", + "itemId": "item-482", + "projectId": "project-id", + }, + }, + }, +] +`; + exports[`ghIssuesBackend > update uses the issue id cached by create 1`] = ` [ { diff --git a/packages/task-list/src/backends/gh-issues.test.ts b/packages/task-list/src/backends/gh-issues.test.ts index 7528233ead..fd8252e0d1 100644 --- a/packages/task-list/src/backends/gh-issues.test.ts +++ b/packages/task-list/src/backends/gh-issues.test.ts @@ -1,5 +1,10 @@ import { describe, expect, it, vi } from "vitest"; -import { InvalidTransitionError, TaskNotFoundError } from "../types.js"; +import { + AnchorNotFoundError, + InvalidTransitionError, + OrderMismatchError, + TaskNotFoundError +} from "../types.js"; import { ghIssuesBackend, type GhIssuesBackendDeps } from "./gh-issues.js"; const DEFAULT_DEPS = { @@ -738,6 +743,244 @@ describe("ghIssuesBackend", () => { ); expect(fetchMock).toHaveBeenCalledTimes(1); }); + + it('move("482", { before: "100" }) positions after the anchor predecessor', async () => { + const fetchMock = createFetchMock([ + projectResponse(), + issueProjectItemResponse({ + issueId: "issue-node-482", + projectItemId: "item-482" + }), + issueProjectItemResponse({ + issueId: "issue-node-100", + projectItemId: "item-100" + }), + itemsResponse({ + nodes: projectOrderingFixture() + }), + updateProjectItemPositionResponse(), + issueResponse({ + number: 482, + title: "Issue 482", + projectItemId: "item-482" + }) + ]); + const taskList = await ghIssuesBackend({ ...DEFAULT_DEPS, fetch: fetchMock }); + + await expect(taskList.list("octo-org/7").move("482", { before: "100" })).resolves.toMatchObject( + { + id: "482" + } + ); + expect(readMutationCalls(fetchMock)).toMatchSnapshot(); + }); + + it('move("482", { after: "100" }) positions after the anchor item', async () => { + const fetchMock = createFetchMock([ + projectResponse(), + issueProjectItemResponse({ + issueId: "issue-node-482", + projectItemId: "item-482" + }), + issueProjectItemResponse({ + issueId: "issue-node-100", + projectItemId: "item-100" + }), + updateProjectItemPositionResponse(), + issueResponse({ + number: 482, + title: "Issue 482", + projectItemId: "item-482" + }) + ]); + const taskList = await ghIssuesBackend({ ...DEFAULT_DEPS, fetch: fetchMock }); + + await expect(taskList.list("octo-org/7").move("482", { after: "100" })).resolves.toMatchObject({ + id: "482" + }); + expect(readMutationCalls(fetchMock)).toMatchSnapshot(); + }); + + it('move("482", { position: "top" }) positions at the top', async () => { + const fetchMock = createFetchMock([ + projectResponse(), + issueProjectItemResponse({ + issueId: "issue-node-482", + projectItemId: "item-482" + }), + updateProjectItemPositionResponse(), + issueResponse({ + number: 482, + title: "Issue 482", + projectItemId: "item-482" + }) + ]); + const taskList = await ghIssuesBackend({ ...DEFAULT_DEPS, fetch: fetchMock }); + + await expect( + taskList.list("octo-org/7").move("482", { position: "top" }) + ).resolves.toMatchObject({ + id: "482" + }); + expect(readMutationCalls(fetchMock)).toMatchSnapshot(); + }); + + it('move("482", { position: "bottom" }) positions after the last item', async () => { + const fetchMock = createFetchMock([ + projectResponse(), + issueProjectItemResponse({ + issueId: "issue-node-482", + projectItemId: "item-482" + }), + itemsResponse({ + nodes: [ + projectIssueItem({ id: "item-200", issue: issue({ number: 200 }) }), + projectIssueItem({ id: "item-482", issue: issue({ number: 482 }) }), + projectIssueItem({ id: "item-100", issue: issue({ number: 100 }) }) + ] + }), + updateProjectItemPositionResponse(), + issueResponse({ + number: 482, + title: "Issue 482", + projectItemId: "item-482" + }) + ]); + const taskList = await ghIssuesBackend({ ...DEFAULT_DEPS, fetch: fetchMock }); + + await expect( + taskList.list("octo-org/7").move("482", { position: "bottom" }) + ).resolves.toMatchObject({ + id: "482" + }); + expect(readMutationCalls(fetchMock)).toMatchSnapshot(); + }); + + it('move("482", { position: "bottom" }) does not position an item after itself', async () => { + const fetchMock = createFetchMock([ + projectResponse(), + issueProjectItemResponse({ + issueId: "issue-node-482", + projectItemId: "item-482" + }), + itemsResponse({ + nodes: projectOrderingFixture() + }), + updateProjectItemPositionResponse(), + issueResponse({ + number: 482, + title: "Issue 482", + projectItemId: "item-482" + }) + ]); + const taskList = await ghIssuesBackend({ ...DEFAULT_DEPS, fetch: fetchMock }); + + await expect( + taskList.list("octo-org/7").move("482", { position: "bottom" }) + ).resolves.toMatchObject({ + id: "482" + }); + expect(readMutationCalls(fetchMock)).toMatchSnapshot(); + }); + + it('move("482", { before: "missing" }) throws AnchorNotFoundError', async () => { + const fetchMock = createFetchMock([ + projectResponse(), + issueProjectItemResponse({ + issueId: "issue-node-482", + projectItemId: "item-482" + }) + ]); + const taskList = await ghIssuesBackend({ ...DEFAULT_DEPS, fetch: fetchMock }); + + await expect( + taskList.list("octo-org/7").move("482", { before: "missing" }) + ).rejects.toBeInstanceOf(AnchorNotFoundError); + }); + + it('reorder(["100", "200", "482"]) issues sequential position mutations', async () => { + const fetchMock = createFetchMock([ + projectResponse(), + itemsResponse({ + nodes: projectOrderingFixture() + }), + updateProjectItemPositionResponse(), + updateProjectItemPositionResponse(), + updateProjectItemPositionResponse(), + itemsResponse({ + nodes: [ + projectIssueItem({ id: "item-100", issue: issue({ number: 100 }) }), + projectIssueItem({ id: "item-200", issue: issue({ number: 200 }) }), + projectIssueItem({ id: "item-482", issue: issue({ number: 482 }) }) + ] + }) + ]); + const taskList = await ghIssuesBackend({ ...DEFAULT_DEPS, fetch: fetchMock }); + + await expect( + taskList.list("octo-org/7").reorder(["100", "200", "482"]).then(ids) + ).resolves.toEqual(["100", "200", "482"]); + expect(readMutationCalls(fetchMock)).toMatchSnapshot(); + }); + + it('reorder(["100", "200"]) throws OrderMismatchError for missing items', async () => { + const fetchMock = createFetchMock([ + projectResponse(), + itemsResponse({ + nodes: projectOrderingFixture() + }) + ]); + const taskList = await ghIssuesBackend({ ...DEFAULT_DEPS, fetch: fetchMock }); + + await expect(taskList.list("octo-org/7").reorder(["100", "200"])).rejects.toBeInstanceOf( + OrderMismatchError + ); + }); + + it('reorder(["100", "200", "482", "999"]) throws OrderMismatchError for extra items', async () => { + const fetchMock = createFetchMock([ + projectResponse(), + itemsResponse({ + nodes: projectOrderingFixture() + }) + ]); + const taskList = await ghIssuesBackend({ ...DEFAULT_DEPS, fetch: fetchMock }); + + await expect( + taskList.list("octo-org/7").reorder(["100", "200", "482", "999"]) + ).rejects.toBeInstanceOf(OrderMismatchError); + }); + + it('delete("482") deletes the project item only', async () => { + const fetchMock = createFetchMock([ + projectResponse(), + issueProjectItemResponse({ + issueId: "issue-node-482", + projectItemId: "item-482" + }), + deleteProjectItemResponse() + ]); + const taskList = await ghIssuesBackend({ ...DEFAULT_DEPS, fetch: fetchMock }); + + await expect(taskList.list("octo-org/7").delete("482")).resolves.toBeUndefined(); + expect(readMutationCalls(fetchMock)).toMatchSnapshot(); + }); + + it('delete("999") throws TaskNotFoundError when the issue is not in this project', async () => { + const fetchMock = createFetchMock([ + projectResponse(), + issueProjectItemResponse({ + issueId: "issue-node-999", + projectItemId: "other-item", + projectId: "other-project" + }) + ]); + const taskList = await ghIssuesBackend({ ...DEFAULT_DEPS, fetch: fetchMock }); + + await expect(taskList.list("octo-org/7").delete("999")).rejects.toBeInstanceOf( + TaskNotFoundError + ); + }); }); function ids(tasks: { id: string }[]): string[] { @@ -922,7 +1165,11 @@ function updateIssueResponse(): Response { }); } -function issueProjectItemResponse(options: { issueId: string; projectItemId: string }): Response { +function issueProjectItemResponse(options: { + issueId: string; + projectItemId: string; + projectId?: string; +}): Response { return graphqlResponse({ repository: { issue: { @@ -932,7 +1179,7 @@ function issueProjectItemResponse(options: { issueId: string; projectItemId: str { id: options.projectItemId, project: { - id: "project-id" + id: options.projectId ?? "project-id" } } ] @@ -942,6 +1189,24 @@ function issueProjectItemResponse(options: { issueId: string; projectItemId: str }); } +function updateProjectItemPositionResponse(): Response { + return graphqlResponse({ + updateProjectV2ItemPosition: { + items: { + totalCount: 3 + } + } + }); +} + +function deleteProjectItemResponse(): Response { + return graphqlResponse({ + deleteProjectV2Item: { + deletedItemId: "item-482" + } + }); +} + function graphqlResponse(data: unknown): Response { return new Response(JSON.stringify({ data }), { status: 200, @@ -1003,6 +1268,14 @@ function projectItemsFixture(): unknown[] { ]; } +function projectOrderingFixture(): unknown[] { + return [ + projectIssueItem({ id: "item-200", issue: issue({ number: 200 }) }), + projectIssueItem({ id: "item-100", issue: issue({ number: 100 }) }), + projectIssueItem({ id: "item-482", issue: issue({ number: 482 }) }) + ]; +} + function projectIssueItem(options: { id: string; issue: unknown; diff --git a/packages/task-list/src/backends/gh-issues.ts b/packages/task-list/src/backends/gh-issues.ts index 0fa3832b98..6938d3258b 100644 --- a/packages/task-list/src/backends/gh-issues.ts +++ b/packages/task-list/src/backends/gh-issues.ts @@ -10,7 +10,12 @@ import type { Tasks, TaskUpdate } from "../types.js"; -import { InvalidTransitionError, TaskNotFoundError } from "../types.js"; +import { + AnchorNotFoundError, + InvalidTransitionError, + OrderMismatchError, + TaskNotFoundError +} from "../types.js"; import { createGhClient, type GhClient } from "./gh-issues-client.js"; import { applyOrder, sortTasks } from "./utils.js"; @@ -162,7 +167,17 @@ const UPDATE_ISSUE_MUTATION = `mutation UpdateIssue($input: UpdateIssueInput!) { } }`; -const NOT_IMPLEMENTED = "not yet implemented"; +const UPDATE_PROJECT_ITEM_POSITION_MUTATION = `mutation UpdateProjectItemPosition($input: UpdateProjectV2ItemPositionInput!) { + updateProjectV2ItemPosition(input: $input) { + clientMutationId + } +}`; + +const DELETE_PROJECT_ITEM_MUTATION = `mutation DeleteProjectItem($input: DeleteProjectV2ItemInput!) { + deleteProjectV2Item(input: $input) { + deletedItemId + } +}`; export interface GhIssuesBackendDeps { repo: string; @@ -521,14 +536,63 @@ function createTasksView( async events(id: string): Promise { return eventsFromState(session.stateMachine, id); }, - async delete(_id: string): Promise { - throw new Error(NOT_IMPLEMENTED); + async delete(id: string): Promise { + const projectItemId = await resolveProjectItemId(id, name, session, context); + await context.client.graphql(DELETE_PROJECT_ITEM_MUTATION, { + input: { + projectId: session.projectId, + itemId: projectItemId + } + }); }, - async move(_id: string, _anchor: MoveAnchor): Promise { - throw new Error(NOT_IMPLEMENTED); + async move(id: string, anchor: MoveAnchor): Promise { + const projectItemId = await resolveProjectItemId(id, name, session, context); + const afterId = await resolveMoveAfterId(id, anchor, name, session, context); + + await updateProjectItemPosition(projectItemId, afterId, session, context); + + return fetchIssueTask(id, name, session, context); }, - async reorder(_ids: readonly string[]): Promise { - throw new Error(NOT_IMPLEMENTED); + async reorder(ids: readonly string[]): Promise { + const currentTasks = await fetchProjectTasks(name, session, context); + const currentIds = currentTasks.map((task) => task.id); + const currentSet = new Set(currentIds); + const inputSet = new Set(ids); + const seenInputIds = new Set(); + const missing = currentIds.filter((id) => !inputSet.has(id)); + const extra = ids.filter((id) => { + if (!currentSet.has(id)) { + return true; + } + + if (seenInputIds.has(id)) { + return true; + } + + seenInputIds.add(id); + return false; + }); + + if (missing.length > 0 || extra.length > 0) { + throw new OrderMismatchError({ missing, extra }); + } + + const itemIdsByTaskId = new Map( + currentTasks.map((task) => [task.id, projectItemIdFromTask(task)]) + ); + let afterId: string | null = null; + + for (const id of ids) { + const projectItemId = itemIdsByTaskId.get(id); + if (projectItemId === undefined) { + throw new OrderMismatchError({ missing: [id], extra: [] }); + } + + await updateProjectItemPosition(projectItemId, afterId, session, context); + afterId = projectItemId; + } + + return fetchProjectTasks(name, session, context); } }; } @@ -634,6 +698,76 @@ async function updateProjectItemStatus( }); } +async function updateProjectItemPosition( + projectItemId: string, + afterId: string | null, + session: GhIssuesSession, + context: GhIssuesTasksContext +): Promise { + await context.client.graphql(UPDATE_PROJECT_ITEM_POSITION_MUTATION, { + input: { + projectId: session.projectId, + itemId: projectItemId, + afterId + } + }); +} + +async function resolveMoveAfterId( + movingId: string, + anchor: MoveAnchor, + listName: string, + session: GhIssuesSession, + context: GhIssuesTasksContext +): Promise { + if ("position" in anchor) { + if (anchor.position === "top") { + return null; + } + + const tasks = await fetchProjectTasks(listName, session, context); + for (let index = tasks.length - 1; index >= 0; index -= 1) { + const task = tasks[index]; + if (task.id !== movingId) { + return projectItemIdFromTask(task); + } + } + + return null; + } + + const anchorId = "before" in anchor ? anchor.before : anchor.after; + let anchorProjectItemId: string; + try { + anchorProjectItemId = await resolveProjectItemId(anchorId, listName, session, context); + } catch (error) { + if (error instanceof TaskNotFoundError) { + throw new AnchorNotFoundError(anchorId); + } + + throw error; + } + + if ("after" in anchor) { + return anchorProjectItemId; + } + + const tasks = await fetchProjectTasks(listName, session, context); + const anchorIndex = tasks.findIndex((task) => task.id === anchorId); + if (anchorIndex < 0) { + throw new AnchorNotFoundError(anchorId); + } + + for (let index = anchorIndex - 1; index >= 0; index -= 1) { + const predecessor = tasks[index]; + if (predecessor.id !== movingId) { + return projectItemIdFromTask(predecessor); + } + } + + return null; +} + async function fetchProjectTasks( listName: string, session: GhIssuesSession, @@ -770,6 +904,15 @@ function mapIssueToTask(options: { }; } +function projectItemIdFromTask(task: Task): string { + const projectItemId = task.metadata.projectItemId; + if (typeof projectItemId !== "string") { + throw new Error(`Task "${task.qualifiedId}" is missing GitHub project item metadata.`); + } + + return projectItemId; +} + function parseRepo(repo: string): { owner: string; name: string } { const parts = repo.split("/"); if (parts.length !== 2 || parts[0] === "" || parts[1] === "") { From 74b27368e626e403039d48a337eee212cd2f2e9e Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 03:40:45 -0500 Subject: [PATCH 074/111] feat(task-list): wire gh issues backend --- .../plans/task-list-ordering-and-gh-issues.md | 8 +- .../task-list-ordering-and-gh-issues.md.lock | 2 +- packages/task-list/README.md | 54 ++++++++++++-- packages/task-list/src/index.ts | 15 ++-- packages/task-list/src/open-task-list.test.ts | 73 +++++++++++++++++-- packages/task-list/src/open.ts | 21 +++++- 6 files changed, 148 insertions(+), 25 deletions(-) diff --git a/docs/plans/task-list-ordering-and-gh-issues.md b/docs/plans/task-list-ordering-and-gh-issues.md index fb153b0375..571fc0d2ba 100644 --- a/docs/plans/task-list-ordering-and-gh-issues.md +++ b/docs/plans/task-list-ordering-and-gh-issues.md @@ -470,7 +470,7 @@ tasks: status: implement: done test: done - commit: open + commit: done - id: gh-issues-wire title: Wire gh-issues into open() + README @@ -512,9 +512,9 @@ tasks: IS the user's permission, scoped to the items above). - No new top-level CLI commands or SDK changes. status: - implement: open - test: open - commit: open + implement: done + test: done + commit: done --- # Context diff --git a/docs/plans/task-list-ordering-and-gh-issues.md.lock b/docs/plans/task-list-ordering-and-gh-issues.md.lock index c76ac42217..a26169375f 100644 --- a/docs/plans/task-list-ordering-and-gh-issues.md.lock +++ b/docs/plans/task-list-ordering-and-gh-issues.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T08:34:21.763Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T08:39:46.639Z"} \ No newline at end of file diff --git a/packages/task-list/README.md b/packages/task-list/README.md index 4d5f25f525..03ed69385f 100644 --- a/packages/task-list/README.md +++ b/packages/task-list/README.md @@ -4,10 +4,13 @@ Multi-list task manager with pluggable storage backends. ## Backends -`@poe-code/task-list` exposes one API over two backends: +`@poe-code/task-list` exposes one API over these backends: -- `markdown-dir`: one Markdown file per task, organized into subdirectories per list -- `yaml-file`: one YAML document with a top-level `lists:` mapping +| Backend | Storage | +| --- | --- | +| `markdown-dir` | One Markdown file per task, organized into subdirectories per list. | +| `yaml-file` | One YAML document with a top-level `lists:` mapping. | +| `gh-issues` | GitHub Issues in one repository, ordered and state-tracked through a GitHub Project v2 Status field. | The task lifecycle is `draft -> planned -> in-progress -> done -> archived`. `archived` is terminal. @@ -47,7 +50,7 @@ Pass a custom machine with `openTaskList({ stateMachine })`. If omitted, the pac | Option | Type | Default | Behavior | | --- | --- | --- | --- | -| `type` | `"markdown-dir" \| "yaml-file"` | required | Selects the backend implementation. | +| `type` | `"markdown-dir" \| "yaml-file" \| "gh-issues"` | required | Selects the backend implementation. | | `path` | `string` | required | Root directory for `markdown-dir` or YAML file path for `yaml-file`. | | `defaults` | `TaskDefaults` | `{ metadata: {} }` | Seeds omitted metadata on new tasks only. New tasks always start at the configured state machine's initial state. | | `create` | `boolean` | `false` | Creates missing storage for the selected backend when enabled. | @@ -58,7 +61,9 @@ Pass a custom machine with `openTaskList({ stateMachine })`. If omitted, the pac ## Env vars -None. +| Env var | Behavior | +| --- | --- | +| `GH_HOST` | Defers to gh CLI's host configuration; set GH_HOST to override. | ## Usage @@ -105,6 +110,36 @@ await planning.fire("review-release", "plan"); await planning.fire("review-release", "start"); ``` +### `gh-issues` + +```ts +import { openTaskList } from "@poe-code/task-list"; + +const taskList = await openTaskList({ + type: "gh-issues", + repo: "octo-org/octo-repo", + project: { + owner: "octo-org", + number: 7 + } +}); + +const project = taskList.list("octo-org/7"); + +await taskList.lists(); // ["octo-org/7"] + +const created = await project.create({ + id: "local-id-is-ignored", + name: "Review release checklist" +}); + +await project.fire(created.id, "In Progress"); +await project.move(created.id, { position: "top" }); +await project.move(created.id, { after: "42" }); +``` + +`gh-issues` exposes one list named `${project.owner}/${project.number}`. `create()` ignores `TaskCreate.id` because GitHub assigns issue numbers. `fire(state)` writes the Project v2 `Status` field to the matching single-select option. `move()` reorders project items. + ## Notes The package never overwrites existing task files or store files. `defaults.metadata` is applied only when creating new tasks and does not retroactively update existing tasks. @@ -112,3 +147,12 @@ The package never overwrites existing task files or store files. `defaults.metad Task state changes are event-driven: use `fire(id, event)` to move between states, `canFire(id, event)` to check whether an event is currently legal, and `events(id)` to list the currently legal event names. There is no `transition()` API. `create()` always starts new tasks at `stateMachine.initial`. `update()` cannot change `state`; use `fire()` instead. + +### `gh-issues` limitations + +- The state machine is fetched at open and frozen for the session; re-open to refresh project Status options. +- `archived` is not supported and returns an empty result. +- `update()` does not write labels, assignees, or milestone in v1. +- `moveBetweenLists()` is unsupported on `gh-issues`. +- `id` on `TaskCreate` is ignored on this backend. +- `gh auth token` must be available, or pass `auth: { token }`. diff --git a/packages/task-list/src/index.ts b/packages/task-list/src/index.ts index 704cc29622..f24be3b82e 100644 --- a/packages/task-list/src/index.ts +++ b/packages/task-list/src/index.ts @@ -31,13 +31,10 @@ export { type Tasks, type TaskUpdate } from "./types.js"; -export { - createGhClient, - resolveAuth, - resolveEndpoint, - type GhClient, - type GhClientOptions, - type ResolveAuthOptions, - type ResolveEndpointOptions +export type { + GhClient, + GhClientOptions, + ResolveAuthOptions, + ResolveEndpointOptions } from "./backends/gh-issues-client.js"; -export { ghIssuesBackend, type GhIssuesBackendDeps } from "./backends/gh-issues.js"; +export type { GhIssuesBackendDeps } from "./backends/gh-issues.js"; diff --git a/packages/task-list/src/open-task-list.test.ts b/packages/task-list/src/open-task-list.test.ts index 22dce112b5..c962ec1a97 100644 --- a/packages/task-list/src/open-task-list.test.ts +++ b/packages/task-list/src/open-task-list.test.ts @@ -113,17 +113,74 @@ describe("openTaskList", () => { ).rejects.toThrow('Unknown task list backend type "sqlite".'); }); - it('throws the placeholder error for "gh-issues"', async () => { - await expect( - openTaskList({ + it('routes "gh-issues" through auth and endpoint resolution to the GitHub Issues backend', async () => { + const previousGhHost = process.env.GH_HOST; + process.env.GH_HOST = "github.example.test"; + const fetchMock: typeof fetch = vi.fn(async () => + createJsonResponse({ + data: { + organization: { + projectV2: { + id: "project-1", + title: "Roadmap", + field: { + id: "status-field", + options: [{ id: "status-todo", name: "Todo" }] + } + } + } + } + }) + ); + + try { + const taskList = await openTaskList({ type: "gh-issues", repo: "owner/name", project: { owner: "owner", number: 1 + }, + auth: { + token: "explicit-token" + }, + fetch: fetchMock + }); + + expect(await taskList.lists()).toEqual(["owner/1"]); + expect(taskList.list("owner/1").stateMachine).toEqual({ + initial: "Todo", + states: ["Todo"], + events: { + Todo: { from: "*", to: "Todo" } } - }) - ).rejects.toThrow("gh-issues backend not yet implemented"); + }); + expect(fetchMock).toHaveBeenCalledWith("https://github.example.test/api/graphql", { + method: "POST", + headers: { + Authorization: "Bearer explicit-token", + "Content-Type": "application/json", + "User-Agent": "poe-code-task-list/0.0.1" + }, + body: expect.any(String) + }); + const request = fetchMock.mock.calls[0]?.[1]; + const body = JSON.parse(String(request?.body)) as { + query: string; + variables: Record; + }; + expect(body.query).toContain("organization(login: $owner)"); + expect(body.variables).toEqual({ + owner: "owner", + number: 1 + }); + } finally { + if (previousGhHost === undefined) { + delete process.env.GH_HOST; + } else { + process.env.GH_HOST = previousGhHost; + } + } }); it("normalizes missing defaults", async () => { @@ -337,3 +394,9 @@ describe("openTaskList", () => { }); } }); + +function createJsonResponse(body: unknown): Response { + return new Response(JSON.stringify(body), { + headers: { "Content-Type": "application/json" } + }); +} diff --git a/packages/task-list/src/open.ts b/packages/task-list/src/open.ts index 23907117ac..d0e9ecb540 100644 --- a/packages/task-list/src/open.ts +++ b/packages/task-list/src/open.ts @@ -1,4 +1,6 @@ import * as fsPromises from "node:fs/promises"; +import { ghIssuesBackend } from "./backends/gh-issues.js"; +import { resolveAuth, resolveEndpoint } from "./backends/gh-issues-client.js"; import { markdownDirBackend } from "./backends/markdown-dir.js"; import { yamlFileBackend } from "./backends/yaml-file.js"; import { validateMachine } from "./state-machine.js"; @@ -6,6 +8,7 @@ import { resolveStateMachine } from "./state.js"; import type { BackendFactory, BackendDeps, + OpenGhIssuesOptions, OpenMarkdownDirOptions, OpenTaskListOptions, OpenYamlFileOptions, @@ -33,7 +36,7 @@ export async function openTaskList(options: OpenTaskListOptions): Promise { return factory(deps); } + +async function openGhIssuesBackend(options: OpenGhIssuesOptions): Promise { + const token = await resolveAuth({ explicitToken: options.auth?.token }); + const endpoint = resolveEndpoint(); + + return ghIssuesBackend({ + repo: options.repo, + project: options.project, + defaults: { + metadata: { ...(options.defaults?.metadata ?? {}) } + }, + token, + endpoint, + fetch: options.fetch + }); +} From d0665530c13529085a006a40485d3dab3baeb8eb Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 03:41:45 -0500 Subject: [PATCH 075/111] docs: archive completed task-list plan --- docs/plans/{ => archive}/task-list-ordering-and-gh-issues.md | 0 docs/plans/task-list-ordering-and-gh-issues.md.lock | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) rename docs/plans/{ => archive}/task-list-ordering-and-gh-issues.md (100%) diff --git a/docs/plans/task-list-ordering-and-gh-issues.md b/docs/plans/archive/task-list-ordering-and-gh-issues.md similarity index 100% rename from docs/plans/task-list-ordering-and-gh-issues.md rename to docs/plans/archive/task-list-ordering-and-gh-issues.md diff --git a/docs/plans/task-list-ordering-and-gh-issues.md.lock b/docs/plans/task-list-ordering-and-gh-issues.md.lock index a26169375f..0e32930f34 100644 --- a/docs/plans/task-list-ordering-and-gh-issues.md.lock +++ b/docs/plans/task-list-ordering-and-gh-issues.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T08:39:46.639Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T08:41:04.559Z"} \ No newline at end of file From ca914f7735d9c8ca857b9922b605959bef1e4391 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 03:47:54 -0500 Subject: [PATCH 076/111] fix: wrap help formatter columns --- .../task-list-ordering-and-gh-issues.md.lock | 1 - .../toolcraft-help-and-result-rendering.md | 6 +- ...oolcraft-help-and-result-rendering.md.lock | 1 + .../src/components/help-formatter.test.ts | 127 ++++++++++++++++ .../src/components/help-formatter.ts | 139 +++++++++++++++++- .../design-system/src/components/index.ts | 4 +- packages/design-system/src/index.ts | 4 +- .../__snapshots__/runtime-help.test.ts.snap | 25 ++-- 8 files changed, 280 insertions(+), 27 deletions(-) delete mode 100644 docs/plans/task-list-ordering-and-gh-issues.md.lock create mode 100644 docs/plans/toolcraft-help-and-result-rendering.md.lock create mode 100644 packages/design-system/src/components/help-formatter.test.ts diff --git a/docs/plans/task-list-ordering-and-gh-issues.md.lock b/docs/plans/task-list-ordering-and-gh-issues.md.lock deleted file mode 100644 index 0e32930f34..0000000000 --- a/docs/plans/task-list-ordering-and-gh-issues.md.lock +++ /dev/null @@ -1 +0,0 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T08:41:04.559Z"} \ No newline at end of file diff --git a/docs/plans/toolcraft-help-and-result-rendering.md b/docs/plans/toolcraft-help-and-result-rendering.md index 1ad84447ad..6c145071e0 100644 --- a/docs/plans/toolcraft-help-and-result-rendering.md +++ b/docs/plans/toolcraft-help-and-result-rendering.md @@ -58,9 +58,9 @@ tasks: No filesystem in tests; pure string assertions. status: - implement: open - test: open - commit: open + implement: done + test: done + commit: done - id: design-system-section-header title: Add text.sectionHeader to design-system diff --git a/docs/plans/toolcraft-help-and-result-rendering.md.lock b/docs/plans/toolcraft-help-and-result-rendering.md.lock new file mode 100644 index 0000000000..9621af88b6 --- /dev/null +++ b/docs/plans/toolcraft-help-and-result-rendering.md.lock @@ -0,0 +1 @@ +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T08:46:14.930Z"} \ No newline at end of file diff --git a/packages/design-system/src/components/help-formatter.test.ts b/packages/design-system/src/components/help-formatter.test.ts new file mode 100644 index 0000000000..25fdc2e13b --- /dev/null +++ b/packages/design-system/src/components/help-formatter.test.ts @@ -0,0 +1,127 @@ +import { describe, expect, it } from "vitest"; +import { withOutputFormat } from "../internal/output-format.js"; +import { + formatColumns, + formatCommandList, + formatOptionList +} from "./help-formatter.js"; + +describe("formatColumns", () => { + it("aligns left to min(maxLen + gap, maxLeftWidth)", () => { + const result = formatColumns({ + rows: [ + { left: "alpha", right: "first" }, + { left: "bravo1", right: "second" } + ], + totalWidth: 80, + minLeftWidth: 1, + maxLeftWidth: 8, + gap: 3, + indent: 2 + }); + + expect(result).toBe(" alpha first\n bravo1 second"); + }); + + it("aligns left to minLeftWidth when content plus gap is smaller", () => { + const result = formatColumns({ + rows: [{ left: "a", right: "first" }], + totalWidth: 80, + minLeftWidth: 8, + maxLeftWidth: 20, + gap: 2, + indent: 0 + }); + + expect(result).toBe("a first"); + }); + + it("wraps right at totalWidth - leftWidth - indent", () => { + const result = formatColumns({ + rows: [{ left: "cmd", right: "one two three four five" }], + totalWidth: 25, + minLeftWidth: 1, + maxLeftWidth: 20, + gap: 1, + indent: 1 + }); + + expect(result).toBe(" cmd one two three four\n five"); + }); + + it("keeps long unbreakable tokens intact when they exceed right width", () => { + const result = formatColumns({ + rows: [{ left: "cmd", right: "short supercalifragilisticexpialidocious tail" }], + totalWidth: 18, + minLeftWidth: 1, + maxLeftWidth: 20, + gap: 1, + indent: 0 + }); + + expect(result).toBe("cmd short\n supercalifragilisticexpialidocious\n tail"); + }); + + it("preserves continuation indent", () => { + const result = formatColumns({ + rows: [{ left: "left", right: "alpha beta gamma delta" }], + totalWidth: 18, + minLeftWidth: 1, + maxLeftWidth: 20, + gap: 2, + indent: 3 + }); + + expect(result.split("\n")[1]?.startsWith(" ".repeat(9))).toBe(true); + }); + + it("does not widen the column for ANSI-styled left tokens", () => { + const result = formatColumns({ + rows: [ + { left: "\u001b[31mred\u001b[39m", right: "colored" }, + { left: "blue", right: "plain" } + ], + totalWidth: 80, + minLeftWidth: 1, + maxLeftWidth: 20, + gap: 2, + indent: 0 + }); + + expect(result).toBe("\u001b[31mred\u001b[39m colored\nblue plain"); + }); + + it("returns an empty string for an empty rows array", () => { + expect(formatColumns({ rows: [] })).toBe(""); + }); +}); + +describe("help formatter lists", () => { + it("formats command lists through columns", () => { + const result = withOutputFormat("markdown", () => + formatCommandList([ + { name: "configure", description: "Set up provider credentials" }, + { name: "run", description: "Run an agent" } + ]) + ); + + expect(result).toMatchInlineSnapshot(` + " \`configure\` Set up provider credentials + \`run\` Run an agent" + `); + }); + + it("formats option lists through columns", () => { + const result = withOutputFormat("markdown", () => + formatOptionList([ + { flags: "--agent ", description: "Agent to configure" }, + { flags: "--yes", description: "Accept defaults" } + ]) + ); + + expect(result).toMatchInlineSnapshot(` + " \`--agent \` Agent to configure + \`--yes\` Accept defaults" + `); + }); +}); diff --git a/packages/design-system/src/components/help-formatter.ts b/packages/design-system/src/components/help-formatter.ts index d27abdb27e..7d10d5fcf6 100644 --- a/packages/design-system/src/components/help-formatter.ts +++ b/packages/design-system/src/components/help-formatter.ts @@ -1,5 +1,4 @@ import { text } from "./text.js"; -import { widths } from "../tokens/widths.js"; export interface CommandInfo { name: string; @@ -11,9 +10,123 @@ export interface OptionInfo { description: string; } +export interface FormatColumnsOptions { + rows: Array<{ left: string; right: string }>; + totalWidth?: number; + minLeftWidth?: number; + maxLeftWidth?: number; + gap?: number; + indent?: number; +} + +function stripAnsi(value: string): string { + let output = ""; + for (let index = 0; index < value.length; index += 1) + if (value[index] === "\u001b" && value[index + 1] === "[") + while (index < value.length && value[index] !== "m") index += 1; + else output += value[index]; + return output; +} + +function visibleWidth(value: string): number { + return stripAnsi(value).length; +} + +function clamp(value: number, min: number, max: number): number { + return Math.min(Math.max(value, min), max); +} + +function padEndVisible(value: string, width: number): string { + return value + " ".repeat(Math.max(0, width - visibleWidth(value))); +} + +function isWhitespace(char: string | undefined): boolean { + return char === " " || char === "\n" || char === "\t" || char === "\r"; +} + +function splitWords(value: string): string[] { + const words: string[] = []; + let word = ""; + + for (const char of value) { + if (isWhitespace(char)) { + if (word) { + words.push(word); + word = ""; + } + continue; + } + word += char; + } + + if (word) { + words.push(word); + } + + return words; +} + +function wrapWords(value: string, width: number): string[] { + const words = splitWords(value); + if (words.length === 0) { + return [""]; + } + + const lines: string[] = []; + let line = ""; + + for (const word of words) { + if (!line) { + line = word; + continue; + } + + if (visibleWidth(line) + 1 + visibleWidth(word) <= width) { + line += ` ${word}`; + continue; + } + + lines.push(line); + line = word; + } + + lines.push(line); + return lines; +} + +export function formatColumns(opts: FormatColumnsOptions): string { + const { rows } = opts; + if (rows.length === 0) { + return ""; + } + + const totalWidth = opts.totalWidth ?? process.stdout.columns ?? 100; + const minLeftWidth = opts.minLeftWidth ?? 12; + const maxLeftWidth = opts.maxLeftWidth ?? 32; + const gap = opts.gap ?? 3; + const indent = opts.indent ?? 2; + const maxLeftContentWidth = Math.max(...rows.map((row) => visibleWidth(row.left))); + const leftWidth = clamp(maxLeftContentWidth + gap, minLeftWidth, maxLeftWidth); + const rightWidth = Math.max(20, totalWidth - leftWidth - indent); + const firstIndent = " ".repeat(indent); + const continuationIndent = " ".repeat(indent + leftWidth); + + return rows + .flatMap((row) => { + const rightLines = wrapWords(row.right, rightWidth); + const firstLine = `${firstIndent}${padEndVisible(row.left, leftWidth)}${rightLines[0]}`; + const continuationLines = rightLines + .slice(1) + .map((line) => `${continuationIndent}${line}`); + return [firstLine, ...continuationLines]; + }) + .join("\n"); +} + export function formatCommand(name: string, description: string): string { - const paddedName = name.padEnd(widths.helpColumn); - return ` ${text.command(paddedName)} ${description}`; + return formatColumns({ + rows: [{ left: text.command(name), right: description }] + }); } export function formatUsage(command: string, args?: string): string { @@ -22,19 +135,31 @@ export function formatUsage(command: string, args?: string): string { } export function formatOption(flags: string, description: string): string { - const paddedFlags = flags.padEnd(widths.helpColumn); - return ` ${text.option(paddedFlags)} ${description}`; + return formatColumns({ + rows: [{ left: text.option(flags), right: description }] + }); } export function formatCommandList(commands: CommandInfo[]): string { - return commands.map((cmd) => formatCommand(cmd.name, cmd.description)).join("\n"); + return formatColumns({ + rows: commands.map((cmd) => ({ + left: text.command(cmd.name), + right: cmd.description + })) + }); } export function formatOptionList(options: OptionInfo[]): string { - return options.map((opt) => formatOption(opt.flags, opt.description)).join("\n"); + return formatColumns({ + rows: options.map((opt) => ({ + left: text.option(opt.flags), + right: opt.description + })) + }); } export const helpFormatter = { + formatColumns, formatCommand, formatUsage, formatOption, diff --git a/packages/design-system/src/components/index.ts b/packages/design-system/src/components/index.ts index 91e0e9aed0..3b5d79bb92 100644 --- a/packages/design-system/src/components/index.ts +++ b/packages/design-system/src/components/index.ts @@ -2,8 +2,8 @@ export { text } from "./text.js"; export { symbols } from "./symbols.js"; export { createLogger, logger } from "./logger.js"; export type { LoggerOutput } from "./logger.js"; -export { helpFormatter, formatCommand, formatUsage, formatOption, formatCommandList, formatOptionList } from "./help-formatter.js"; -export type { CommandInfo, OptionInfo } from "./help-formatter.js"; +export { helpFormatter, formatColumns, formatCommand, formatUsage, formatOption, formatCommandList, formatOptionList } from "./help-formatter.js"; +export type { CommandInfo, OptionInfo, FormatColumnsOptions } from "./help-formatter.js"; export { formatCommandNotFound } from "./command-errors.js"; export { formatCommandNotFoundPanel } from "./command-errors.js"; export { renderTable } from "./table.js"; diff --git a/packages/design-system/src/index.ts b/packages/design-system/src/index.ts index 34f0e722a4..a449808dc9 100644 --- a/packages/design-system/src/index.ts +++ b/packages/design-system/src/index.ts @@ -11,8 +11,8 @@ export { text } from "./components/text.js"; export { symbols } from "./components/symbols.js"; export { createLogger, logger } from "./components/logger.js"; export type { LoggerOutput } from "./components/logger.js"; -export { helpFormatter, formatCommand, formatUsage, formatOption, formatCommandList, formatOptionList } from "./components/help-formatter.js"; -export type { CommandInfo, OptionInfo } from "./components/help-formatter.js"; +export { helpFormatter, formatColumns, formatCommand, formatUsage, formatOption, formatCommandList, formatOptionList } from "./components/help-formatter.js"; +export type { CommandInfo, OptionInfo, FormatColumnsOptions } from "./components/help-formatter.js"; export { formatCommandNotFound } from "./components/command-errors.js"; export { formatCommandNotFoundPanel } from "./components/command-errors.js"; export { renderTable } from "./components/table.js"; diff --git a/src/cli/commands/__snapshots__/runtime-help.test.ts.snap b/src/cli/commands/__snapshots__/runtime-help.test.ts.snap index 4235f95832..326884958f 100644 --- a/src/cli/commands/__snapshots__/runtime-help.test.ts.snap +++ b/src/cli/commands/__snapshots__/runtime-help.test.ts.snap @@ -101,19 +101,20 @@ Usage: poe-code superintendent run [options] [doc] Run the full superintendent loop. Options: - [doc] Path to the superintendent markdown document - --agent Override the builder agent for this run. Precedence: --agent > plan frontmatter builder.agent. - --runtime Override runtime backend: host, docker, or e2b - --runtime-image Override Docker runtime image - --runtime-template Override E2B runtime template id - --detach [value] Run as a detached runtime job - --mount-poe-code [value] Mount the local poe-code checkout into the runtime - --runner-sync Override runner workspace sync: both, upload, or none - --tui [value] Show a live dashboard while Superintendent is running + [doc] Path to the superintendent markdown document + --agent Override the builder agent for this run. Precedence: --agent > plan + frontmatter builder.agent. + --runtime Override runtime backend: host, docker, or e2b + --runtime-image Override Docker runtime image + --runtime-template Override E2B runtime template id + --detach [value] Run as a detached runtime job + --mount-poe-code [value] Mount the local poe-code checkout into the runtime + --runner-sync Override runner workspace sync: both, upload, or none + --tui [value] Show a live dashboard while Superintendent is running Global options: - --yes Accept defaults, skip prompts - --output Output format (rich, md, json) - -h, --help Show help + --yes Accept defaults, skip prompts + --output Output format (rich, md, json) + -h, --help Show help " `; From ff067b2ede3e2b289b93f7ad1b27c4894d30bd86 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 03:53:23 -0500 Subject: [PATCH 077/111] feat(design-system): add section header text helper --- docs/plans/toolcraft-help-and-result-rendering.md | 4 ++-- .../plans/toolcraft-help-and-result-rendering.md.lock | 2 +- .../design-system/src/components/components.test.ts | 11 +++++++++++ packages/design-system/src/components/text.ts | 6 ++++++ packages/design-system/src/index.test.ts | 5 +++++ 5 files changed, 25 insertions(+), 3 deletions(-) diff --git a/docs/plans/toolcraft-help-and-result-rendering.md b/docs/plans/toolcraft-help-and-result-rendering.md index 6c145071e0..32ccb2a3bc 100644 --- a/docs/plans/toolcraft-help-and-result-rendering.md +++ b/docs/plans/toolcraft-help-and-result-rendering.md @@ -91,8 +91,8 @@ tasks: - markdown mode: returns `## Title` - JSON mode: returns input unchanged status: - implement: open - test: open + implement: done + test: done commit: open - id: design-system-help-formatter-plain diff --git a/docs/plans/toolcraft-help-and-result-rendering.md.lock b/docs/plans/toolcraft-help-and-result-rendering.md.lock index 9621af88b6..332b437872 100644 --- a/docs/plans/toolcraft-help-and-result-rendering.md.lock +++ b/docs/plans/toolcraft-help-and-result-rendering.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T08:46:14.930Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T08:52:20.010Z"} \ No newline at end of file diff --git a/packages/design-system/src/components/components.test.ts b/packages/design-system/src/components/components.test.ts index f676fe4622..12b71bae53 100644 --- a/packages/design-system/src/components/components.test.ts +++ b/packages/design-system/src/components/components.test.ts @@ -346,6 +346,7 @@ describe("text", () => { expect(text.intro("Intro")).toBe("**Intro**"); expect(text.heading("Heading")).toBe("## Heading"); expect(text.section("Section")).toBe("**Section**"); + expect(text.sectionHeader("Title")).toBe("## Title"); expect(text.command("poe-code")).toBe("`poe-code`"); expect(text.argument("provider")).toBe(""); expect(text.option("--help")).toBe("`--help`"); @@ -365,6 +366,7 @@ describe("text", () => { expect(text.intro("Intro")).toBe("Intro"); expect(text.heading("Heading")).toBe("Heading"); expect(text.section("Section")).toBe("Section"); + expect(text.sectionHeader("Title")).toBe("Title"); expect(text.command("poe-code")).toBe("poe-code"); expect(text.argument("provider")).toBe("provider"); expect(text.option("--help")).toBe("--help"); @@ -387,6 +389,15 @@ describe("text", () => { expect(result).not.toBe("my-file.md — codex · ×3"); expect(result).not.toBe("my-file.md codex · ×3"); }); + + it("renders terminal section headers as bold uppercase without a colon", () => { + const result = withOutputFormat("terminal", () => + text.sectionHeader("Title") + ); + + expect(result).toBe(chalk.bold("TITLE")); + expect(result).not.toContain(":"); + }); }); describe("text.selectLabel", () => { diff --git a/packages/design-system/src/components/text.ts b/packages/design-system/src/components/text.ts index 8dc157853c..5299faa615 100644 --- a/packages/design-system/src/components/text.ts +++ b/packages/design-system/src/components/text.ts @@ -22,6 +22,12 @@ export const text = { if (format === "markdown") return `**${content}**`; return typography.bold(content); }, + sectionHeader(content: string): string { + const format = resolveOutputFormat(); + if (format === "json") return content; + if (format === "markdown") return `## ${content}`; + return typography.bold(content.toUpperCase()); + }, command(content: string): string { const format = resolveOutputFormat(); if (format === "json") return content; diff --git a/packages/design-system/src/index.test.ts b/packages/design-system/src/index.test.ts index 5fb27315c4..8409b5992b 100644 --- a/packages/design-system/src/index.test.ts +++ b/packages/design-system/src/index.test.ts @@ -5,6 +5,7 @@ import { parse, render, renderMarkdown, + text, type Dashboard, type DashboardOptions, type MdNode, @@ -46,6 +47,10 @@ describe("design-system root exports", () => { expect(dashboard.createDashboard).toBe(createDashboard); }); + it("re-exports text helpers from the root barrel", () => { + expect(text.sectionHeader("Title")).toBeTypeOf("string"); + }); + it("exposes the same dashboard factory from the dashboard barrel", () => { expect(createDashboardFromDashboardBarrel).toBe(createDashboard); expect(defaultHints()).toEqual([ From 49fcab43c26c3004a34b3839d5dc1df70c1f9a05 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 03:58:37 -0500 Subject: [PATCH 078/111] feat(design-system): add plain help formatter --- .../toolcraft-help-and-result-rendering.md | 8 +- ...oolcraft-help-and-result-rendering.md.lock | 2 +- .../components/help-formatter-plain.test.ts | 93 +++++++++++ .../src/components/help-formatter-plain.ts | 150 ++++++++++++++++++ packages/design-system/src/index.ts | 1 + 5 files changed, 249 insertions(+), 5 deletions(-) create mode 100644 packages/design-system/src/components/help-formatter-plain.test.ts create mode 100644 packages/design-system/src/components/help-formatter-plain.ts diff --git a/docs/plans/toolcraft-help-and-result-rendering.md b/docs/plans/toolcraft-help-and-result-rendering.md index 32ccb2a3bc..f53337fd3e 100644 --- a/docs/plans/toolcraft-help-and-result-rendering.md +++ b/docs/plans/toolcraft-help-and-result-rendering.md @@ -93,7 +93,7 @@ tasks: status: implement: done test: done - commit: open + commit: done - id: design-system-help-formatter-plain title: Plain-text fallback module for help-formatter @@ -129,9 +129,9 @@ tasks: (reuse a couple of cases from help-formatter.test.ts to confirm parity) status: - implement: open - test: open - commit: open + implement: done + test: done + commit: done - id: toolcraft-help-global-options-gate title: Gate global option rows in toolcraft help diff --git a/docs/plans/toolcraft-help-and-result-rendering.md.lock b/docs/plans/toolcraft-help-and-result-rendering.md.lock index 332b437872..6028c63506 100644 --- a/docs/plans/toolcraft-help-and-result-rendering.md.lock +++ b/docs/plans/toolcraft-help-and-result-rendering.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T08:52:20.010Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T08:57:44.328Z"} \ No newline at end of file diff --git a/packages/design-system/src/components/help-formatter-plain.test.ts b/packages/design-system/src/components/help-formatter-plain.test.ts new file mode 100644 index 0000000000..416a681cd7 --- /dev/null +++ b/packages/design-system/src/components/help-formatter-plain.test.ts @@ -0,0 +1,93 @@ +import { describe, expect, it } from "vitest"; +import { + formatColumns, + formatCommandList, + formatOptionList +} from "./help-formatter-plain.js"; + +const ansiEscapePattern = /\x1b\[[0-9;]*m/; + +describe("plain help formatter", () => { + it("does not emit ANSI escape codes", () => { + const result = formatColumns({ + rows: [ + { left: "\u001b[31mred\u001b[39m", right: "colored\u001b[2K" }, + { left: "blue", right: "\u001b[1mplain\u001b[22m" } + ], + totalWidth: 80, + minLeftWidth: 1, + maxLeftWidth: 20, + gap: 2, + indent: 0 + }); + + expect(ansiEscapePattern.test(result)).toBe(false); + expect(result).not.toContain("\u001b"); + expect(result).toBe("red colored\nblue plain"); + }); + + it("converts non-ASCII input without changing formatter width accounting", () => { + const result = formatColumns({ + rows: [ + { left: "café", right: "ready" }, + { left: "globe 🌍", right: "wide" } + ], + totalWidth: 80, + minLeftWidth: 1, + maxLeftWidth: 20, + gap: 2, + indent: 0 + }); + + expect(result).toBe("caf? ready\nglobe ?? wide"); + }); + + it("aligns left to min(maxLen + gap, maxLeftWidth)", () => { + const result = formatColumns({ + rows: [ + { left: "alpha", right: "first" }, + { left: "bravo1", right: "second" } + ], + totalWidth: 80, + minLeftWidth: 1, + maxLeftWidth: 8, + gap: 3, + indent: 2 + }); + + expect(result).toBe(" alpha first\n bravo1 second"); + }); + + it("wraps right at totalWidth - leftWidth - indent", () => { + const result = formatColumns({ + rows: [{ left: "cmd", right: "one two three four five" }], + totalWidth: 25, + minLeftWidth: 1, + maxLeftWidth: 20, + gap: 1, + indent: 1 + }); + + expect(result).toBe(" cmd one two three four\n five"); + }); + + it("formats command lists without text styling", () => { + const result = formatCommandList([ + { name: "configure", description: "Set up provider credentials" }, + { name: "run", description: "Run an agent" } + ]); + + expect(ansiEscapePattern.test(result)).toBe(false); + expect(result).toBe(" configure Set up provider credentials\n run Run an agent"); + }); + + it("formats option lists without text styling", () => { + const result = formatOptionList([ + { flags: "--agent ", description: "Agent to configure" }, + { flags: "--yes", description: "Accept defaults" } + ]); + + expect(ansiEscapePattern.test(result)).toBe(false); + expect(result).toBe(" --agent Agent to configure\n --yes Accept defaults"); + }); +}); diff --git a/packages/design-system/src/components/help-formatter-plain.ts b/packages/design-system/src/components/help-formatter-plain.ts new file mode 100644 index 0000000000..fdaab93bd4 --- /dev/null +++ b/packages/design-system/src/components/help-formatter-plain.ts @@ -0,0 +1,150 @@ +import type { + CommandInfo, + FormatColumnsOptions, + OptionInfo +} from "./help-formatter.js"; + +function stripAnsi(value: string): string { + let output = ""; + for (let index = 0; index < value.length; index += 1) { + if (value[index] === "\u001b") { + if (value[index + 1] === "[") { + index += 2; + while (index < value.length) { + const code = value.charCodeAt(index); + if (code >= 0x40 && code <= 0x7e) { + break; + } + index += 1; + } + } + continue; + } + + output += value[index]; + } + return output; +} + +function toAscii(value: string): string { + let output = ""; + const stripped = stripAnsi(value); + for (let index = 0; index < stripped.length; index += 1) { + const code = stripped.charCodeAt(index); + output += code <= 0x7f ? stripped[index] : "?"; + } + return output; +} + +function clamp(value: number, min: number, max: number): number { + return Math.min(Math.max(value, min), max); +} + +function padEndVisible(value: string, width: number): string { + return value + " ".repeat(Math.max(0, width - value.length)); +} + +function isWhitespace(char: string | undefined): boolean { + return char === " " || char === "\n" || char === "\t" || char === "\r"; +} + +function splitWords(value: string): string[] { + const words: string[] = []; + let word = ""; + + for (const char of value) { + if (isWhitespace(char)) { + if (word) { + words.push(word); + word = ""; + } + continue; + } + word += char; + } + + if (word) { + words.push(word); + } + + return words; +} + +function wrapWords(value: string, width: number): string[] { + const words = splitWords(value); + if (words.length === 0) { + return [""]; + } + + const lines: string[] = []; + let line = ""; + + for (const word of words) { + if (!line) { + line = word; + continue; + } + + if (line.length + 1 + word.length <= width) { + line += ` ${word}`; + continue; + } + + lines.push(line); + line = word; + } + + lines.push(line); + return lines; +} + +export function formatColumns(opts: FormatColumnsOptions): string { + const rows = opts.rows.map((row) => ({ + left: toAscii(row.left), + right: toAscii(row.right) + })); + + if (rows.length === 0) { + return ""; + } + + const totalWidth = opts.totalWidth ?? process.stdout.columns ?? 100; + const minLeftWidth = opts.minLeftWidth ?? 12; + const maxLeftWidth = opts.maxLeftWidth ?? 32; + const gap = opts.gap ?? 3; + const indent = opts.indent ?? 2; + const maxLeftContentWidth = Math.max(...rows.map((row) => row.left.length)); + const leftWidth = clamp(maxLeftContentWidth + gap, minLeftWidth, maxLeftWidth); + const rightWidth = Math.max(20, totalWidth - leftWidth - indent); + const firstIndent = " ".repeat(indent); + const continuationIndent = " ".repeat(indent + leftWidth); + + return rows + .flatMap((row) => { + const rightLines = wrapWords(row.right, rightWidth); + const firstLine = `${firstIndent}${padEndVisible(row.left, leftWidth)}${rightLines[0]}`; + const continuationLines = rightLines + .slice(1) + .map((line) => `${continuationIndent}${line}`); + return [firstLine, ...continuationLines]; + }) + .join("\n"); +} + +export function formatCommandList(commands: CommandInfo[]): string { + return formatColumns({ + rows: commands.map((cmd) => ({ + left: cmd.name, + right: cmd.description + })) + }); +} + +export function formatOptionList(options: OptionInfo[]): string { + return formatColumns({ + rows: options.map((opt) => ({ + left: opt.flags, + right: opt.description + })) + }); +} diff --git a/packages/design-system/src/index.ts b/packages/design-system/src/index.ts index a449808dc9..215a486067 100644 --- a/packages/design-system/src/index.ts +++ b/packages/design-system/src/index.ts @@ -12,6 +12,7 @@ export { symbols } from "./components/symbols.js"; export { createLogger, logger } from "./components/logger.js"; export type { LoggerOutput } from "./components/logger.js"; export { helpFormatter, formatColumns, formatCommand, formatUsage, formatOption, formatCommandList, formatOptionList } from "./components/help-formatter.js"; +export * as helpFormatterPlain from "./components/help-formatter-plain.js"; export type { CommandInfo, OptionInfo, FormatColumnsOptions } from "./components/help-formatter.js"; export { formatCommandNotFound } from "./components/command-errors.js"; export { formatCommandNotFoundPanel } from "./components/command-errors.js"; From 90bf5f2f2f145f621ce596fb01eed26fb07c34bc Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 04:07:58 -0500 Subject: [PATCH 079/111] fix: update toolcraft help rendering --- .../toolcraft-help-and-result-rendering.md | 4 +- ...oolcraft-help-and-result-rendering.md.lock | 2 +- .../components/help-formatter-plain.test.ts | 13 +++ .../src/components/help-formatter-plain.ts | 6 ++ .../src/components/help-formatter.test.ts | 13 +++ .../src/components/help-formatter.ts | 6 ++ packages/superintendent/src/cli.help.test.ts | 3 +- packages/toolcraft/src/cli.test.ts | 99 ++++++++++++++++--- packages/toolcraft/src/cli.ts | 57 +++++++---- .../src/entrypoints-mcp-proxy.test.ts | 1 + .../human-in-loop/approvals-commands.test.ts | 1 + .../cli-runtime.integration.test.ts | 1 + .../__snapshots__/runtime-help.test.ts.snap | 7 +- 13 files changed, 173 insertions(+), 40 deletions(-) diff --git a/docs/plans/toolcraft-help-and-result-rendering.md b/docs/plans/toolcraft-help-and-result-rendering.md index f53337fd3e..2b5ff3ee0c 100644 --- a/docs/plans/toolcraft-help-and-result-rendering.md +++ b/docs/plans/toolcraft-help-and-result-rendering.md @@ -180,8 +180,8 @@ tasks: --output, --version rendered (in that order) 3. -h, --help never appears in any of the above status: - implement: open - test: open + implement: done + test: done commit: open - id: toolcraft-help-field-tokens diff --git a/docs/plans/toolcraft-help-and-result-rendering.md.lock b/docs/plans/toolcraft-help-and-result-rendering.md.lock index 6028c63506..2e38c7c346 100644 --- a/docs/plans/toolcraft-help-and-result-rendering.md.lock +++ b/docs/plans/toolcraft-help-and-result-rendering.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T08:57:44.328Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T09:03:47.589Z"} \ No newline at end of file diff --git a/packages/design-system/src/components/help-formatter-plain.test.ts b/packages/design-system/src/components/help-formatter-plain.test.ts index 416a681cd7..1319de380f 100644 --- a/packages/design-system/src/components/help-formatter-plain.test.ts +++ b/packages/design-system/src/components/help-formatter-plain.test.ts @@ -71,6 +71,19 @@ describe("plain help formatter", () => { expect(result).toBe(" cmd one two three four\n five"); }); + it("puts overwide left cells on their own line before the description", () => { + const result = formatColumns({ + rows: [{ left: "run [doc] [--agent ]", right: "Run the full loop." }], + totalWidth: 50, + minLeftWidth: 1, + maxLeftWidth: 12, + gap: 2, + indent: 2 + }); + + expect(result).toBe(" run [doc] [--agent ]\n Run the full loop."); + }); + it("formats command lists without text styling", () => { const result = formatCommandList([ { name: "configure", description: "Set up provider credentials" }, diff --git a/packages/design-system/src/components/help-formatter-plain.ts b/packages/design-system/src/components/help-formatter-plain.ts index fdaab93bd4..a3a4e0bc38 100644 --- a/packages/design-system/src/components/help-formatter-plain.ts +++ b/packages/design-system/src/components/help-formatter-plain.ts @@ -122,6 +122,12 @@ export function formatColumns(opts: FormatColumnsOptions): string { return rows .flatMap((row) => { const rightLines = wrapWords(row.right, rightWidth); + if (row.left.length > leftWidth) { + return [ + `${firstIndent}${row.left}`, + ...rightLines.map((line) => `${continuationIndent}${line}`) + ]; + } const firstLine = `${firstIndent}${padEndVisible(row.left, leftWidth)}${rightLines[0]}`; const continuationLines = rightLines .slice(1) diff --git a/packages/design-system/src/components/help-formatter.test.ts b/packages/design-system/src/components/help-formatter.test.ts index 25fdc2e13b..6ac17ff529 100644 --- a/packages/design-system/src/components/help-formatter.test.ts +++ b/packages/design-system/src/components/help-formatter.test.ts @@ -62,6 +62,19 @@ describe("formatColumns", () => { expect(result).toBe("cmd short\n supercalifragilisticexpialidocious\n tail"); }); + it("puts overwide left cells on their own line before the description", () => { + const result = formatColumns({ + rows: [{ left: "run [doc] [--agent ]", right: "Run the full loop." }], + totalWidth: 50, + minLeftWidth: 1, + maxLeftWidth: 12, + gap: 2, + indent: 2 + }); + + expect(result).toBe(" run [doc] [--agent ]\n Run the full loop."); + }); + it("preserves continuation indent", () => { const result = formatColumns({ rows: [{ left: "left", right: "alpha beta gamma delta" }], diff --git a/packages/design-system/src/components/help-formatter.ts b/packages/design-system/src/components/help-formatter.ts index 7d10d5fcf6..2dce60bafc 100644 --- a/packages/design-system/src/components/help-formatter.ts +++ b/packages/design-system/src/components/help-formatter.ts @@ -114,6 +114,12 @@ export function formatColumns(opts: FormatColumnsOptions): string { return rows .flatMap((row) => { const rightLines = wrapWords(row.right, rightWidth); + if (visibleWidth(row.left) > leftWidth) { + return [ + `${firstIndent}${row.left}`, + ...rightLines.map((line) => `${continuationIndent}${line}`) + ]; + } const firstLine = `${firstIndent}${padEndVisible(row.left, leftWidth)}${rightLines[0]}`; const continuationLines = rightLines .slice(1) diff --git a/packages/superintendent/src/cli.help.test.ts b/packages/superintendent/src/cli.help.test.ts index 80054644f1..f73928bd60 100644 --- a/packages/superintendent/src/cli.help.test.ts +++ b/packages/superintendent/src/cli.help.test.ts @@ -22,7 +22,8 @@ describe("superintendent CLI help", () => { const output = readStdout(stdoutWrite); expect(output).toContain("superintendent"); - expect(output).toContain("Commands:"); + expect(output).toContain("COMMANDS"); + expect(output).not.toContain("Commands:"); expect(output).toContain("run"); expect(output).toContain("complete"); expect(output).toContain("builder"); diff --git a/packages/toolcraft/src/cli.test.ts b/packages/toolcraft/src/cli.test.ts index 3b145ca17d..cb24d9ed98 100644 --- a/packages/toolcraft/src/cli.test.ts +++ b/packages/toolcraft/src/cli.test.ts @@ -42,6 +42,7 @@ vi.mock("@poe-code/design-system", () => ({ text: { heading: (value: string) => value, section: (value: string) => value, + sectionHeader: (value: string) => value, muted: (value: string) => value, usageCommand: (value: string) => value, }, @@ -661,7 +662,7 @@ describe("runCLI", () => { }); }); - it("hides --preset from generated help unless presets are enabled", async () => { + it("renders only always-on global options when presets and version are disabled", async () => { const deploy = defineCommand({ name: "deploy", params: S.Object({ @@ -682,12 +683,30 @@ describe("runCLI", () => { await runCLI(root); const output = readStdout(stdoutWrite); - expect(output).toContain("Global options:"); + expect(output).toMatchInlineSnapshot(` + "toolcraft + + Commands + deploy --service + approvals Inspect and execute queued approvals. + list [--state ] List queued approvals. + show --approval-id Show one approval. + run --approval-id Run one queued approval. + + Options + --yes Accept defaults, skip prompts + --output Output format: rich, md, json. + " + `); + expect(output).toContain("Options"); expect(output).not.toContain("--preset"); expect(output).toContain("--yes"); + expect(output).toContain("--output "); + expect(output).not.toContain("--version"); + expect(output).not.toContain("-h, --help"); }); - it("shows --preset in generated help when presets are enabled", async () => { + it("renders preset and version global options when presets and version are enabled", async () => { const deploy = defineCommand({ name: "deploy", params: S.Object({ @@ -705,11 +724,66 @@ describe("runCLI", () => { const stdoutWrite = vi.spyOn(process.stdout, "write").mockImplementation(() => true); - await runCLI(root, { presets: true }); + await runCLI(root, { presets: true, version: "1.2.3" }); const output = readStdout(stdoutWrite); - expect(output).toContain("Global options:"); + expect(output).toMatchInlineSnapshot(` + "toolcraft + + Commands + deploy --service + approvals Inspect and execute queued approvals. + list [--state ] List queued approvals. + show --approval-id Show one approval. + run --approval-id Run one queued approval. + + Options + --preset Load parameter defaults from a JSON file + --yes Accept defaults, skip prompts + --output Output format: rich, md, json. + --version Show version + " + `); + expect(output).toContain("Options"); expect(output).toContain("--preset "); + expect(output).toContain("--version"); + expect(output).not.toContain("-h, --help"); + }); + + it("never renders commander help in generated global option tables", async () => { + const deploy = defineCommand({ + name: "deploy", + params: S.Object({ + service: S.String(), + }), + handler: vi.fn(), + }); + + const root = defineGroup({ + name: "toolcraft", + children: [deploy], + }); + + process.argv = ["node", "toolcraft", "--help"]; + + const stdoutWrite = vi.spyOn(process.stdout, "write").mockImplementation(() => true); + + await runCLI(root); + const withoutPresetOrVersion = readStdout(stdoutWrite); + + stdoutWrite.mockClear(); + await runCLI(root, { presets: true, version: "1.2.3" }); + const withPresetAndVersion = readStdout(stdoutWrite); + + expect({ + withPresetAndVersion: withPresetAndVersion.includes("-h, --help"), + withoutPresetOrVersion: withoutPresetOrVersion.includes("-h, --help"), + }).toMatchInlineSnapshot(` + { + "withPresetAndVersion": false, + "withoutPresetOrVersion": false, + } + `); }); it("allows a command parameter named preset when presets are not enabled", async () => { @@ -1972,7 +2046,8 @@ describe("runCLI", () => { await runCLI(root); const output = readStdout(stdoutWrite); - expect(output).toContain("Commands:"); + expect(output).toContain("Commands"); + expect(output).not.toContain("Commands:"); expect(output).toContain("calendar"); expect(output).toContain(" events"); expect(output).toContain(" list"); @@ -2407,15 +2482,15 @@ describe("runCLI", () => { const output = readStdout(stdoutWrite); expect(output).toContain("poe-code generate text"); - expect(output).toContain("Options:"); + expect(output).toContain("Options"); expect(output).toContain("--prompt "); expect(output).toContain("Generation prompt (required)"); expect(output).toContain("--model "); expect(output).toContain("Model identifier (default: GPT-4.1)"); - expect(output).toContain("Global options:"); + expect(output).not.toContain("Global options:"); expect(output).not.toContain("--preset"); expect(output).toContain("--yes"); - expect(output).toContain("Secrets (via environment):"); + expect(output).toContain("Secrets (environment)"); expect(output).toContain("POE_API_KEY"); expect(output).toContain("Inherited from generate group"); }); @@ -2512,7 +2587,8 @@ describe("runCLI", () => { await runCLI(root); const output = readStdout(stdoutWrite); - expect(output).toContain("Commands:"); + expect(output).toContain("Commands"); + expect(output).not.toContain("Commands:"); expect(output).toContain("text"); expect(output).not.toContain("invoke"); }); @@ -2536,7 +2612,8 @@ describe("runCLI", () => { await runCLI(root); const output = readStdout(stdoutWrite); - expect(output).toContain("Commands:"); + expect(output).toContain("Commands"); + expect(output).not.toContain("Commands:"); expect(output).toContain("builder"); }); diff --git a/packages/toolcraft/src/cli.ts b/packages/toolcraft/src/cli.ts index 55c6525d77..b7b0a22879 100644 --- a/packages/toolcraft/src/cli.ts +++ b/packages/toolcraft/src/cli.ts @@ -1208,10 +1208,13 @@ function formatCommandRows( }); } -function formatGlobalOptionRows(showVersion: boolean, presetsEnabled: boolean): HelpOptionRow[] { +function formatGlobalOptionRows(ctx: { + showVersion: boolean; + presetsEnabled: boolean; +}): HelpOptionRow[] { const rows: HelpOptionRow[] = []; - if (presetsEnabled) { + if (ctx.presetsEnabled) { rows.push({ flags: "--preset ", description: "Load parameter defaults from a JSON file", @@ -1225,15 +1228,11 @@ function formatGlobalOptionRows(showVersion: boolean, presetsEnabled: boolean): }, { flags: "--output ", - description: "Output format (rich, md, json)", - }, - { - flags: "-h, --help", - description: "Show help", + description: "Output format: rich, md, json.", } ); - if (showVersion) { + if (ctx.showVersion) { rows.push({ flags: "--version", description: "Show version", @@ -1260,19 +1259,21 @@ function renderGroupHelp( breadcrumb: string[], scope: Scope, casing: Casing, - showVersion: boolean, - presetsEnabled: boolean, + globalOptions: { + showVersion: boolean; + presetsEnabled: boolean; + }, rootUsageName?: string ): string { const sections: string[] = []; - const globalLongOptionFlags = getGlobalLongOptionFlags(presetsEnabled); + const globalLongOptionFlags = getGlobalLongOptionFlags(globalOptions.presetsEnabled); const commandRows = formatCommandRows(group, scope, casing, globalLongOptionFlags); if (commandRows.length > 0) { - sections.push(`${text.section("Commands:")}\n${formatCommandList(commandRows)}`); + sections.push(`${text.sectionHeader("Commands")}\n${formatCommandList(commandRows)}`); } - sections.push(`${text.section("Global options:")}\n${formatOptionList(formatGlobalOptionRows(showVersion, presetsEnabled))}`); + sections.push(`${text.sectionHeader("Options")}\n${formatOptionList(formatGlobalOptionRows(globalOptions))}`); return renderHelpDocument({ breadcrumb, @@ -1287,11 +1288,14 @@ function renderLeafHelp( command: Command, breadcrumb: string[], casing: Casing, - presetsEnabled: boolean, + globalOptions: { + showVersion: boolean; + presetsEnabled: boolean; + }, rootUsageName?: string ): string { const sections: string[] = []; - const globalLongOptionFlags = getGlobalLongOptionFlags(presetsEnabled); + const globalLongOptionFlags = getGlobalLongOptionFlags(globalOptions.presetsEnabled); const collected = collectFields(command.params, casing, globalLongOptionFlags); const fields = assignPositionals(collected.fields, command.positional); const optionRows = fields.map((field) => ({ @@ -1300,14 +1304,14 @@ function renderLeafHelp( })).concat(collected.dynamicFields.flatMap((field) => formatDynamicHelpFields(field, casing))); if (optionRows.length > 0) { - sections.push(`${text.section("Options:")}\n${formatOptionList(optionRows)}`); + sections.push(`${text.sectionHeader("Options")}\n${formatOptionList(optionRows)}`); } - sections.push(`${text.section("Global options:")}\n${formatOptionList(formatGlobalOptionRows(false, presetsEnabled))}`); + sections.push(`${text.sectionHeader("Options")}\n${formatOptionList(formatGlobalOptionRows(globalOptions))}`); const secretRows = formatSecretRows(command.secrets); if (secretRows.length > 0) { - sections.push(`${text.section("Secrets (via environment):")}\n${formatOptionList(secretRows)}`); + sections.push(`${text.sectionHeader("Secrets (environment)")}\n${formatOptionList(secretRows)}`); } const positionalFields = fields.filter((f) => f.positionalIndex !== undefined); @@ -1371,11 +1375,22 @@ async function renderGeneratedHelp( target.breadcrumb, "cli", casing, - options.version !== undefined, - options.presets === true, + { + showVersion: options.version !== undefined, + presetsEnabled: options.presets === true, + }, options.rootUsageName ) - : renderLeafHelp(target.node, target.breadcrumb, casing, options.presets === true, options.rootUsageName); + : renderLeafHelp( + target.node, + target.breadcrumb, + casing, + { + showVersion: options.version !== undefined, + presetsEnabled: options.presets === true, + }, + options.rootUsageName + ); process.stdout.write(rendered); }); diff --git a/packages/toolcraft/src/entrypoints-mcp-proxy.test.ts b/packages/toolcraft/src/entrypoints-mcp-proxy.test.ts index 673f08dea1..033a5cfd69 100644 --- a/packages/toolcraft/src/entrypoints-mcp-proxy.test.ts +++ b/packages/toolcraft/src/entrypoints-mcp-proxy.test.ts @@ -91,6 +91,7 @@ vi.mock("@poe-code/design-system", () => ({ text: { heading: (value: string) => value, section: (value: string) => value, + sectionHeader: (value: string) => value, muted: (value: string) => value, usageCommand: (value: string) => value, }, diff --git a/packages/toolcraft/src/human-in-loop/approvals-commands.test.ts b/packages/toolcraft/src/human-in-loop/approvals-commands.test.ts index e54cec2884..5794cc19f4 100644 --- a/packages/toolcraft/src/human-in-loop/approvals-commands.test.ts +++ b/packages/toolcraft/src/human-in-loop/approvals-commands.test.ts @@ -30,6 +30,7 @@ vi.mock("@poe-code/design-system", () => ({ text: { heading: (value: string) => value, section: (value: string) => value, + sectionHeader: (value: string) => value, muted: (value: string) => value, usageCommand: (value: string) => value, }, diff --git a/packages/toolcraft/src/human-in-loop/cli-runtime.integration.test.ts b/packages/toolcraft/src/human-in-loop/cli-runtime.integration.test.ts index 928ad58681..af7f840549 100644 --- a/packages/toolcraft/src/human-in-loop/cli-runtime.integration.test.ts +++ b/packages/toolcraft/src/human-in-loop/cli-runtime.integration.test.ts @@ -25,6 +25,7 @@ vi.mock("@poe-code/design-system", () => ({ text: { heading: (value: string) => value, section: (value: string) => value, + sectionHeader: (value: string) => value, muted: (value: string) => value, usageCommand: (value: string) => value, }, diff --git a/src/cli/commands/__snapshots__/runtime-help.test.ts.snap b/src/cli/commands/__snapshots__/runtime-help.test.ts.snap index 326884958f..b0a0c251c3 100644 --- a/src/cli/commands/__snapshots__/runtime-help.test.ts.snap +++ b/src/cli/commands/__snapshots__/runtime-help.test.ts.snap @@ -100,7 +100,7 @@ Usage: poe-code superintendent run [options] [doc] Run the full superintendent loop. -Options: +OPTIONS [doc] Path to the superintendent markdown document --agent Override the builder agent for this run. Precedence: --agent > plan frontmatter builder.agent. @@ -112,9 +112,8 @@ Options: --runner-sync Override runner workspace sync: both, upload, or none --tui [value] Show a live dashboard while Superintendent is running -Global options: +OPTIONS --yes Accept defaults, skip prompts - --output Output format (rich, md, json) - -h, --help Show help + --output Output format: rich, md, json. " `; From 38e02a21debd987debfda84ad3ebbea6e18fb618 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 04:20:27 -0500 Subject: [PATCH 080/111] fix: improve help value token rendering --- .../toolcraft-help-and-result-rendering.md | 8 +- ...oolcraft-help-and-result-rendering.md.lock | 2 +- .../components/help-formatter-plain.test.ts | 16 ++ .../src/components/help-formatter-plain.ts | 4 + .../src/components/help-formatter.test.ts | 16 ++ .../src/components/help-formatter.ts | 4 + packages/toolcraft/src/cli.test.ts | 151 ++++++++++++++-- packages/toolcraft/src/cli.ts | 171 ++++++++++++++---- .../__snapshots__/runtime-help.test.ts.snap | 20 +- 9 files changed, 326 insertions(+), 66 deletions(-) diff --git a/docs/plans/toolcraft-help-and-result-rendering.md b/docs/plans/toolcraft-help-and-result-rendering.md index 2b5ff3ee0c..e6f50b46e2 100644 --- a/docs/plans/toolcraft-help-and-result-rendering.md +++ b/docs/plans/toolcraft-help-and-result-rendering.md @@ -182,7 +182,7 @@ tasks: status: implement: done test: done - commit: open + commit: done - id: toolcraft-help-field-tokens title: Boolean-aware and pattern-aware help field tokens @@ -240,9 +240,9 @@ tasks: - / never appear in any rendered help row (regex assertion across the rendered output) status: - implement: open - test: open - commit: open + implement: done + test: done + commit: done - id: toolcraft-help-document-layout title: Heading line, Usage line, breadcrumb, flat commands list diff --git a/docs/plans/toolcraft-help-and-result-rendering.md.lock b/docs/plans/toolcraft-help-and-result-rendering.md.lock index 2e38c7c346..5d3a216aa9 100644 --- a/docs/plans/toolcraft-help-and-result-rendering.md.lock +++ b/docs/plans/toolcraft-help-and-result-rendering.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T09:03:47.589Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T09:15:23.762Z"} \ No newline at end of file diff --git a/packages/design-system/src/components/help-formatter-plain.test.ts b/packages/design-system/src/components/help-formatter-plain.test.ts index 1319de380f..0a848cdcc6 100644 --- a/packages/design-system/src/components/help-formatter-plain.test.ts +++ b/packages/design-system/src/components/help-formatter-plain.test.ts @@ -84,6 +84,22 @@ describe("plain help formatter", () => { expect(result).toBe(" run [doc] [--agent ]\n Run the full loop."); }); + it("does not pad rows with empty right cells", () => { + const result = formatColumns({ + rows: [ + { left: "deploy --service ", right: "" }, + { left: "approvals", right: "Inspect approvals" } + ], + totalWidth: 80, + minLeftWidth: 1, + maxLeftWidth: 32, + gap: 2, + indent: 2 + }); + + expect(result).toBe(" deploy --service \n approvals Inspect approvals"); + }); + it("formats command lists without text styling", () => { const result = formatCommandList([ { name: "configure", description: "Set up provider credentials" }, diff --git a/packages/design-system/src/components/help-formatter-plain.ts b/packages/design-system/src/components/help-formatter-plain.ts index a3a4e0bc38..a04ce43e59 100644 --- a/packages/design-system/src/components/help-formatter-plain.ts +++ b/packages/design-system/src/components/help-formatter-plain.ts @@ -121,6 +121,10 @@ export function formatColumns(opts: FormatColumnsOptions): string { return rows .flatMap((row) => { + if (row.right.length === 0) { + return [`${firstIndent}${row.left}`]; + } + const rightLines = wrapWords(row.right, rightWidth); if (row.left.length > leftWidth) { return [ diff --git a/packages/design-system/src/components/help-formatter.test.ts b/packages/design-system/src/components/help-formatter.test.ts index 6ac17ff529..f1dabeba37 100644 --- a/packages/design-system/src/components/help-formatter.test.ts +++ b/packages/design-system/src/components/help-formatter.test.ts @@ -88,6 +88,22 @@ describe("formatColumns", () => { expect(result.split("\n")[1]?.startsWith(" ".repeat(9))).toBe(true); }); + it("does not pad rows with empty right cells", () => { + const result = formatColumns({ + rows: [ + { left: "deploy --service ", right: "" }, + { left: "approvals", right: "Inspect approvals" } + ], + totalWidth: 80, + minLeftWidth: 1, + maxLeftWidth: 32, + gap: 2, + indent: 2 + }); + + expect(result).toBe(" deploy --service \n approvals Inspect approvals"); + }); + it("does not widen the column for ANSI-styled left tokens", () => { const result = formatColumns({ rows: [ diff --git a/packages/design-system/src/components/help-formatter.ts b/packages/design-system/src/components/help-formatter.ts index 2dce60bafc..479590d401 100644 --- a/packages/design-system/src/components/help-formatter.ts +++ b/packages/design-system/src/components/help-formatter.ts @@ -113,6 +113,10 @@ export function formatColumns(opts: FormatColumnsOptions): string { return rows .flatMap((row) => { + if (row.right.length === 0) { + return [`${firstIndent}${row.left}`]; + } + const rightLines = wrapWords(row.right, rightWidth); if (visibleWidth(row.left) > leftWidth) { return [ diff --git a/packages/toolcraft/src/cli.test.ts b/packages/toolcraft/src/cli.test.ts index cb24d9ed98..48b1810a37 100644 --- a/packages/toolcraft/src/cli.test.ts +++ b/packages/toolcraft/src/cli.test.ts @@ -47,7 +47,13 @@ vi.mock("@poe-code/design-system", () => ({ usageCommand: (value: string) => value, }, formatCommandList: (commands: Array<{ name: string; description: string }>) => - commands.map((command) => ` ${command.name} ${command.description}`).join("\n"), + commands + .map((command) => + command.description.length === 0 + ? ` ${command.name}` + : ` ${command.name} ${command.description}` + ) + .join("\n"), formatOptionList: (options: Array<{ flags: string; description: string }>) => options.map((option) => ` ${option.flags} ${option.description}`).join("\n"), promptText: promptState.text, @@ -687,11 +693,11 @@ describe("runCLI", () => { "toolcraft Commands - deploy --service + deploy --service approvals Inspect and execute queued approvals. - list [--state ] List queued approvals. - show --approval-id Show one approval. - run --approval-id Run one queued approval. + list [--state ] List queued approvals. + show --approval-id Show one approval. + run --approval-id Run one queued approval. Options --yes Accept defaults, skip prompts @@ -731,11 +737,11 @@ describe("runCLI", () => { "toolcraft Commands - deploy --service + deploy --service approvals Inspect and execute queued approvals. - list [--state ] List queued approvals. - show --approval-id Show one approval. - run --approval-id Run one queued approval. + list [--state ] List queued approvals. + show --approval-id Show one approval. + run --approval-id Run one queued approval. Options --preset Load parameter defaults from a JSON file @@ -2002,8 +2008,8 @@ describe("runCLI", () => { await runCLI(root); const output = readStdout(stdoutWrite); - expect(output).toContain("list-tasks [--section ]"); - expect(output).toContain("details --task-gid "); + expect(output).toContain("list-tasks [--section ]"); + expect(output).toContain("details --task-gid "); }); it("renders nested command groups in root help", async () => { @@ -2483,9 +2489,9 @@ describe("runCLI", () => { const output = readStdout(stdoutWrite); expect(output).toContain("poe-code generate text"); expect(output).toContain("Options"); - expect(output).toContain("--prompt "); + expect(output).toContain("--prompt "); expect(output).toContain("Generation prompt (required)"); - expect(output).toContain("--model "); + expect(output).toContain("--model "); expect(output).toContain("Model identifier (default: GPT-4.1)"); expect(output).not.toContain("Global options:"); expect(output).not.toContain("--preset"); @@ -2495,6 +2501,111 @@ describe("runCLI", () => { expect(output).toContain("Inherited from generate group"); }); + it("renders help value tokens from boolean defaults, schema metadata, and field names", async () => { + const inspect = defineCommand({ + name: "inspect", + params: S.Object({ + impliedFlag: S.Boolean({ + description: "Implied false flag", + }), + flag: S.Boolean({ + description: "Enable flag", + default: false, + }), + enabled: S.Boolean({ + description: "Enabled by default", + default: true, + }), + date: S.String({ + description: "Run date", + pattern: "^\\d{4}-\\d{2}-\\d{2}$", + }), + timestamp: S.String({ + description: "Run timestamp", + pattern: "^\\d{4}-\\d{2}-\\d{2}T", + }), + callbackUrl: S.String({ + description: "Callback URL", + format: "uri", + }), + userEmail: S.String({ + description: "User email", + format: "email", + }), + reportFiles: S.Array(S.String({ + description: "Report files", + })), + configPath: S.String({ + description: "Config path", + }), + token: S.String({ + description: "Token value", + }), + retries: S.Number({ + description: "Retry count", + }), + }), + handler: async () => null, + }); + + const root = defineGroup({ + name: "toolcraft", + children: [inspect], + }); + + process.argv = ["node", "toolcraft", "inspect", "--help"]; + + const stdoutWrite = vi.spyOn(process.stdout, "write").mockImplementation(() => true); + + await runCLI(root); + + const output = readStdout(stdoutWrite); + expect(output).toContain("--implied-flag Implied false flag (required)"); + expect(output).toContain("--flag Enable flag (default: false)"); + expect(output).not.toContain("--flag [value]"); + expect(output).toContain("--no-enabled Enabled by default (default: true)"); + expect(output).toContain("--date Run date (required)"); + expect(output).toContain("--timestamp Run timestamp (required)"); + expect(output).toContain("--callback-url Callback URL (required)"); + expect(output).toContain("--user-email User email (required)"); + expect(output).toContain("--report-files reportFiles (required)"); + expect(output).toContain("--config-path Config path (required)"); + expect(output).toContain("--token Token value (required)"); + expect(output).toContain("--retries Retry count (required)"); + expect(output).not.toMatch(/<(string|number)>/u); + }); + + it("renders field-name help tokens with snake casing", async () => { + const inspect = defineCommand({ + name: "inspect", + params: S.Object({ + configPath: S.String({ + description: "Config path", + }), + ownerEmail: S.String({ + description: "Owner email", + }), + }), + handler: async () => null, + }); + + const root = defineGroup({ + name: "toolcraft", + children: [inspect], + }); + + process.argv = ["node", "toolcraft", "inspect", "--help"]; + + const stdoutWrite = vi.spyOn(process.stdout, "write").mockImplementation(() => true); + + await runCLI(root, { casing: "snake" }); + + const output = readStdout(stdoutWrite); + expect(output).toContain("--config_path Config path (required)"); + expect(output).toContain("--owner_email Owner email (required)"); + expect(output).not.toMatch(/<(string|number)>/u); + }); + it("renders help for oneOf, union, record, array-object, and json params", async () => { const publish = defineCommand({ name: "publish", @@ -2543,14 +2654,14 @@ describe("runCLI", () => { const output = readStdout(stdoutWrite); expect(output).toContain("--destination.kind "); - expect(output).toContain("--destination.address "); - expect(output).toContain("--destination.url "); + expect(output).toContain("--destination.address "); + expect(output).toContain("--destination.url "); expect(output).toContain("--contact-kind "); - expect(output).toContain("--contact.email "); - expect(output).toContain("--contact.phone "); - expect(output).toContain("--weights. "); - expect(output).toContain("--recipients..name "); - expect(output).toContain("--recipients..email "); + expect(output).toContain("--contact.email "); + expect(output).toContain("--contact.phone "); + expect(output).toContain("--weights. "); + expect(output).toContain("--recipients..name "); + expect(output).toContain("--recipients..email "); expect(output).toContain("--payload "); }); diff --git a/packages/toolcraft/src/cli.ts b/packages/toolcraft/src/cli.ts index b7b0a22879..b1e0ef8114 100644 --- a/packages/toolcraft/src/cli.ts +++ b/packages/toolcraft/src/cli.ts @@ -928,41 +928,23 @@ function resolveHelpTarget( }; } -function describeSchemaType(schema: FieldSchema): string { - switch (schema.kind) { - case "string": - return "string"; - - case "number": - return "number"; - - case "boolean": - return "boolean"; - - case "enum": - return "value"; - - case "array": - return `${describeSchemaType(unwrapOptional(schema.item) as FieldSchema)}...`; - - case "json": - return "json"; - - default: - throw new UserError("Unsupported CLI schema kind."); - } -} - function formatHelpFieldFlags(field: FieldDefinition, globalLongOptionFlags: ReadonlySet): string { if (field.positionalIndex !== undefined) { return formatPositionalToken(field); } if (field.schema.kind === "boolean") { - return `${formatOptionFlags(field, globalLongOptionFlags)} [value]`; + if (field.defaultValue === true) { + return `--no-${field.optionFlag.slice(2)}`; + } + + return formatOptionFlags(field, globalLongOptionFlags); } - return `${formatOptionFlags(field, globalLongOptionFlags)} <${describeSchemaType(field.schema)}>`; + return `${formatOptionFlags(field, globalLongOptionFlags)} <${describeHelpValueToken(field.schema, { + displayPath: field.displayPath, + optionFlag: field.optionFlag, + })}>`; } function appendHelpMetadata(description: string, metadata: string[]): string { @@ -992,6 +974,122 @@ function formatHelpFieldDescription(field: FieldDefinition): string { return appendHelpMetadata(description, metadata); } +function describeKnownStringFormat(format: string | undefined): string | undefined { + switch (format) { + case "date": + return "date"; + + case "date-time": + return "datetime"; + + case "uri": + return "url"; + + case "email": + return "email"; + + default: + return undefined; + } +} + +function describeKnownStringPattern(pattern: string | undefined): string | undefined { + if (pattern === undefined) { + return undefined; + } + + if (pattern === "^\\d{4}-\\d{2}-\\d{2}$") { + return "YYYY-MM-DD"; + } + + if (pattern.startsWith("^\\d{4}-\\d{2}-\\d{2}T")) { + return "YYYY-MM-DDTHH:MM:SS"; + } + + return undefined; +} + +function stripLongOptionPrefix(optionFlag: string): string { + return optionFlag.startsWith("--") ? optionFlag.slice(2) : optionFlag; +} + +function getLastSegment(value: string, separator: string): string { + const segments = value.split(separator); + return segments[segments.length - 1] ?? value; +} + +function matchesFieldNameSuffix(name: string, suffix: string): boolean { + const lowerName = name.toLowerCase(); + const lowerSuffix = suffix.toLowerCase(); + + return ( + lowerName === lowerSuffix || + name.endsWith(suffix) || + lowerName.endsWith(`-${lowerSuffix}`) || + lowerName.endsWith(`_${lowerSuffix}`) + ); +} + +function describeFieldNameValueToken(displayPath: string, optionFlag: string): string | undefined { + const displayName = getLastSegment(displayPath, "."); + const optionName = getLastSegment(stripLongOptionPrefix(optionFlag), "."); + const candidates = [displayName, optionName]; + const suffixTokens = [ + ["Path", "path"], + ["Paths", "path"], + ["File", "path"], + ["Files", "path"], + ["Url", "url"], + ["Email", "email"], + ["Name", "name"], + ["Id", "id"], + ] as const; + + for (const [suffix, token] of suffixTokens) { + if (candidates.some((candidate) => matchesFieldNameSuffix(candidate, suffix))) { + return token; + } + } + + return undefined; +} + +function describeHelpValueToken( + schema: FieldSchema, + field: { + displayPath: string; + optionFlag: string; + } +): string { + if (schema.kind === "array") { + const itemSchema = unwrapOptional(schema.item); + + if (itemSchema.kind === "array" || itemSchema.kind === "object") { + return "value..."; + } + + return `${describeHelpValueToken(itemSchema as FieldSchema, field)}...`; + } + + if (schema.kind === "json") { + return "json"; + } + + if (schema.kind === "string") { + const metadataToken = describeKnownStringFormat(schema.format) ?? describeKnownStringPattern(schema.pattern); + + if (metadataToken !== undefined) { + return metadataToken; + } + } + + if (schema.kind === "enum") { + return "value"; + } + + return describeFieldNameValueToken(field.displayPath, field.optionFlag) ?? "value"; +} + function describeDynamicFieldType(field: DynamicFieldDefinition): string { if (field.schema.kind === "record") { const valueSchema = unwrapOptional(field.schema.value); @@ -1001,14 +1099,20 @@ function describeDynamicFieldType(field: DynamicFieldDefinition): string { } if (valueSchema.kind === "array") { - return `${describeSchemaType(valueSchema as FieldSchema)}`; + return describeHelpValueToken(valueSchema as FieldSchema, { + displayPath: field.optionPathDisplay, + optionFlag: field.optionFlag, + }); } if (valueSchema.kind === "object") { return "value"; } - return describeSchemaType(valueSchema as FieldSchema); + return describeHelpValueToken(valueSchema as FieldSchema, { + displayPath: field.optionPathDisplay, + optionFlag: field.optionFlag, + }); } return "value"; @@ -1086,8 +1190,13 @@ function collectDynamicObjectHelpRows( rows.push({ flags: childSchema.kind === "boolean" - ? `${optionFlag} [value]` - : `${optionFlag} <${describeSchemaType(childSchema as FieldSchema)}>`, + ? childSchema.default === true + ? `--no-${optionFlag.slice(2)}` + : optionFlag + : `${optionFlag} <${describeHelpValueToken(childSchema as FieldSchema, { + displayPath, + optionFlag, + })}>`, description: appendHelpMetadata(description, metadata), }); } diff --git a/src/cli/commands/__snapshots__/runtime-help.test.ts.snap b/src/cli/commands/__snapshots__/runtime-help.test.ts.snap index b0a0c251c3..c1b3e4284d 100644 --- a/src/cli/commands/__snapshots__/runtime-help.test.ts.snap +++ b/src/cli/commands/__snapshots__/runtime-help.test.ts.snap @@ -101,16 +101,16 @@ Usage: poe-code superintendent run [options] [doc] Run the full superintendent loop. OPTIONS - [doc] Path to the superintendent markdown document - --agent Override the builder agent for this run. Precedence: --agent > plan - frontmatter builder.agent. - --runtime Override runtime backend: host, docker, or e2b - --runtime-image Override Docker runtime image - --runtime-template Override E2B runtime template id - --detach [value] Run as a detached runtime job - --mount-poe-code [value] Mount the local poe-code checkout into the runtime - --runner-sync Override runner workspace sync: both, upload, or none - --tui [value] Show a live dashboard while Superintendent is running + [doc] Path to the superintendent markdown document + --agent Override the builder agent for this run. Precedence: --agent > plan + frontmatter builder.agent. + --runtime Override runtime backend: host, docker, or e2b + --runtime-image Override Docker runtime image + --runtime-template Override E2B runtime template id + --detach Run as a detached runtime job + --mount-poe-code Mount the local poe-code checkout into the runtime + --runner-sync Override runner workspace sync: both, upload, or none + --tui Show a live dashboard while Superintendent is running OPTIONS --yes Accept defaults, skip prompts From 8a8bcdfc15ff980c0b62afc201f3aaacde3c7d6b Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 04:28:55 -0500 Subject: [PATCH 081/111] fix(toolcraft): refine help rendering --- .../toolcraft-help-and-result-rendering.md | 4 +- ...oolcraft-help-and-result-rendering.md.lock | 2 +- packages/toolcraft/src/cli.test.ts | 1351 +++++++++++------ packages/toolcraft/src/cli.ts | 588 ++++--- .../__snapshots__/runtime-help.test.ts.snap | 4 +- 5 files changed, 1239 insertions(+), 710 deletions(-) diff --git a/docs/plans/toolcraft-help-and-result-rendering.md b/docs/plans/toolcraft-help-and-result-rendering.md index e6f50b46e2..b15aabc286 100644 --- a/docs/plans/toolcraft-help-and-result-rendering.md +++ b/docs/plans/toolcraft-help-and-result-rendering.md @@ -304,8 +304,8 @@ tasks: 7. Snapshot at isTTY=false: plain-text helpFormatterPlain path is used; output contains no ANSI escape codes status: - implement: open - test: open + implement: done + test: done commit: open - id: toolcraft-renderer-mcp-unwrap diff --git a/docs/plans/toolcraft-help-and-result-rendering.md.lock b/docs/plans/toolcraft-help-and-result-rendering.md.lock index 5d3a216aa9..04331d6469 100644 --- a/docs/plans/toolcraft-help-and-result-rendering.md.lock +++ b/docs/plans/toolcraft-help-and-result-rendering.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T09:15:23.762Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T09:27:34.906Z"} \ No newline at end of file diff --git a/packages/toolcraft/src/cli.test.ts b/packages/toolcraft/src/cli.test.ts index 48b1810a37..d041752bf5 100644 --- a/packages/toolcraft/src/cli.test.ts +++ b/packages/toolcraft/src/cli.test.ts @@ -11,7 +11,7 @@ const loggerState = { error: [] as string[], resolved: [] as Array<{ label: string; value: string }>, errorResolved: [] as Array<{ label: string; value: string }>, - message: [] as string[], + message: [] as string[] }; const promptState = { @@ -20,7 +20,12 @@ const promptState = { confirm: vi.fn(), isCancel: vi.fn((value: unknown) => typeof value === "symbol"), cancel: vi.fn(), - resetOutputFormatCache: vi.fn(), + resetOutputFormatCache: vi.fn() +}; + +const formatterState = { + plainCommandListCalls: 0, + plainOptionListCalls: 0 }; vi.mock("@poe-code/design-system", () => ({ @@ -32,37 +37,47 @@ vi.mock("@poe-code/design-system", () => ({ resolved: (label: string, value: string) => loggerState.resolved.push({ label, value }), errorResolved: (label: string, value: string) => loggerState.errorResolved.push({ label, value }), - message: (message: string) => loggerState.message.push(message), + message: (message: string) => loggerState.message.push(message) }), renderTable: vi.fn(() => "table"), getTheme: vi.fn(() => ({ header: (value: string) => value, - muted: (value: string) => value, + muted: (value: string) => value })), text: { heading: (value: string) => value, section: (value: string) => value, sectionHeader: (value: string) => value, muted: (value: string) => value, - usageCommand: (value: string) => value, + usageCommand: (value: string) => value }, formatCommandList: (commands: Array<{ name: string; description: string }>) => - commands - .map((command) => - command.description.length === 0 - ? ` ${command.name}` - : ` ${command.name} ${command.description}` - ) - .join("\n"), + formatMockColumns( + commands.map((command) => ({ left: command.name, right: command.description })) + ), formatOptionList: (options: Array<{ flags: string; description: string }>) => - options.map((option) => ` ${option.flags} ${option.description}`).join("\n"), + formatMockColumns(options.map((option) => ({ left: option.flags, right: option.description }))), + helpFormatterPlain: { + formatCommandList: (commands: Array<{ name: string; description: string }>) => { + formatterState.plainCommandListCalls += 1; + return formatMockColumns( + commands.map((command) => ({ left: command.name, right: command.description })) + ); + }, + formatOptionList: (options: Array<{ flags: string; description: string }>) => { + formatterState.plainOptionListCalls += 1; + return formatMockColumns( + options.map((option) => ({ left: option.flags, right: option.description })) + ); + } + }, promptText: promptState.text, select: promptState.select, confirm: promptState.confirm, isCancel: promptState.isCancel, cancel: promptState.cancel, resetOutputFormatCache: promptState.resetOutputFormatCache, - note: vi.fn(), + note: vi.fn() })); vi.mock("node:fs/promises", async () => { @@ -146,15 +161,15 @@ const fixtureCommand = defineCommand<{ store: FixtureStoreService }>({ params: S.Object({}), secrets: { apiKey: { - env: "API_KEY", - }, + env: "API_KEY" + } }, handler: async ({ fetch, fs, secrets, store }) => { const matched = await fetch("https://example.com/items"); const matchedBody = matched === null ? null : await matched.json(); const unmatchedRead = await fetch("https://example.com/missing"); const unmatchedWrite = await fetch("https://example.com/items", { - method: "POST", + method: "POST" }); const file = await fs.readFile("/config.json"); const missingFile = await fs.readFile("/missing.json"); @@ -172,14 +187,14 @@ const fixtureCommand = defineCommand<{ store: FixtureStoreService }>({ secret: secrets.apiKey, storeValue, unmatchedReadStatus: unmatchedRead === null ? null : unmatchedRead.status, - unmatchedWriteStatus: unmatchedWrite === null ? null : unmatchedWrite.status, + unmatchedWriteStatus: unmatchedWrite === null ? null : unmatchedWrite.status }; - }, + } }); const fixtureRoot = defineGroup({ name: "toolcraft", - children: [fixtureCommand], + children: [fixtureCommand] }); function resetLoggerState(): void { @@ -194,14 +209,76 @@ function resetLoggerState(): void { const originalArgv = [...process.argv]; const stdoutTTY = Object.getOwnPropertyDescriptor(process.stdout, "isTTY"); +const stdoutColumns = Object.getOwnPropertyDescriptor(process.stdout, "columns"); const stdinTTY = Object.getOwnPropertyDescriptor(process.stdin, "isTTY"); const originalOutputFormat = process.env.OUTPUT_FORMAT; const originalFixtureSelector = process.env.TOOLCRAFT_FIXTURE; +function formatMockColumns(rows: Array<{ left: string; right: string }>): string { + if (typeof process.stdout.columns !== "number") { + return rows + .map((row) => (row.right.length === 0 ? ` ${row.left}` : ` ${row.left} ${row.right}`)) + .join("\n"); + } + + const maxLeftContentWidth = Math.max(...rows.map((row) => row.left.length), 0); + const leftWidth = Math.min(Math.max(maxLeftContentWidth + 3, 12), 32); + const rightWidth = Math.max(20, process.stdout.columns - leftWidth - 2); + const continuationIndent = " ".repeat(2 + leftWidth); + + return rows + .flatMap((row) => { + if (row.right.length === 0) { + return [` ${row.left}`]; + } + + const words = row.right.split(" ").filter((word) => word.length > 0); + const rightLines: string[] = []; + let line = ""; + + for (const word of words) { + if (line.length === 0) { + line = word; + continue; + } + + if (line.length + 1 + word.length <= rightWidth) { + line = `${line} ${word}`; + continue; + } + + rightLines.push(line); + line = word; + } + + rightLines.push(line); + + if (row.left.length > leftWidth) { + return [ + ` ${row.left}`, + ...rightLines.map((rightLine) => `${continuationIndent}${rightLine}`) + ]; + } + + return [ + ` ${row.left}${" ".repeat(leftWidth - row.left.length)}${rightLines[0] ?? ""}`, + ...rightLines.slice(1).map((rightLine) => `${continuationIndent}${rightLine}`) + ]; + }) + .join("\n"); +} + function setTTY(stream: NodeJS.WriteStream | NodeJS.ReadStream, value: boolean): void { Object.defineProperty(stream, "isTTY", { configurable: true, - value, + value + }); +} + +function setStdoutColumns(value: number): void { + Object.defineProperty(process.stdout, "columns", { + configurable: true, + value }); } @@ -222,9 +299,11 @@ describe("runCLI", () => { vi.clearAllMocks(); vol.reset(); vol.fromJSON({ - [fixtureFilePath]: fixtureFileContents, + [fixtureFilePath]: fixtureFileContents }); resetLoggerState(); + formatterState.plainCommandListCalls = 0; + formatterState.plainOptionListCalls = 0; promptState.isCancel.mockImplementation((value: unknown) => typeof value === "symbol"); process.argv = [...originalArgv]; process.exitCode = undefined; @@ -243,26 +322,33 @@ describe("runCLI", () => { if (stdoutTTY) { Object.defineProperty(process.stdout, "isTTY", stdoutTTY); } + if (stdoutColumns) { + Object.defineProperty(process.stdout, "columns", stdoutColumns); + } else { + Reflect.deleteProperty(process.stdout, "columns"); + } if (stdinTTY) { Object.defineProperty(process.stdin, "isTTY", stdinTTY); } }); it("parses nested params, arrays, booleans, enums, and positionals with kebab casing", async () => { - const handler = vi.fn(async (ctx: { - params: { - name: string; - dryRun?: boolean; - retryCount: number; - mode: "safe" | "fast"; - tags: string[]; - database: { host: string }; - }; - marker: string; - }) => { - expect(ctx.marker).toBe("service"); - return ctx.params; - }); + const handler = vi.fn( + async (ctx: { + params: { + name: string; + dryRun?: boolean; + retryCount: number; + mode: "safe" | "fast"; + tags: string[]; + database: { host: string }; + }; + marker: string; + }) => { + expect(ctx.marker).toBe("service"); + return ctx.params; + } + ); const renderJson = vi.fn((result: unknown) => result); @@ -276,18 +362,18 @@ describe("runCLI", () => { mode: S.Enum(["safe", "fast"] as const), tags: S.Array(S.String()), database: S.Object({ - host: S.String(), - }), + host: S.String() + }) }), handler, render: { - json: renderJson, - }, + json: renderJson + } }); const root = defineGroup({ name: "toolcraft", - children: [deploy], + children: [deploy] }); process.argv = [ @@ -307,15 +393,15 @@ describe("runCLI", () => { "db.internal", "--output", "json", - "--yes", + "--yes" ]; const stdoutWrite = vi.spyOn(process.stdout, "write").mockImplementation(() => true); await runCLI(root, { services: { - marker: "service", - }, + marker: "service" + } }); expect(handler).toHaveBeenCalledTimes(1); @@ -326,8 +412,8 @@ describe("runCLI", () => { mode: "safe", tags: ["alpha", "beta", "gamma"], database: { - host: "db.internal", - }, + host: "db.internal" + } }); expect(renderJson).toHaveBeenCalledWith( { @@ -337,13 +423,13 @@ describe("runCLI", () => { mode: "safe", tags: ["alpha", "beta", "gamma"], database: { - host: "db.internal", - }, + host: "db.internal" + } }, expect.objectContaining({ logger: expect.any(Object), renderTable: expect.any(Function), - getTheme: expect.any(Function), + getTheme: expect.any(Function) }) ); expect(stdoutWrite).toHaveBeenCalledWith( @@ -352,73 +438,80 @@ describe("runCLI", () => { }); it("supports snake casing for generated option names", async () => { - const handler = vi.fn(async (ctx: { params: { dryRun: boolean; retryCount: number } }) => ctx.params); + const handler = vi.fn( + async (ctx: { params: { dryRun: boolean; retryCount: number } }) => ctx.params + ); const deploy = defineCommand({ name: "deploy", params: S.Object({ dryRun: S.Boolean(), - retryCount: S.Number(), + retryCount: S.Number() }), - handler, + handler }); const root = defineGroup({ name: "toolcraft", - children: [deploy], + children: [deploy] }); - process.argv = [ - "node", - "toolcraft", - "deploy", - "--dry_run", - "--retry_count", - "5", - "--yes", - ]; + process.argv = ["node", "toolcraft", "deploy", "--dry_run", "--retry_count", "5", "--yes"]; await runCLI(root, { - casing: "snake", + casing: "snake" }); expect(handler).toHaveBeenCalledTimes(1); expect(handler.mock.calls[0]?.[0].params).toEqual({ dryRun: true, - retryCount: 5, + retryCount: 5 }); }); it("accepts --flag true and --flag false as explicit boolean values", async () => { - const handler = vi.fn(async (ctx: { params: { enabled: boolean; disabled: boolean } }) => ctx.params); + const handler = vi.fn( + async (ctx: { params: { enabled: boolean; disabled: boolean } }) => ctx.params + ); const toggle = defineCommand({ name: "toggle", params: S.Object({ enabled: S.Boolean(), - disabled: S.Boolean(), + disabled: S.Boolean() }), - handler, + handler }); const root = defineGroup({ name: "toolcraft", children: [toggle] }); - process.argv = ["node", "toolcraft", "toggle", "--enabled", "true", "--disabled", "false", "--yes"]; + process.argv = [ + "node", + "toolcraft", + "toggle", + "--enabled", + "true", + "--disabled", + "false", + "--yes" + ]; await runCLI(root); expect(handler.mock.calls[0]?.[0].params).toEqual({ enabled: true, disabled: false }); }); it("accepts --flag (no value) as true and --no-flag as false for boolean params", async () => { - const handler = vi.fn(async (ctx: { params: { enabled: boolean; disabled: boolean } }) => ctx.params); + const handler = vi.fn( + async (ctx: { params: { enabled: boolean; disabled: boolean } }) => ctx.params + ); const toggle = defineCommand({ name: "toggle", params: S.Object({ enabled: S.Boolean(), - disabled: S.Boolean(), + disabled: S.Boolean() }), - handler, + handler }); const root = defineGroup({ name: "toolcraft", children: [toggle] }); @@ -435,7 +528,7 @@ describe("runCLI", () => { const toggle = defineCommand({ name: "toggle", params: S.Object({ enabled: S.Boolean() }), - handler, + handler }); const root = defineGroup({ name: "toolcraft", children: [toggle] }); @@ -459,15 +552,15 @@ describe("runCLI", () => { name: "deploy", params: S.Object({ count: S.Number({ - jsonType: "integer", - }), + jsonType: "integer" + }) }), - handler, + handler }); const root = defineGroup({ name: "toolcraft", - children: [deploy], + children: [deploy] }); process.argv = ["node", "toolcraft", "deploy", "--count", "1.5"]; @@ -483,23 +576,25 @@ describe("runCLI", () => { }); it("prompts for missing required params, uses select for enums, and confirms resolved values", async () => { - const handler = vi.fn(async (ctx: { params: { name: string; mode: "safe" | "fast" } }) => ctx.params); + const handler = vi.fn( + async (ctx: { params: { name: string; mode: "safe" | "fast" } }) => ctx.params + ); const deploy = defineCommand({ name: "deploy", confirm: true, params: S.Object({ name: S.String({ - default: "demo-service", + default: "demo-service" }), - mode: S.Enum(["safe", "fast"] as const), + mode: S.Enum(["safe", "fast"] as const) }), - handler, + handler }); const root = defineGroup({ name: "toolcraft", - children: [deploy], + children: [deploy] }); promptState.text.mockResolvedValueOnce("demo-service"); @@ -512,27 +607,27 @@ describe("runCLI", () => { expect(promptState.text).toHaveBeenCalledWith({ message: "name", - initialValue: "demo-service", + initialValue: "demo-service" }); expect(promptState.select).toHaveBeenCalledWith({ message: "mode", options: [ { label: "safe", value: "safe" }, - { label: "fast", value: "fast" }, + { label: "fast", value: "fast" } ], - initialValue: undefined, + initialValue: undefined }); expect(loggerState.resolved).toEqual([ { label: "name", value: "demo-service" }, - { label: "mode", value: "fast" }, + { label: "mode", value: "fast" } ]); expect(promptState.confirm).toHaveBeenCalledWith({ message: "Proceed?", - initialValue: true, + initialValue: true }); expect(handler.mock.calls[0]?.[0].params).toEqual({ name: "demo-service", - mode: "fast", + mode: "fast" }); }); @@ -545,11 +640,11 @@ describe("runCLI", () => { mode: S.Enum(["safe", "fast"] as const, { loadOptions: async () => [ { label: "Safe (slow)", value: "safe" }, - { label: "Fast (risky)", value: "fast" }, - ], - }), + { label: "Fast (risky)", value: "fast" } + ] + }) }), - handler, + handler }); const root = defineGroup({ name: "toolcraft", children: [deploy] }); @@ -564,8 +659,8 @@ describe("runCLI", () => { expect.objectContaining({ options: [ { label: "Safe (slow)", value: "safe" }, - { label: "Fast (risky)", value: "fast" }, - ], + { label: "Fast (risky)", value: "fast" } + ] }) ); expect(handler.mock.calls[0]?.[0].params).toEqual({ mode: "safe" }); @@ -580,9 +675,9 @@ describe("runCLI", () => { mode: S.Enum(["safe", "fast"] as const, { description: "Pick a deployment mode", labels: { safe: "Safe (slow)", fast: "Fast (risky)" } - }), + }) }), - handler, + handler }); const root = defineGroup({ name: "toolcraft", children: [deploy] }); @@ -597,21 +692,23 @@ describe("runCLI", () => { message: "Pick a deployment mode", options: [ { label: "Safe (slow)", value: "safe" }, - { label: "Fast (risky)", value: "fast" }, + { label: "Fast (risky)", value: "fast" } ], - initialValue: undefined, + initialValue: undefined }); }); it("merges preset values before CLI flags and only prompts for still-missing required params", async () => { - const handler = vi.fn(async (ctx: { - params: { - service: string; - region: string; - replicas: number; - mode: "safe" | "fast"; - }; - }) => ctx.params); + const handler = vi.fn( + async (ctx: { + params: { + service: string; + region: string; + replicas: number; + mode: "safe" | "fast"; + }; + }) => ctx.params + ); const deploy = defineCommand({ name: "deploy", @@ -619,22 +716,22 @@ describe("runCLI", () => { service: S.String(), region: S.String(), replicas: S.Number(), - mode: S.Enum(["safe", "fast"] as const), + mode: S.Enum(["safe", "fast"] as const) }), - handler, + handler }); const root = defineGroup({ name: "toolcraft", - children: [deploy], + children: [deploy] }); vol.fromJSON({ "/presets/staging.json": JSON.stringify({ service: "api", region: "us-east-1", - replicas: 1, - }), + replicas: 1 + }) }); promptState.select.mockResolvedValueOnce("fast"); @@ -645,7 +742,7 @@ describe("runCLI", () => { "--preset", "/presets/staging.json", "--replicas", - "5", + "5" ]; await runCLI(root, { presets: true }); @@ -655,16 +752,16 @@ describe("runCLI", () => { message: "mode", options: [ { label: "safe", value: "safe" }, - { label: "fast", value: "fast" }, + { label: "fast", value: "fast" } ], - initialValue: undefined, + initialValue: undefined }); expect(handler).toHaveBeenCalledTimes(1); expect(handler.mock.calls[0]?.[0].params).toEqual({ service: "api", region: "us-east-1", replicas: 5, - mode: "fast", + mode: "fast" }); }); @@ -672,14 +769,14 @@ describe("runCLI", () => { const deploy = defineCommand({ name: "deploy", params: S.Object({ - service: S.String(), + service: S.String() }), - handler: vi.fn(), + handler: vi.fn() }); const root = defineGroup({ name: "toolcraft", - children: [deploy], + children: [deploy] }); process.argv = ["node", "toolcraft", "--help"]; @@ -692,12 +789,11 @@ describe("runCLI", () => { expect(output).toMatchInlineSnapshot(` "toolcraft + Usage: toolcraft [command] [options] + Commands deploy --service approvals Inspect and execute queued approvals. - list [--state ] List queued approvals. - show --approval-id Show one approval. - run --approval-id Run one queued approval. Options --yes Accept defaults, skip prompts @@ -716,14 +812,14 @@ describe("runCLI", () => { const deploy = defineCommand({ name: "deploy", params: S.Object({ - service: S.String(), + service: S.String() }), - handler: vi.fn(), + handler: vi.fn() }); const root = defineGroup({ name: "toolcraft", - children: [deploy], + children: [deploy] }); process.argv = ["node", "toolcraft", "--help"]; @@ -736,12 +832,11 @@ describe("runCLI", () => { expect(output).toMatchInlineSnapshot(` "toolcraft + Usage: toolcraft [command] [options] + Commands deploy --service approvals Inspect and execute queued approvals. - list [--state ] List queued approvals. - show --approval-id Show one approval. - run --approval-id Run one queued approval. Options --preset Load parameter defaults from a JSON file @@ -760,14 +855,14 @@ describe("runCLI", () => { const deploy = defineCommand({ name: "deploy", params: S.Object({ - service: S.String(), + service: S.String() }), - handler: vi.fn(), + handler: vi.fn() }); const root = defineGroup({ name: "toolcraft", - children: [deploy], + children: [deploy] }); process.argv = ["node", "toolcraft", "--help"]; @@ -783,7 +878,7 @@ describe("runCLI", () => { expect({ withPresetAndVersion: withPresetAndVersion.includes("-h, --help"), - withoutPresetOrVersion: withoutPresetOrVersion.includes("-h, --help"), + withoutPresetOrVersion: withoutPresetOrVersion.includes("-h, --help") }).toMatchInlineSnapshot(` { "withPresetAndVersion": false, @@ -798,14 +893,14 @@ describe("runCLI", () => { const deploy = defineCommand({ name: "deploy", params: S.Object({ - preset: S.String(), + preset: S.String() }), - handler, + handler }); const root = defineGroup({ name: "toolcraft", - children: [deploy], + children: [deploy] }); process.argv = ["node", "toolcraft", "deploy", "--preset", "custom", "--yes"]; @@ -814,7 +909,7 @@ describe("runCLI", () => { expect(handler).toHaveBeenCalledTimes(1); expect(handler.mock.calls[0]?.[0].params).toEqual({ - preset: "custom", + preset: "custom" }); }); @@ -824,37 +919,30 @@ describe("runCLI", () => { const deploy = defineCommand({ name: "deploy", params: S.Object({ - service: S.String(), + service: S.String() }), - handler, + handler }); const root = defineGroup({ name: "toolcraft", - children: [deploy], + children: [deploy] }); vol.fromJSON({ "/presets/invalid.json": JSON.stringify({ service: "api", - unknown: "value", - }), + unknown: "value" + }) }); - process.argv = [ - "node", - "toolcraft", - "deploy", - "--preset", - "/presets/invalid.json", - "--yes", - ]; + process.argv = ["node", "toolcraft", "deploy", "--preset", "/presets/invalid.json", "--yes"]; await runCLI(root, { presets: true }); expect(handler).not.toHaveBeenCalled(); expect(loggerState.error).toEqual([ - 'Preset file "/presets/invalid.json" contains unknown parameter "unknown".', + 'Preset file "/presets/invalid.json" contains unknown parameter "unknown".' ]); expect(process.exitCode).toBe(1); }); @@ -866,21 +954,21 @@ describe("runCLI", () => { name: "deploy", params: S.Object({ slug: S.String({ - pattern: "^[a-z]+$", - }), + pattern: "^[a-z]+$" + }) }), - handler, + handler }); const root = defineGroup({ name: "toolcraft", - children: [deploy], + children: [deploy] }); vol.fromJSON({ "/presets/invalid-pattern.json": JSON.stringify({ - slug: "bad-value", - }), + slug: "bad-value" + }) }); process.argv = [ @@ -889,14 +977,14 @@ describe("runCLI", () => { "deploy", "--preset", "/presets/invalid-pattern.json", - "--yes", + "--yes" ]; await runCLI(root, { presets: true }); expect(handler).not.toHaveBeenCalled(); expect(loggerState.error).toEqual([ - 'Preset file "/presets/invalid-pattern.json" has an invalid value for "slug": "bad-value" does not match pattern "^[a-z]+$".', + 'Preset file "/presets/invalid-pattern.json" has an invalid value for "slug": "bad-value" does not match pattern "^[a-z]+$".' ]); expect(process.exitCode).toBe(1); }); @@ -907,31 +995,22 @@ describe("runCLI", () => { const deploy = defineCommand({ name: "deploy", params: S.Object({ - service: S.String(), + service: S.String() }), - handler, + handler }); const root = defineGroup({ name: "toolcraft", - children: [deploy], + children: [deploy] }); - process.argv = [ - "node", - "toolcraft", - "deploy", - "--preset", - "/presets/missing.json", - "--yes", - ]; + process.argv = ["node", "toolcraft", "deploy", "--preset", "/presets/missing.json", "--yes"]; await runCLI(root, { presets: true }); expect(handler).not.toHaveBeenCalled(); - expect(loggerState.error).toEqual([ - 'Preset file "/presets/missing.json" was not found.', - ]); + expect(loggerState.error).toEqual(['Preset file "/presets/missing.json" was not found.']); expect(process.exitCode).toBe(1); }); @@ -941,18 +1020,18 @@ describe("runCLI", () => { const deploy = defineCommand({ name: "deploy", params: S.Object({ - service: S.String(), + service: S.String() }), - handler, + handler }); const root = defineGroup({ name: "toolcraft", - children: [deploy], + children: [deploy] }); vol.fromJSON({ - "/presets/invalid-json.json": "{", + "/presets/invalid-json.json": "{" }); process.argv = [ @@ -961,14 +1040,14 @@ describe("runCLI", () => { "deploy", "--preset", "/presets/invalid-json.json", - "--yes", + "--yes" ]; await runCLI(root, { presets: true }); expect(handler).not.toHaveBeenCalled(); expect(loggerState.error).toEqual([ - 'Preset file "/presets/invalid-json.json" is not valid JSON.', + 'Preset file "/presets/invalid-json.json" is not valid JSON.' ]); expect(process.exitCode).toBe(1); }); @@ -979,28 +1058,21 @@ describe("runCLI", () => { const deploy = defineCommand({ name: "deploy", params: S.Object({ - service: S.String(), + service: S.String() }), - handler, + handler }); const root = defineGroup({ name: "toolcraft", - children: [deploy], + children: [deploy] }); vol.mkdirSync("/presets/directory", { - recursive: true, + recursive: true }); - process.argv = [ - "node", - "toolcraft", - "deploy", - "--preset", - "/presets/directory", - "--yes", - ]; + process.argv = ["node", "toolcraft", "deploy", "--preset", "/presets/directory", "--yes"]; await runCLI(root, { presets: true }); @@ -1017,15 +1089,15 @@ describe("runCLI", () => { name: "deploy", params: S.Object({ name: S.String({ - default: "demo-service", - }), + default: "demo-service" + }) }), - handler, + handler }); const root = defineGroup({ name: "toolcraft", - children: [deploy], + children: [deploy] }); promptState.text.mockResolvedValueOnce(""); @@ -1035,27 +1107,29 @@ describe("runCLI", () => { expect(handler).toHaveBeenCalledTimes(1); expect(handler.mock.calls[0]?.[0].params).toEqual({ - name: "demo-service", + name: "demo-service" }); }); it("skips prompts when stdin is not a TTY and uses defaults", async () => { - const handler = vi.fn(async (ctx: { params: { name: string; optional?: string } }) => ctx.params); + const handler = vi.fn( + async (ctx: { params: { name: string; optional?: string } }) => ctx.params + ); const deploy = defineCommand({ name: "deploy", params: S.Object({ name: S.String({ - default: "demo-service", + default: "demo-service" }), - optional: S.Optional(S.String()), + optional: S.Optional(S.String()) }), - handler, + handler }); const root = defineGroup({ name: "toolcraft", - children: [deploy], + children: [deploy] }); setTTY(process.stdin, false); @@ -1066,7 +1140,7 @@ describe("runCLI", () => { expect(promptState.text).not.toHaveBeenCalled(); expect(promptState.select).not.toHaveBeenCalled(); expect(handler.mock.calls[0]?.[0].params).toEqual({ - name: "demo-service", + name: "demo-service" }); }); @@ -1076,16 +1150,16 @@ describe("runCLI", () => { name: "deploy", params: S.Object({}), handler: async () => ({ - ok: true, + ok: true }), render: { - markdown: () => "rendered markdown", - }, + markdown: () => "rendered markdown" + } }); const root = defineGroup({ name: "toolcraft", - children: [deploy], + children: [deploy] }); process.argv = ["node", "toolcraft", "deploy", "--output", "markdown", "--yes"]; @@ -1099,18 +1173,18 @@ describe("runCLI", () => { { argv: ["node", "toolcraft", "deploy", "--yes"], expected: "terminal", - label: "rich", + label: "rich" }, { argv: ["node", "toolcraft", "deploy", "--output", "md", "--yes"], expected: "markdown", - label: "md", + label: "md" }, { argv: ["node", "toolcraft", "deploy", "--output", "json", "--yes"], expected: "json", - label: "json", - }, + label: "json" + } ])("sets OUTPUT_FORMAT to $expected while running $label output", async ({ argv, expected }) => { const seenOutputFormats: Array = []; const stdoutWrite = vi.spyOn(process.stdout, "write").mockImplementation(() => true); @@ -1120,12 +1194,12 @@ describe("runCLI", () => { handler: async () => { seenOutputFormats.push(process.env.OUTPUT_FORMAT); return null; - }, + } }); const root = defineGroup({ name: "toolcraft", - children: [deploy], + children: [deploy] }); process.argv = argv; @@ -1146,17 +1220,17 @@ describe("runCLI", () => { name: "deploy", params: S.Object({}), handler: async () => ({ - ok: true, + ok: true }), render: { rich: renderRich, - json: renderJson, - }, + json: renderJson + } }); const root = defineGroup({ name: "toolcraft", - children: [deploy], + children: [deploy] }); setTTY(process.stdout, false); @@ -1168,12 +1242,12 @@ describe("runCLI", () => { expect(renderRich).toHaveBeenCalledWith( { - ok: true, + ok: true }, expect.objectContaining({ logger: expect.any(Object), renderTable: expect.any(Function), - getTheme: expect.any(Function), + getTheme: expect.any(Function) }) ); expect(renderJson).not.toHaveBeenCalled(); @@ -1187,20 +1261,20 @@ describe("runCLI", () => { const deploy = defineCommand({ name: "deploy", params: S.Object({ - json: S.Optional(S.Boolean()), + json: S.Optional(S.Boolean()) }), handler: async () => ({ - ok: true, + ok: true }), render: { rich: renderRich, - json: renderJson, - }, + json: renderJson + } }); const root = defineGroup({ name: "toolcraft", - children: [deploy], + children: [deploy] }); process.argv = ["node", "toolcraft", "deploy", "--output", "md", "--json", "--yes"]; @@ -1210,7 +1284,7 @@ describe("runCLI", () => { expect([ renderRich.mock.calls.length, renderJson.mock.calls.length, - readStdout(stdoutWrite), + readStdout(stdoutWrite) ]).toEqual([0, 1, '{\n "ok": true\n}\n']); }); @@ -1218,14 +1292,14 @@ describe("runCLI", () => { const deploy = defineCommand({ name: "deploy", params: S.Object({ - name: S.String(), + name: S.String() }), - handler: async () => null, + handler: async () => null }); const root = defineGroup({ name: "toolcraft", - children: [deploy], + children: [deploy] }); setTTY(process.stdin, false); @@ -1244,12 +1318,12 @@ describe("runCLI", () => { params: S.Object({}), handler: async () => { throw new UserError("Invalid input."); - }, + } }); const root = defineGroup({ name: "toolcraft", - children: [deploy], + children: [deploy] }); process.argv = ["node", "toolcraft", "deploy", "--yes"]; @@ -1269,15 +1343,15 @@ describe("runCLI", () => { secrets: { apiKey: { env: "API_KEY", - description: "Set it in the environment before running this command.", - }, + description: "Set it in the environment before running this command." + } }, - handler, + handler }); const root = defineGroup({ name: "toolcraft", - children: [deploy], + children: [deploy] }); delete process.env.API_KEY; @@ -1288,7 +1362,7 @@ describe("runCLI", () => { expect(handler).not.toHaveBeenCalled(); expect(promptState.text).not.toHaveBeenCalled(); expect(loggerState.error).toEqual([ - "Error: Missing required secret API_KEY\n Set it in the environment before running this command.", + "Error: Missing required secret API_KEY\n Set it in the environment before running this command." ]); expect(process.exitCode).toBe(1); }); @@ -1299,17 +1373,17 @@ describe("runCLI", () => { const deploy = defineCommand({ name: "deploy", params: S.Object({ - name: S.String(), + name: S.String() }), requires: { - auth: true, + auth: true }, - handler, + handler }); const root = defineGroup({ name: "toolcraft", - children: [deploy], + children: [deploy] }); delete process.env.POE_API_KEY; @@ -1320,7 +1394,7 @@ describe("runCLI", () => { expect(handler).not.toHaveBeenCalled(); expect(promptState.text).not.toHaveBeenCalled(); expect(loggerState.error).toEqual([ - `Error: Command "deploy" requires authentication.\n Run 'poe-code login' first.`, + `Error: Command "deploy" requires authentication.\n Run 'poe-code login' first.` ]); expect(process.exitCode).toBe(1); }); @@ -1331,12 +1405,12 @@ describe("runCLI", () => { params: S.Object({}), handler: async () => { throw new Error("Boom."); - }, + } }); const root = defineGroup({ name: "toolcraft", - children: [deploy], + children: [deploy] }); const stderrWrite = vi.spyOn(process.stderr, "write").mockImplementation(() => true); @@ -1364,19 +1438,19 @@ describe("runCLI", () => { const deploy = defineCommand({ name: "deploy", params: S.Object({}), - handler: async () => null, + handler: async () => null }); const root = defineGroup({ name: "toolcraft", - children: [deploy], + children: [deploy] }); await expect( runCLI(root, { services: { - params: "bad", - }, + params: "bad" + } }) ).rejects.toThrow('Service name "params" is reserved. Choose a different name.'); }); @@ -1389,7 +1463,7 @@ describe("runCLI", () => { }), writeValue: vi.fn(async () => { throw new Error("real store write should not be used in fixture mode"); - }), + }) }; process.env.TOOLCRAFT_FIXTURE = "2"; @@ -1397,8 +1471,8 @@ describe("runCLI", () => { await runCLI(fixtureRoot, { services: { - store: realStore, - }, + store: realStore + } }); const payload = JSON.parse(stdoutWrite.mock.calls.map(([chunk]) => String(chunk)).join("")); @@ -1406,13 +1480,13 @@ describe("runCLI", () => { exists: true, file: "named file", matched: { - scenario: "named", + scenario: "named" }, missingFile: null, secret: "fixture-secret", storeValue: null, unmatchedReadStatus: null, - unmatchedWriteStatus: 204, + unmatchedWriteStatus: 204 }); expect(realStore.readValue).not.toHaveBeenCalled(); expect(realStore.writeValue).not.toHaveBeenCalled(); @@ -1428,14 +1502,14 @@ describe("runCLI", () => { services: { store: { readValue: async () => "live value", - writeValue: async () => undefined, - }, - }, + writeValue: async () => undefined + } + } }); const payload = JSON.parse(stdoutWrite.mock.calls.map(([chunk]) => String(chunk)).join("")); expect(payload.matched).toEqual({ - scenario: "named", + scenario: "named" }); expect(payload.file).toBe("named file"); expect(payload.unmatchedReadStatus).toBeNull(); @@ -1446,7 +1520,7 @@ describe("runCLI", () => { const stdoutWrite = vi.spyOn(process.stdout, "write").mockImplementation(() => true); const realStore = { readValue: vi.fn(async () => "live value"), - writeValue: vi.fn(async () => undefined), + writeValue: vi.fn(async () => undefined) }; process.env.TOOLCRAFT_FIXTURE = "no-op fallback"; @@ -1454,8 +1528,8 @@ describe("runCLI", () => { await runCLI(fixtureRoot, { services: { - store: realStore, - }, + store: realStore + } }); const payload = JSON.parse(stdoutWrite.mock.calls.map(([chunk]) => String(chunk)).join("")); @@ -1467,7 +1541,7 @@ describe("runCLI", () => { secret: "fixture-secret", storeValue: null, unmatchedReadStatus: null, - unmatchedWriteStatus: 204, + unmatchedWriteStatus: 204 }); expect(realStore.readValue).not.toHaveBeenCalled(); expect(realStore.writeValue).not.toHaveBeenCalled(); @@ -1483,20 +1557,20 @@ describe("runCLI", () => { discriminator: "kind", branches: { email: S.Object({ - address: S.String(), + address: S.String() }), webhook: S.Object({ - url: S.String(), - }), - }, - }), + url: S.String() + }) + } + }) }), - handler, + handler }); const root = defineGroup({ name: "toolcraft", - children: [send], + children: [send] }); process.argv = [ @@ -1507,7 +1581,7 @@ describe("runCLI", () => { "email", "--destination.address", "alerts@example.com", - "--yes", + "--yes" ]; await runCLI(root); @@ -1517,9 +1591,9 @@ describe("runCLI", () => { params: { destination: { kind: "email", - address: "alerts@example.com", - }, - }, + address: "alerts@example.com" + } + } }) ); }); @@ -1534,20 +1608,20 @@ describe("runCLI", () => { discriminator: "kind", branches: { email: S.Object({ - address: S.String(), + address: S.String() }), webhook: S.Object({ - url: S.String(), - }), - }, - }), + url: S.String() + }) + } + }) }), - handler, + handler }); const root = defineGroup({ name: "toolcraft", - children: [send], + children: [send] }); process.argv = [ @@ -1560,14 +1634,14 @@ describe("runCLI", () => { "alerts@example.com", "--destination.url", "https://example.com/hook", - "--yes", + "--yes" ]; await runCLI(root); expect(handler).not.toHaveBeenCalled(); expect(loggerState.error).toEqual([ - 'Parameter "destination.url" is not valid when "destination.kind" is "email".', + 'Parameter "destination.url" is not valid when "destination.kind" is "email".' ]); expect(process.exitCode).toBe(1); }); @@ -1580,19 +1654,19 @@ describe("runCLI", () => { params: S.Object({ contact: S.Union([ S.Object({ - email: S.String(), + email: S.String() }), S.Object({ - phone: S.String(), - }), - ]), + phone: S.String() + }) + ]) }), - handler, + handler }); const root = defineGroup({ name: "toolcraft", - children: [notify], + children: [notify] }); process.argv = [ @@ -1603,7 +1677,7 @@ describe("runCLI", () => { "email", "--contact.email", "alerts@example.com", - "--yes", + "--yes" ]; await runCLI(root); @@ -1612,9 +1686,9 @@ describe("runCLI", () => { expect.objectContaining({ params: { contact: { - email: "alerts@example.com", - }, - }, + email: "alerts@example.com" + } + } }) ); }); @@ -1627,19 +1701,19 @@ describe("runCLI", () => { params: S.Object({ contact: S.Union([ S.Object({ - email: S.String(), + email: S.String() }), S.Object({ - phone: S.String(), - }), - ]), + phone: S.String() + }) + ]) }), - handler, + handler }); const root = defineGroup({ name: "toolcraft", - children: [notify], + children: [notify] }); process.argv = [ @@ -1650,14 +1724,14 @@ describe("runCLI", () => { "phone", "--contact.email", "alerts@example.com", - "--yes", + "--yes" ]; await runCLI(root); expect(handler).not.toHaveBeenCalled(); expect(loggerState.error).toEqual([ - 'Parameter "contact.email" is not valid when "contact-kind" is "phone".', + 'Parameter "contact.email" is not valid when "contact-kind" is "phone".' ]); expect(process.exitCode).toBe(1); }); @@ -1668,14 +1742,14 @@ describe("runCLI", () => { const configure = defineCommand({ name: "configure", params: S.Object({ - weights: S.Record(S.Number()), + weights: S.Record(S.Number()) }), - handler, + handler }); const root = defineGroup({ name: "toolcraft", - children: [configure], + children: [configure] }); process.argv = [ @@ -1686,7 +1760,7 @@ describe("runCLI", () => { "3", "--weights.secondary", "7", - "--yes", + "--yes" ]; await runCLI(root); @@ -1696,9 +1770,9 @@ describe("runCLI", () => { params: { weights: { primary: 3, - secondary: 7, - }, - }, + secondary: 7 + } + } }) ); }); @@ -1712,16 +1786,16 @@ describe("runCLI", () => { recipients: S.Array( S.Object({ name: S.String(), - email: S.String(), + email: S.String() }) - ), + ) }), - handler, + handler }); const root = defineGroup({ name: "toolcraft", - children: [invite], + children: [invite] }); process.argv = [ @@ -1736,7 +1810,7 @@ describe("runCLI", () => { "Linus", "--recipients.1.email", "linus@example.com", - "--yes", + "--yes" ]; await runCLI(root); @@ -1747,14 +1821,14 @@ describe("runCLI", () => { recipients: [ { name: "Ada", - email: "ada@example.com", + email: "ada@example.com" }, { name: "Linus", - email: "linus@example.com", - }, - ], - }, + email: "linus@example.com" + } + ] + } }) ); }); @@ -1767,32 +1841,25 @@ describe("runCLI", () => { params: S.Object({ recipients: S.Array( S.Object({ - name: S.String(), + name: S.String() }) - ), + ) }), - handler, + handler }); const root = defineGroup({ name: "toolcraft", - children: [invite], + children: [invite] }); - process.argv = [ - "node", - "toolcraft", - "invite", - "--recipients.1.name", - "Linus", - "--yes", - ]; + process.argv = ["node", "toolcraft", "invite", "--recipients.1.name", "Linus", "--yes"]; await runCLI(root); expect(handler).not.toHaveBeenCalled(); expect(loggerState.error).toEqual([ - 'Array parameter "recipients" must use contiguous indices starting at 0.', + 'Array parameter "recipients" must use contiguous indices starting at 0.' ]); expect(process.exitCode).toBe(1); }); @@ -1804,15 +1871,15 @@ describe("runCLI", () => { name: "update", params: S.Object({ nickname: S.String({ - nullable: true, - }), + nullable: true + }) }), - handler, + handler }); const root = defineGroup({ name: "toolcraft", - children: [update], + children: [update] }); process.argv = ["node", "toolcraft", "update", "--nickname=null", "--yes"]; @@ -1822,8 +1889,8 @@ describe("runCLI", () => { expect(handler).toHaveBeenCalledWith( expect.objectContaining({ params: { - nickname: null, - }, + nickname: null + } }) ); }); @@ -1835,15 +1902,15 @@ describe("runCLI", () => { name: "deploy", params: S.Object({ slug: S.String({ - pattern: "^[a-z]+$", - }), + pattern: "^[a-z]+$" + }) }), - handler, + handler }); const root = defineGroup({ name: "toolcraft", - children: [deploy], + children: [deploy] }); process.argv = ["node", "toolcraft", "deploy", "--slug", "bad-value", "--yes"]; @@ -1852,7 +1919,7 @@ describe("runCLI", () => { expect(handler).not.toHaveBeenCalled(); expect(loggerState.error).toEqual([ - 'Invalid value for "slug": "bad-value" does not match pattern "^[a-z]+$".', + 'Invalid value for "slug": "bad-value" does not match pattern "^[a-z]+$".' ]); expect(process.exitCode).toBe(1); }); @@ -1866,17 +1933,17 @@ describe("runCLI", () => { network: S.Object({ database: S.Object({ primary: S.Object({ - host: S.String(), - }), - }), - }), + host: S.String() + }) + }) + }) }), - handler, + handler }); const root = defineGroup({ name: "toolcraft", - children: [connect], + children: [connect] }); process.argv = [ @@ -1885,7 +1952,7 @@ describe("runCLI", () => { "connect", "--network.database.primary.host", "db.internal", - "--yes", + "--yes" ]; await runCLI(root); @@ -1896,11 +1963,11 @@ describe("runCLI", () => { network: { database: { primary: { - host: "db.internal", - }, - }, - }, - }, + host: "db.internal" + } + } + } + } }) ); }); @@ -1911,14 +1978,14 @@ describe("runCLI", () => { const publish = defineCommand({ name: "publish", params: S.Object({ - payload: S.Json(), + payload: S.Json() }), - handler, + handler }); const root = defineGroup({ name: "toolcraft", - children: [publish], + children: [publish] }); process.argv = [ @@ -1927,7 +1994,7 @@ describe("runCLI", () => { "publish", "--payload", '{"topic":"release","meta":{"count":2}}', - "--yes", + "--yes" ]; await runCLI(root); @@ -1938,10 +2005,10 @@ describe("runCLI", () => { payload: { topic: "release", meta: { - count: 2, - }, - }, - }, + count: 2 + } + } + } }) ); }); @@ -1950,17 +2017,17 @@ describe("runCLI", () => { const deploy = defineCommand({ name: "deploy", params: S.Object({}), - handler: async () => null, + handler: async () => null }); const generate = defineGroup({ name: "generate", - children: [deploy], + children: [deploy] }); const root = defineGroup({ name: "poe-code", - children: [generate], + children: [generate] }); process.argv = ["node", "poe-code", "--help"]; @@ -1968,7 +2035,7 @@ describe("runCLI", () => { const stdoutWrite = vi.spyOn(process.stdout, "write").mockImplementation(() => true); await runCLI(root, { - version: "1.2.3", + version: "1.2.3" }); expect(readStdout(stdoutWrite)).toContain("poe-code\n"); @@ -1980,25 +2047,25 @@ describe("runCLI", () => { name: "list-tasks", description: "List tasks", params: S.Object({ - section: S.Optional(S.String()), + section: S.Optional(S.String()) }), - handler: async () => null, + handler: async () => null }); const details = defineCommand({ name: "details", description: "Get task details", params: S.Object({ - taskGid: S.String(), + taskGid: S.String() }), - handler: async () => null, + handler: async () => null }); const asana = defineGroup({ name: "asana", - children: [listTasks, details], + children: [listTasks, details] }); const root = defineGroup({ name: "toolcraft", - children: [asana], + children: [asana] }); process.argv = ["node", "toolcraft", "asana", "--help"]; @@ -2017,13 +2084,13 @@ describe("runCLI", () => { name: "list", description: "List calendar events", params: S.Object({}), - handler: async () => null, + handler: async () => null }); const createMeeting = defineCommand({ name: "create", description: "Create meeting", params: S.Object({}), - handler: async () => null, + handler: async () => null }); const calendar = defineGroup({ name: "calendar", @@ -2031,18 +2098,18 @@ describe("runCLI", () => { children: [ defineGroup({ name: "events", - children: [listEvents], + children: [listEvents] }), defineGroup({ name: "meeting", - children: [createMeeting], - }), - ], + children: [createMeeting] + }) + ] }); const root = defineGroup({ name: "toolcraft", - children: [calendar], + children: [calendar] }); process.argv = ["node", "toolcraft", "--help"]; @@ -2055,12 +2122,12 @@ describe("runCLI", () => { expect(output).toContain("Commands"); expect(output).not.toContain("Commands:"); expect(output).toContain("calendar"); - expect(output).toContain(" events"); - expect(output).toContain(" list"); - expect(output).toContain("List calendar events"); - expect(output).toContain(" meeting"); - expect(output).toContain(" create"); - expect(output).toContain("Create meeting"); + expect(output).not.toContain("\n events"); + expect(output).not.toContain("\n list"); + expect(output).not.toContain("List calendar events"); + expect(output).not.toContain("\n meeting"); + expect(output).not.toContain("\n create"); + expect(output).not.toContain("Create meeting"); }); it("resolves MCP proxy caches from the configured project root", async () => { @@ -2074,11 +2141,11 @@ describe("runCLI", () => { scope: ["cli", "sdk", "mcp"], mcp: { transport: "stdio", - command: "mock-server", + command: "mock-server" }, - children: [], - }), - ], + children: [] + }) + ] }); vol.fromJSON( @@ -2097,11 +2164,11 @@ describe("runCLI", () => { inputSchema: { type: "object", properties: {}, - additionalProperties: false, - }, - }, - ], - }), + additionalProperties: false + } + } + ] + }) }, "/" ); @@ -2119,9 +2186,9 @@ describe("runCLI", () => { defineCommand({ name: "noop", params: S.Object({}), - handler: async () => null, - }), - ], + handler: async () => null + }) + ] }); vol.fromJSON({ @@ -2129,9 +2196,9 @@ describe("runCLI", () => { "/repo/package.json": JSON.stringify({ name: "workspace", version: "0.0.1" }), "/repo/packages/mytool/package.json": JSON.stringify({ name: "mytool", - version: "2.3.4", + version: "2.3.4" }), - "/repo/packages/mytool/dist/bin.js": "", + "/repo/packages/mytool/dist/bin.js": "" }); process.argv = ["node", "/repo/packages/mytool/dist/bin.js", "--version"]; @@ -2143,28 +2210,30 @@ describe("runCLI", () => { }); it("accepts short option flags defined on params", async () => { - const handler = vi.fn(async ({ params }: { params: { session?: string; literal?: boolean } }) => params); + const handler = vi.fn( + async ({ params }: { params: { session?: string; literal?: boolean } }) => params + ); const waitFor = defineCommand({ name: "wait-for", params: S.Object({ session: S.Optional( S.String({ - short: "s", + short: "s" }) ), literal: S.Optional( S.Boolean({ - short: "l", + short: "l" }) - ), + ) }), - handler, + handler }); const root = defineGroup({ name: "toolcraft", - children: [waitFor], + children: [waitFor] }); process.argv = ["node", "toolcraft", "wait-for", "-s", "tests", "-l", "--yes"]; @@ -2175,8 +2244,8 @@ describe("runCLI", () => { expect.objectContaining({ params: { session: "tests", - literal: true, - }, + literal: true + } }) ); }); @@ -2188,15 +2257,15 @@ describe("runCLI", () => { name: "screenshot", params: S.Object({ output: S.String({ - short: "o", - }), + short: "o" + }) }), - handler, + handler }); const root = defineGroup({ name: "toolcraft", - children: [screenshot], + children: [screenshot] }); process.argv = ["node", "toolcraft", "screenshot", "-o", "screen.png", "--yes"]; @@ -2206,28 +2275,30 @@ describe("runCLI", () => { expect(handler).toHaveBeenCalledWith( expect.objectContaining({ params: { - output: "screen.png", - }, + output: "screen.png" + } }) ); }); it("accepts a trailing positional array", async () => { - const handler = vi.fn(async ({ params }: { params: { command: string; args?: string[] } }) => params); + const handler = vi.fn( + async ({ params }: { params: { command: string; args?: string[] } }) => params + ); const createSession = defineCommand({ name: "create-session", positional: ["command", "args"], params: S.Object({ command: S.String(), - args: S.Optional(S.Array(S.String())), + args: S.Optional(S.Array(S.String())) }), - handler, + handler }); const root = defineGroup({ name: "toolcraft", - children: [createSession], + children: [createSession] }); process.argv = ["node", "toolcraft", "create-session", "npm", "test", "--", "--runInBand"]; @@ -2238,8 +2309,8 @@ describe("runCLI", () => { expect.objectContaining({ params: { command: "npm", - args: ["test", "--runInBand"], - }, + args: ["test", "--runInBand"] + } }) ); }); @@ -2252,15 +2323,15 @@ describe("runCLI", () => { positional: ["agent"], params: S.Object({ agent: S.Enum(["claude-code", "codex"], { - default: "claude-code", - }), + default: "claude-code" + }) }), - handler, + handler }); const root = defineGroup({ name: "toolcraft", - children: [install], + children: [install] }); process.argv = ["node", "toolcraft", "install", "--yes"]; @@ -2271,8 +2342,8 @@ describe("runCLI", () => { expect(handler).toHaveBeenCalledWith( expect.objectContaining({ params: { - agent: "claude-code", - }, + agent: "claude-code" + } }) ); }); @@ -2286,15 +2357,15 @@ describe("runCLI", () => { params: S.Object({ agent: S.Enum(["claude-code", "codex"], { default: "claude-code", - description: "Select agent", - }), + description: "Select agent" + }) }), - handler, + handler }); const root = defineGroup({ name: "toolcraft", - children: [install], + children: [install] }); promptState.select.mockResolvedValueOnce("codex"); @@ -2305,14 +2376,14 @@ describe("runCLI", () => { expect(promptState.select).toHaveBeenCalledWith( expect.objectContaining({ message: "Select agent", - initialValue: "claude-code", + initialValue: "claude-code" }) ); expect(handler).toHaveBeenCalledWith( expect.objectContaining({ params: { - agent: "codex", - }, + agent: "codex" + } }) ); }); @@ -2329,11 +2400,11 @@ describe("runCLI", () => { name: "deploy", positional: ["name"], params: S.Object({ - name: S.String(), + name: S.String() }), - handler: deployHandler, - }), - ], + handler: deployHandler + }) + ] }); const terminalPng = defineGroup({ @@ -2343,11 +2414,11 @@ describe("runCLI", () => { name: "render", positional: ["target"], params: S.Object({ - target: S.String(), + target: S.String() }), - handler: renderHandler, - }), - ], + handler: renderHandler + }) + ] }); process.argv = ["node", "poe-code", "terminal-png", "render", "screen.png", "--yes"]; @@ -2357,8 +2428,8 @@ describe("runCLI", () => { expect(renderHandler).toHaveBeenCalledWith( expect.objectContaining({ params: { - target: "screen.png", - }, + target: "screen.png" + } }) ); expect(deployHandler).not.toHaveBeenCalled(); @@ -2371,20 +2442,20 @@ describe("runCLI", () => { name: "run", positional: ["name"], params: S.Object({ - name: S.String(), + name: S.String() }), - handler, + handler }); const githubWorkflows = defineGroup({ name: "github-workflows", children: [run], - default: run, + default: run }); const root = defineGroup({ name: "poe-code", - children: [githubWorkflows], + children: [githubWorkflows] }); process.argv = ["node", "poe-code", "github-workflows", "demo", "--yes"]; @@ -2394,8 +2465,8 @@ describe("runCLI", () => { expect(handler).toHaveBeenCalledWith( expect.objectContaining({ params: { - name: "demo", - }, + name: "demo" + } }) ); }); @@ -2408,29 +2479,29 @@ describe("runCLI", () => { name: "run", positional: ["name"], params: S.Object({ - name: S.String(), + name: S.String() }), - handler: runHandler, + handler: runHandler }); const install = defineCommand({ name: "install", positional: ["name"], params: S.Object({ - name: S.String(), + name: S.String() }), - handler: installHandler, + handler: installHandler }); const githubWorkflows = defineGroup({ name: "github-workflows", children: [run, install], - default: run, + default: run }); const root = defineGroup({ name: "poe-code", - children: [githubWorkflows], + children: [githubWorkflows] }); process.argv = ["node", "poe-code", "github-workflows", "install", "demo", "--yes"]; @@ -2440,8 +2511,8 @@ describe("runCLI", () => { expect(installHandler).toHaveBeenCalledWith( expect.objectContaining({ params: { - name: "demo", - }, + name: "demo" + } }) ); expect(runHandler).not.toHaveBeenCalled(); @@ -2453,14 +2524,14 @@ describe("runCLI", () => { description: "Generate text.", params: S.Object({ prompt: S.String({ - description: "Generation prompt", + description: "Generation prompt" }), model: S.String({ description: "Model identifier", - default: "GPT-4.1", - }), + default: "GPT-4.1" + }) }), - handler: async () => null, + handler: async () => null }); const generate = defineGroup({ @@ -2469,15 +2540,15 @@ describe("runCLI", () => { secrets: { apiKey: { env: "POE_API_KEY", - description: "Inherited from generate group", - }, + description: "Inherited from generate group" + } }, - children: [textCommand], + children: [textCommand] }); const root = defineGroup({ name: "poe-code", - children: [generate], + children: [generate] }); process.argv = ["node", "poe-code", "generate", "text", "--help"]; @@ -2506,51 +2577,53 @@ describe("runCLI", () => { name: "inspect", params: S.Object({ impliedFlag: S.Boolean({ - description: "Implied false flag", + description: "Implied false flag" }), flag: S.Boolean({ description: "Enable flag", - default: false, + default: false }), enabled: S.Boolean({ description: "Enabled by default", - default: true, + default: true }), date: S.String({ description: "Run date", - pattern: "^\\d{4}-\\d{2}-\\d{2}$", + pattern: "^\\d{4}-\\d{2}-\\d{2}$" }), timestamp: S.String({ description: "Run timestamp", - pattern: "^\\d{4}-\\d{2}-\\d{2}T", + pattern: "^\\d{4}-\\d{2}-\\d{2}T" }), callbackUrl: S.String({ description: "Callback URL", - format: "uri", + format: "uri" }), userEmail: S.String({ description: "User email", - format: "email", + format: "email" }), - reportFiles: S.Array(S.String({ - description: "Report files", - })), + reportFiles: S.Array( + S.String({ + description: "Report files" + }) + ), configPath: S.String({ - description: "Config path", + description: "Config path" }), token: S.String({ - description: "Token value", + description: "Token value" }), retries: S.Number({ - description: "Retry count", - }), + description: "Retry count" + }) }), - handler: async () => null, + handler: async () => null }); const root = defineGroup({ name: "toolcraft", - children: [inspect], + children: [inspect] }); process.argv = ["node", "toolcraft", "inspect", "--help"]; @@ -2580,18 +2653,18 @@ describe("runCLI", () => { name: "inspect", params: S.Object({ configPath: S.String({ - description: "Config path", + description: "Config path" }), ownerEmail: S.String({ - description: "Owner email", - }), + description: "Owner email" + }) }), - handler: async () => null, + handler: async () => null }); const root = defineGroup({ name: "toolcraft", - children: [inspect], + children: [inspect] }); process.argv = ["node", "toolcraft", "inspect", "--help"]; @@ -2614,36 +2687,36 @@ describe("runCLI", () => { discriminator: "kind", branches: { email: S.Object({ - address: S.String(), + address: S.String() }), webhook: S.Object({ - url: S.String(), - }), - }, + url: S.String() + }) + } }), contact: S.Union([ S.Object({ - email: S.String(), + email: S.String() }), S.Object({ - phone: S.String(), - }), + phone: S.String() + }) ]), weights: S.Record(S.Number()), recipients: S.Array( S.Object({ name: S.String(), - email: S.String(), + email: S.String() }) ), - payload: S.Json(), + payload: S.Json() }), - handler: async () => null, + handler: async () => null }); const root = defineGroup({ name: "toolcraft", - children: [publish], + children: [publish] }); process.argv = ["node", "toolcraft", "publish", "--help"]; @@ -2670,25 +2743,25 @@ describe("runCLI", () => { name: "text", description: "Generate text", params: S.Object({}), - handler: async () => null, + handler: async () => null }); const hiddenCommand = defineCommand({ name: "invoke", description: "Internal SDK helper", params: S.Object({}), scope: ["sdk"], - handler: async () => null, + handler: async () => null }); const generate = defineGroup({ name: "generate", description: "Generate content via Poe API.", - children: [visibleCommand, hiddenCommand], + children: [visibleCommand, hiddenCommand] }); const root = defineGroup({ name: "poe-code", - children: [generate], + children: [generate] }); process.argv = ["node", "poe-code", "generate", "--help"]; @@ -2708,12 +2781,12 @@ describe("runCLI", () => { const builder = defineGroup({ name: "builder", description: "Builder commands.", - children: [], + children: [] }); const root = defineGroup({ name: "poe-code", - children: [builder], + children: [builder] }); process.argv = ["node", "poe-code", "--help"]; @@ -2732,12 +2805,12 @@ describe("runCLI", () => { const builder = defineGroup({ name: "builder", description: "Builder commands.", - children: [], + children: [] }); const root = defineGroup({ name: "poe-code", - children: [builder], + children: [builder] }); process.argv = ["node", "poe-code", "builder", "--help"]; @@ -2754,11 +2827,11 @@ describe("runCLI", () => { it("falls back to toolcraft as the program name when mounting multiple roots without an entrypoint", async () => { const first = defineGroup({ name: "first", - children: [], + children: [] }); const second = defineGroup({ name: "second", - children: [], + children: [] }); process.argv = ["node", "", "--help"]; @@ -2769,4 +2842,286 @@ describe("runCLI", () => { expect(readStdout(stdoutWrite)).toContain("toolcraft\n"); }); + + it("renders a blank-named root group with inferred heading and usage", async () => { + setStdoutColumns(100); + const root = defineGroup({ + name: "", + description: "X", + children: [ + defineCommand({ + name: "deploy", + params: S.Object({}), + handler: async () => null + }) + ] + }); + + process.argv = ["node", "/usr/local/bin/poe-code", "--help"]; + + const stdoutWrite = vi.spyOn(process.stdout, "write").mockImplementation(() => true); + + await runCLI(root); + + expect(readStdout(stdoutWrite)).toMatchInlineSnapshot(` + "poe-code — X + + Usage: poe-code [command] [options] + + Commands + deploy + approvals Inspect and execute queued approvals. + + Options + --yes Accept defaults, skip prompts + --output Output format: rich, md, json. + " + `); + }); + + it("renders two-level group help with full heading and usage", async () => { + setStdoutColumns(100); + const child = defineGroup({ + name: "child", + description: "desc", + children: [] + }); + const parent = defineGroup({ + name: "parent", + children: [child] + }); + const root = defineGroup({ + name: "", + children: [parent] + }); + + process.argv = ["node", "/opt/bin/poe-code", "parent", "child", "--help"]; + + const stdoutWrite = vi.spyOn(process.stdout, "write").mockImplementation(() => true); + + await runCLI(root); + + expect(readStdout(stdoutWrite)).toMatchInlineSnapshot(` + "parent child — desc + + Usage: poe-code parent child [command] [options] + + Options + --yes Accept defaults, skip prompts + --output Output format: rich, md, json. + " + `); + }); + + it("always renders usage lines at every help level with argv-derived root usage", async () => { + setStdoutColumns(100); + const leaf = defineCommand({ + name: "leaf", + positional: ["target"], + params: S.Object({ + target: S.String() + }), + handler: async () => null + }); + const group = defineGroup({ + name: "group", + children: [leaf] + }); + const root = defineGroup({ + name: "", + children: [group] + }); + + const stdoutWrite = vi.spyOn(process.stdout, "write").mockImplementation(() => true); + + process.argv = ["node", "/repo/bin/custom-cli", "--help"]; + await runCLI(root); + const rootHelp = readStdout(stdoutWrite); + + stdoutWrite.mockClear(); + process.argv = ["node", "/repo/bin/custom-cli", "group", "--help"]; + await runCLI(root); + const groupHelp = readStdout(stdoutWrite); + + stdoutWrite.mockClear(); + process.argv = ["node", "/repo/bin/custom-cli", "group", "leaf", "--help"]; + await runCLI(root); + const leafHelp = readStdout(stdoutWrite); + + expect({ + root: rootHelp.split("\n").find((line) => line.startsWith("Usage:")), + group: groupHelp.split("\n").find((line) => line.startsWith("Usage:")), + leaf: leafHelp.split("\n").find((line) => line.startsWith("Usage:")) + }).toMatchInlineSnapshot(` + { + "group": "Usage: custom-cli group [command] [options]", + "leaf": "Usage: custom-cli group leaf [options] ", + "root": "Usage: custom-cli [command] [options]", + } + `); + }); + + it("lists only direct children in a group commands section", async () => { + setStdoutColumns(100); + const grandchild = defineCommand({ + name: "grandchild", + description: "Nested leaf", + params: S.Object({}), + handler: async () => null + }); + const child = defineGroup({ + name: "child", + description: "Child group", + children: [grandchild] + }); + const sibling = defineCommand({ + name: "sibling", + description: "Sibling leaf", + params: S.Object({}), + handler: async () => null + }); + const root = defineGroup({ + name: "toolcraft", + children: [child, sibling] + }); + + process.argv = ["node", "toolcraft", "--help"]; + + const stdoutWrite = vi.spyOn(process.stdout, "write").mockImplementation(() => true); + + await runCLI(root); + + expect(readStdout(stdoutWrite)).toMatchInlineSnapshot(` + "toolcraft + + Usage: toolcraft [command] [options] + + Commands + child Child group + sibling Sibling leaf + approvals Inspect and execute queued approvals. + + Options + --yes Accept defaults, skip prompts + --output Output format: rich, md, json. + " + `); + }); + + it("splits a multi-sentence leaf description between heading and paragraph", async () => { + setStdoutColumns(100); + const inspect = defineCommand({ + name: "inspect", + description: "First sentence. Second sentence explains more.", + params: S.Object({}), + handler: async () => null + }); + const root = defineGroup({ + name: "toolcraft", + children: [inspect] + }); + + process.argv = ["node", "toolcraft", "inspect", "--help"]; + + const stdoutWrite = vi.spyOn(process.stdout, "write").mockImplementation(() => true); + + await runCLI(root); + + expect(readStdout(stdoutWrite)).toMatchInlineSnapshot(` + "toolcraft inspect — First sentence. + + Second sentence explains more. + + Usage: toolcraft inspect [options] + + Options + --yes Accept defaults, skip prompts + --output Output format: rich, md, json. + " + `); + }); + + it("wraps help descriptions at narrow terminal widths", async () => { + setStdoutColumns(60); + const scan = defineCommand({ + name: "scan", + description: "Scan repositories and summarize changes.", + params: S.Object({ + repositoryPath: S.String({ + description: + "Repository path with a deliberately long explanation that wraps in narrow terminals" + }) + }), + handler: async () => null + }); + const root = defineGroup({ + name: "toolcraft", + description: "Developer automation commands.", + children: [scan] + }); + + process.argv = ["node", "toolcraft", "--help"]; + + const stdoutWrite = vi.spyOn(process.stdout, "write").mockImplementation(() => true); + + await runCLI(root); + + expect(readStdout(stdoutWrite)).toMatchInlineSnapshot(` + "toolcraft — Developer automation commands. + + Usage: toolcraft [command] [options] + + Commands + scan --repository-path Scan repositories and + summarize changes. + approvals Inspect and execute queued + approvals. + + Options + --yes Accept defaults, skip prompts + --output Output format: rich, md, json. + " + `); + }); + + it("uses plain help formatting when stdout is not a TTY", async () => { + setStdoutColumns(100); + setTTY(process.stdout, false); + const root = defineGroup({ + name: "toolcraft", + children: [ + defineCommand({ + name: "deploy", + description: "Deploy a service", + params: S.Object({}), + handler: async () => null + }) + ] + }); + + process.argv = ["node", "toolcraft", "--help"]; + + const stdoutWrite = vi.spyOn(process.stdout, "write").mockImplementation(() => true); + + await runCLI(root); + + const output = readStdout(stdoutWrite); + expect(output).toMatchInlineSnapshot(` + "toolcraft + + Usage: toolcraft [command] [options] + + Commands + deploy Deploy a service + approvals Inspect and execute queued approvals. + + Options + --yes Accept defaults, skip prompts + --output Output format: rich, md, json. + " + `); + expect(formatterState.plainCommandListCalls).toBeGreaterThan(0); + expect(formatterState.plainOptionListCalls).toBeGreaterThan(0); + expect(output).not.toContain("\u001b["); + }); }); diff --git a/packages/toolcraft/src/cli.ts b/packages/toolcraft/src/cli.ts index b1e0ef8114..6a304e866f 100644 --- a/packages/toolcraft/src/cli.ts +++ b/packages/toolcraft/src/cli.ts @@ -1,13 +1,18 @@ import { access, readFile, writeFile } from "node:fs/promises"; import path from "node:path"; -import { Command as CommanderCommand, CommanderError, InvalidArgumentError, Option } from "commander"; +import { + Command as CommanderCommand, + CommanderError, + InvalidArgumentError, + Option +} from "commander"; import type { AnySchema, ArraySchema, EnumSchema, JsonValueSchema, ObjectSchema, - RecordSchema, + RecordSchema } from "toolcraft-schema"; import { cancel, @@ -16,13 +21,14 @@ import { formatCommandList, formatOptionList, getTheme, + helpFormatterPlain, isCancel, note, promptText, renderTable, resetOutputFormatCache, select, - text, + text } from "@poe-code/design-system"; import type { Command, @@ -33,9 +39,15 @@ import type { HandlerFs, SecretDeclarations, SecretDefinition, - Scope, + Scope +} from "./index.js"; +import { + ApprovalDeclinedError, + UserError, + assertCommandRequirements, + getCommandSourcePath, + resolveCommandSecrets } from "./index.js"; -import { ApprovalDeclinedError, UserError, assertCommandRequirements, getCommandSourcePath, resolveCommandSecrets } from "./index.js"; import { mergeApprovalsGroup } from "./human-in-loop/approvals-commands.js"; import { invokeWithHumanInLoop } from "./human-in-loop/index.js"; import type { HumanInLoopPending, HumanInLoopRuntimeOptions } from "./human-in-loop/index.js"; @@ -215,7 +227,7 @@ function normalizeRoots( name: inferProgramName(argv), aliases: [], secrets: {}, - children: roots, + children: roots }; } @@ -250,8 +262,12 @@ function splitWords(value: string): string[] { const isUppercase = char !== lower && char === upper; const previous = value[index - 1]; const next = value[index + 1]; - const previousIsLowercase = previous !== undefined && previous === previous.toLowerCase() && previous !== previous.toUpperCase(); - const nextIsLowercase = next !== undefined && next === next.toLowerCase() && next !== next.toUpperCase(); + const previousIsLowercase = + previous !== undefined && + previous === previous.toLowerCase() && + previous !== previous.toUpperCase(); + const nextIsLowercase = + next !== undefined && next === next.toLowerCase() && next !== next.toUpperCase(); if (isUppercase && current.length > 0 && (previousIsLowercase || nextIsLowercase)) { words.push(current.toLowerCase()); @@ -328,7 +344,7 @@ function createSyntheticEnumSchema(values: string[]): EnumSchema<[string, ...str return { kind: "enum", - values: values as [string, ...string[]], + values: values as [string, ...string[]] }; } @@ -355,17 +371,25 @@ function collectFields( const collected: CollectedCliSchema = { dynamicFields: [], fields: [], - variants: [], + variants: [] }; for (const [key, rawChildSchema] of Object.entries(schema.shape) as Array<[string, AnySchema]>) { const nextPath = [...path, key]; const runtimeOptional = inheritedOptional || rawChildSchema.kind === "optional"; const childSchema = unwrapOptional(rawChildSchema); - const requiredWhenActive = rawChildSchema.kind !== "optional" && childSchema.default === undefined; + const requiredWhenActive = + rawChildSchema.kind !== "optional" && childSchema.default === undefined; if (childSchema.kind === "object") { - const nested = collectFields(childSchema, casing, globalLongOptionFlags, nextPath, runtimeOptional, variantContext); + const nested = collectFields( + childSchema, + casing, + globalLongOptionFlags, + nextPath, + runtimeOptional, + variantContext + ); collected.dynamicFields.push(...nested.dynamicFields); collected.fields.push(...nested.fields); collected.variants.push(...nested.variants); @@ -380,7 +404,11 @@ function collectFields( path: [...nextPath, childSchema.discriminator], displayPath: toDisplayPath([...nextPath, childSchema.discriminator]), optionAttribute: toOptionAttribute([...nextPath, childSchema.discriminator], casing), - commanderOptionAttribute: toCommanderOptionAttribute([...nextPath, childSchema.discriminator], casing, globalLongOptionFlags), + commanderOptionAttribute: toCommanderOptionAttribute( + [...nextPath, childSchema.discriminator], + casing, + globalLongOptionFlags + ), optionFlag: toOptionFlag([...nextPath, childSchema.discriminator], casing), shortFlag: undefined, schema: createSyntheticEnumSchema(branchIds), @@ -388,7 +416,7 @@ function collectFields( optional: runtimeOptional, hasDefault: false, defaultValue: undefined, - requiredWhenActive, + requiredWhenActive }; collected.fields.push(controlField); @@ -397,7 +425,7 @@ function collectFields( for (const [branchId, branchSchema] of Object.entries(childSchema.branches)) { const branch = collectFields(branchSchema, casing, globalLongOptionFlags, nextPath, true, { id: variantId, - branchId, + branchId }); collected.dynamicFields.push(...branch.dynamicFields); collected.fields.push(...branch.fields); @@ -411,7 +439,7 @@ function collectFields( .map((field) => field.id), requiredFieldIds: branch.fields .filter((field) => field.requiredWhenActive) - .map((field) => field.id), + .map((field) => field.id) }); } @@ -420,7 +448,7 @@ function collectFields( controlDisplayPath: controlField.displayPath, controlFieldId: controlField.id, optional: runtimeOptional, - branches, + branches }); continue; } @@ -429,13 +457,19 @@ function collectFields( const variantId = `${toDisplayPath(nextPath)}:union`; const controlPath = toUnionKindControlPath(nextPath); const controlDisplayPath = toUnionKindDisplayPath(nextPath); - const branchIds = childSchema.branches.map((branch) => getRequiredBranchFingerprint(branch, casing)); + const branchIds = childSchema.branches.map((branch) => + getRequiredBranchFingerprint(branch, casing) + ); const controlField: FieldDefinition = { id: controlDisplayPath, path: controlPath, displayPath: controlDisplayPath, optionAttribute: toOptionAttribute(controlPath, casing), - commanderOptionAttribute: toCommanderOptionAttribute(controlPath, casing, globalLongOptionFlags), + commanderOptionAttribute: toCommanderOptionAttribute( + controlPath, + casing, + globalLongOptionFlags + ), optionFlag: toOptionFlag(controlPath, casing), shortFlag: undefined, schema: createSyntheticEnumSchema(branchIds), @@ -444,7 +478,7 @@ function collectFields( hasDefault: false, defaultValue: undefined, requiredWhenActive, - synthetic: true, + synthetic: true }; collected.fields.push(controlField); @@ -454,7 +488,7 @@ function collectFields( const branchId = branchIds[index] ?? ""; const branch = collectFields(branchSchema, casing, globalLongOptionFlags, nextPath, true, { id: variantId, - branchId, + branchId }); collected.dynamicFields.push(...branch.dynamicFields); collected.fields.push(...branch.fields); @@ -468,7 +502,7 @@ function collectFields( .map((field) => field.id), requiredFieldIds: branch.fields .filter((field) => field.requiredWhenActive) - .map((field) => field.id), + .map((field) => field.id) }); }); @@ -477,7 +511,7 @@ function collectFields( controlDisplayPath, controlFieldId: controlField.id, optional: runtimeOptional, - branches, + branches }); continue; } @@ -497,7 +531,7 @@ function collectFields( requiredWhenActive, schema: childSchema, variantId: variantContext?.id, - variantBranchId: variantContext?.branchId, + variantBranchId: variantContext?.branchId }); continue; } @@ -517,7 +551,7 @@ function collectFields( requiredWhenActive, schema: childSchema as ArraySchema>, variantId: variantContext?.id, - variantBranchId: variantContext?.branchId, + variantBranchId: variantContext?.branchId }); continue; } @@ -537,7 +571,7 @@ function collectFields( defaultValue: childSchema.default, requiredWhenActive, variantId: variantContext?.id, - variantBranchId: variantContext?.branchId, + variantBranchId: variantContext?.branchId }); } @@ -593,7 +627,10 @@ function assignPositionals(fields: FieldDefinition[], positional: string[]): Fie return fields; } -function formatOptionFlags(field: FieldDefinition, globalLongOptionFlags: ReadonlySet): string { +function formatOptionFlags( + field: FieldDefinition, + globalLongOptionFlags: ReadonlySet +): string { const collidesWithGlobalFlag = globalLongOptionFlags.has(field.optionFlag); if (collidesWithGlobalFlag) { @@ -637,7 +674,11 @@ function parseBooleanText(value: string, label: string): boolean { throw new InvalidArgumentError(`Invalid value for "${label}". Expected true or false.`); } -function parseEnumValue(value: string, values: ReadonlyArray, label: string): string | number | boolean { +function parseEnumValue( + value: string, + values: ReadonlyArray, + label: string +): string | number | boolean { const match = values.find((candidate) => String(candidate) === value); if (match === undefined) { @@ -649,7 +690,11 @@ function parseEnumValue(value: string, values: ReadonlyArray, label: string): string { +function validateStringPattern( + value: string, + schema: Extract, + label: string +): string { if (schema.pattern === undefined) { return value; } @@ -679,7 +724,11 @@ function normalizeCommanderOptionValue(value: unknown): unknown { return value === NULL_OPTION_VALUE ? null : value; } -function parseScalarValue(value: string, schema: ScalarSchema, label: string): string | number | boolean { +function parseScalarValue( + value: string, + schema: ScalarSchema, + label: string +): string | number | boolean { if (value === "null" && schema.nullable === true) { return null as unknown as string | number | boolean; } @@ -703,7 +752,6 @@ function parseScalarValue(value: string, schema: ScalarSchema, label: string): s case "enum": return parseEnumValue(value, schema.values, label); - } throw new UserError("Unsupported CLI schema kind."); @@ -747,10 +795,15 @@ function parseArrayValue(value: string, schema: ArraySchema, label: string) throw new UserError(`Array parameter "${label}" must use scalar items.`); } - return splitArrayInput(value).map((item) => parseScalarValue(item, itemSchema as ScalarSchema, label)); + return splitArrayInput(value).map((item) => + parseScalarValue(item, itemSchema as ScalarSchema, label) + ); } -function createOption(field: FieldDefinition, globalLongOptionFlags: ReadonlySet): Option[] { +function createOption( + field: FieldDefinition, + globalLongOptionFlags: ReadonlySet +): Option[] { const flags = formatOptionFlags(field, globalLongOptionFlags); const collidesWithGlobalFlag = globalLongOptionFlags.has(field.optionFlag); const commanderValue = (value: unknown): unknown => (value === null ? NULL_OPTION_VALUE : value); @@ -764,12 +817,14 @@ function createOption(field: FieldDefinition, globalLongOptionFlags: ReadonlySet mainOption.preset(true); // Commander v14 passes the preset value through argParser too, so guard with typeof check mainOption.argParser((value: string | boolean) => - typeof value === "boolean" ? value : commanderValue(parseBooleanText(value, field.displayPath)) + typeof value === "boolean" + ? value + : commanderValue(parseBooleanText(value, field.displayPath)) ); return [ mainOption, - createCommanderOption(`--no-${field.optionFlag.slice(2)}`, field.description, field), + createCommanderOption(`--no-${field.optionFlag.slice(2)}`, field.description, field) ]; } @@ -777,28 +832,35 @@ function createOption(field: FieldDefinition, globalLongOptionFlags: ReadonlySet return [ createCommanderOption(`${flags} `, field.description, field).argParser( (value: string, previous: unknown[] | null = []) => { - const parsed = parseArrayValue(value, field.schema as ArraySchema, field.displayPath); + const parsed = parseArrayValue( + value, + field.schema as ArraySchema, + field.displayPath + ); if (parsed === null) { return NULL_OPTION_VALUE as unknown as null; } return [...(previous ?? []), ...parsed]; } - ), + ) ]; } if (field.schema.kind === "json") { return [ - createCommanderOption(`${flags} `, field.description, field).argParser((value: string) => - commanderValue(parseJsonText(value, field.displayPath)) - ), + createCommanderOption(`${flags} `, field.description, field).argParser( + (value: string) => commanderValue(parseJsonText(value, field.displayPath)) + ) ]; } const option = createCommanderOption(`${flags} `, field.description, field); - if (field.schema.kind === "enum" && field.schema.values.every((value) => typeof value === "string")) { + if ( + field.schema.kind === "enum" && + field.schema.values.every((value) => typeof value === "string") + ) { option.choices([...field.schema.values] as string[]); } @@ -811,7 +873,11 @@ function createOption(field: FieldDefinition, globalLongOptionFlags: ReadonlySet const ALWAYS_GLOBAL_LONG_OPTION_FLAGS = ["--yes", "--output", "--verbose"] as const; function getGlobalLongOptionFlags(presetsEnabled: boolean): ReadonlySet { - return new Set(presetsEnabled ? ["--preset", ...ALWAYS_GLOBAL_LONG_OPTION_FLAGS] : ALWAYS_GLOBAL_LONG_OPTION_FLAGS); + return new Set( + presetsEnabled + ? ["--preset", ...ALWAYS_GLOBAL_LONG_OPTION_FLAGS] + : ALWAYS_GLOBAL_LONG_OPTION_FLAGS + ); } function createCommanderOption( @@ -877,7 +943,10 @@ function isNodeVisibleInScope( ); } -function getVisibleChildren(group: Group, scope: Scope): Array | Group> { +function getVisibleChildren( + group: Group, + scope: Scope +): Array | Group> { return group.children.filter((child) => isNodeVisibleInScope(child, scope)); } @@ -909,11 +978,8 @@ function resolveHelpTarget( break; } - const child: Command | Group | undefined = findVisibleChild( - current, - token, - scope - ); + const child: Command | Group | undefined = + findVisibleChild(current, token, scope); if (child === undefined) { break; } @@ -924,11 +990,14 @@ function resolveHelpTarget( return { breadcrumb, - node: current, + node: current }; } -function formatHelpFieldFlags(field: FieldDefinition, globalLongOptionFlags: ReadonlySet): string { +function formatHelpFieldFlags( + field: FieldDefinition, + globalLongOptionFlags: ReadonlySet +): string { if (field.positionalIndex !== undefined) { return formatPositionalToken(field); } @@ -941,10 +1010,13 @@ function formatHelpFieldFlags(field: FieldDefinition, globalLongOptionFlags: Rea return formatOptionFlags(field, globalLongOptionFlags); } - return `${formatOptionFlags(field, globalLongOptionFlags)} <${describeHelpValueToken(field.schema, { - displayPath: field.displayPath, - optionFlag: field.optionFlag, - })}>`; + return `${formatOptionFlags(field, globalLongOptionFlags)} <${describeHelpValueToken( + field.schema, + { + displayPath: field.displayPath, + optionFlag: field.optionFlag + } + )}>`; } function appendHelpMetadata(description: string, metadata: string[]): string { @@ -1042,7 +1114,7 @@ function describeFieldNameValueToken(displayPath: string, optionFlag: string): s ["Url", "url"], ["Email", "email"], ["Name", "name"], - ["Id", "id"], + ["Id", "id"] ] as const; for (const [suffix, token] of suffixTokens) { @@ -1076,7 +1148,8 @@ function describeHelpValueToken( } if (schema.kind === "string") { - const metadataToken = describeKnownStringFormat(schema.format) ?? describeKnownStringPattern(schema.pattern); + const metadataToken = + describeKnownStringFormat(schema.format) ?? describeKnownStringPattern(schema.pattern); if (metadataToken !== undefined) { return metadataToken; @@ -1101,7 +1174,7 @@ function describeDynamicFieldType(field: DynamicFieldDefinition): string { if (valueSchema.kind === "array") { return describeHelpValueToken(valueSchema as FieldSchema, { displayPath: field.optionPathDisplay, - optionFlag: field.optionFlag, + optionFlag: field.optionFlag }); } @@ -1111,7 +1184,7 @@ function describeDynamicFieldType(field: DynamicFieldDefinition): string { return describeHelpValueToken(valueSchema as FieldSchema, { displayPath: field.optionPathDisplay, - optionFlag: field.optionFlag, + optionFlag: field.optionFlag }); } @@ -1148,7 +1221,9 @@ function collectDynamicObjectHelpRows( const description = childSchema.description ?? displayPath; if (childSchema.kind === "object") { - rows.push(...collectDynamicObjectHelpRows(childSchema, casing, optionFlag, displayPath, metadata)); + rows.push( + ...collectDynamicObjectHelpRows(childSchema, casing, optionFlag, displayPath, metadata) + ); continue; } @@ -1166,10 +1241,10 @@ function collectDynamicObjectHelpRows( hasDefault: false, defaultValue: undefined, requiredWhenActive: false, - schema: childSchema, - } satisfies DynamicFieldDefinition), + schema: childSchema + } satisfies DynamicFieldDefinition) })}>`, - description: appendHelpMetadata(description, metadata), + description: appendHelpMetadata(description, metadata) }); continue; } @@ -1194,10 +1269,10 @@ function collectDynamicObjectHelpRows( ? `--no-${optionFlag.slice(2)}` : optionFlag : `${optionFlag} <${describeHelpValueToken(childSchema as FieldSchema, { - displayPath, - optionFlag, - })}>`, - description: appendHelpMetadata(description, metadata), + displayPath, + optionFlag + })}>`, + description: appendHelpMetadata(description, metadata) }); } @@ -1233,16 +1308,18 @@ function formatDynamicHelpFields(field: DynamicFieldDefinition, casing: Casing): } } - return [{ - flags: `${field.optionFlag} <${describeDynamicFieldType(field)}>`, - description: appendHelpMetadata(field.description ?? field.optionPathDisplay, metadata), - }]; + return [ + { + flags: `${field.optionFlag} <${describeDynamicFieldType(field)}>`, + description: appendHelpMetadata(field.description ?? field.optionPathDisplay, metadata) + } + ]; } function formatSecretRows(secrets: SecretDeclarations): HelpOptionRow[] { return Object.values(secrets).map((secret) => ({ flags: secret.env, - description: formatSecretDescription(secret), + description: formatSecretDescription(secret) })); } @@ -1258,7 +1335,10 @@ function wrapOptionalCommandParameterToken(token: string, optional: boolean): st return optional ? `[${token}]` : token; } -function formatCommandDynamicParameterTokens(field: DynamicFieldDefinition, casing: Casing): string[] { +function formatCommandDynamicParameterTokens( + field: DynamicFieldDefinition, + casing: Casing +): string[] { const optional = field.optional || field.hasDefault; return formatDynamicHelpFields(field, casing).map((row) => wrapOptionalCommandParameterToken(row.flags, optional) @@ -1280,41 +1360,36 @@ function formatCommandParameterTokens( field.positionalIndex === undefined && (field.optional || field.hasDefault) ) ) - .concat(collected.dynamicFields.flatMap((field) => formatCommandDynamicParameterTokens(field, casing))); + .concat( + collected.dynamicFields.flatMap((field) => formatCommandDynamicParameterTokens(field, casing)) + ); } function formatCommandRowName( node: Command | Group, - depth: number, casing: Casing, globalLongOptionFlags: ReadonlySet ): string { - const baseName = node.aliases.length === 0 ? node.name : `${node.name} (${node.aliases.join(", ")})`; + const baseName = + node.aliases.length === 0 ? node.name : `${node.name} (${node.aliases.join(", ")})`; const parameterTokens = - node.kind === "command" ? formatCommandParameterTokens(node, casing, globalLongOptionFlags) : []; + node.kind === "command" + ? formatCommandParameterTokens(node, casing, globalLongOptionFlags) + : []; const name = parameterTokens.length === 0 ? baseName : `${baseName} ${parameterTokens.join(" ")}`; - return `${" ".repeat(depth)}${name}`; + return name; } function formatCommandRows( group: Group, scope: Scope, casing: Casing, - globalLongOptionFlags: ReadonlySet, - depth = 0 + globalLongOptionFlags: ReadonlySet ): HelpCommandRow[] { - return getVisibleChildren(group, scope).flatMap((child) => { - const row = { - name: formatCommandRowName(child, depth, casing, globalLongOptionFlags), - description: child.description ?? "", - }; - - if (child.kind === "command") { - return [row]; - } - - return [row, ...formatCommandRows(child, scope, casing, globalLongOptionFlags, depth + 1)]; - }); + return getVisibleChildren(group, scope).map((child) => ({ + name: formatCommandRowName(child, casing, globalLongOptionFlags), + description: child.description ?? "" + })); } function formatGlobalOptionRows(ctx: { @@ -1326,25 +1401,25 @@ function formatGlobalOptionRows(ctx: { if (ctx.presetsEnabled) { rows.push({ flags: "--preset ", - description: "Load parameter defaults from a JSON file", + description: "Load parameter defaults from a JSON file" }); } rows.push( { flags: "--yes", - description: "Accept defaults, skip prompts", + description: "Accept defaults, skip prompts" }, { flags: "--output ", - description: "Output format: rich, md, json.", + description: "Output format: rich, md, json." } ); if (ctx.showVersion) { rows.push({ flags: "--version", - description: "Show version", + description: "Show version" }); } @@ -1355,12 +1430,25 @@ function renderHelpSections(sections: string[]): string { return sections.filter((section) => section.length > 0).join("\n\n"); } -function buildUsageLine(breadcrumb: string[], rootUsageName: string | undefined, suffix: string): string | undefined { - if (rootUsageName === undefined) { - return undefined; - } - const subPath = breadcrumb.slice(1).join(" "); - return subPath ? `${rootUsageName} ${subPath} ${suffix}` : `${rootUsageName} ${suffix}`; +function formatHelpCommandList(rows: HelpCommandRow[]): string { + return process.stdout.isTTY === false + ? helpFormatterPlain.formatCommandList(rows) + : formatCommandList(rows); +} + +function formatHelpOptionList(rows: HelpOptionRow[]): string { + return process.stdout.isTTY === false + ? helpFormatterPlain.formatOptionList(rows) + : formatOptionList(rows); +} + +function buildUsageLine(breadcrumb: string[], rootUsageName: string, suffix: string): string { + const visibleBreadcrumb = breadcrumb.filter((segment) => segment.length > 0); + const usageBreadcrumb = + breadcrumb[0] === "" ? [rootUsageName, ...visibleBreadcrumb] : visibleBreadcrumb; + const subPath = usageBreadcrumb.slice(1).join(" "); + const tokens = [rootUsageName, subPath, suffix].filter((segment) => segment.length > 0); + return tokens.join(" "); } function renderGroupHelp( @@ -1372,24 +1460,27 @@ function renderGroupHelp( showVersion: boolean; presetsEnabled: boolean; }, - rootUsageName?: string + rootUsageName: string ): string { const sections: string[] = []; const globalLongOptionFlags = getGlobalLongOptionFlags(globalOptions.presetsEnabled); const commandRows = formatCommandRows(group, scope, casing, globalLongOptionFlags); if (commandRows.length > 0) { - sections.push(`${text.sectionHeader("Commands")}\n${formatCommandList(commandRows)}`); + sections.push(`${text.sectionHeader("Commands")}\n${formatHelpCommandList(commandRows)}`); } - sections.push(`${text.sectionHeader("Options")}\n${formatOptionList(formatGlobalOptionRows(globalOptions))}`); + sections.push( + `${text.sectionHeader("Options")}\n${formatHelpOptionList(formatGlobalOptionRows(globalOptions))}` + ); return renderHelpDocument({ breadcrumb, - usageLine: buildUsageLine(breadcrumb, rootUsageName, "[options] [command]"), + rootUsageName, + usageLine: buildUsageLine(breadcrumb, rootUsageName, "[command] [options]"), description: group.description, requiresAuth: group.requires?.auth === true, - sections, + sections }); } @@ -1401,64 +1492,80 @@ function renderLeafHelp( showVersion: boolean; presetsEnabled: boolean; }, - rootUsageName?: string + rootUsageName: string ): string { const sections: string[] = []; const globalLongOptionFlags = getGlobalLongOptionFlags(globalOptions.presetsEnabled); const collected = collectFields(command.params, casing, globalLongOptionFlags); const fields = assignPositionals(collected.fields, command.positional); - const optionRows = fields.map((field) => ({ - flags: formatHelpFieldFlags(field, globalLongOptionFlags), - description: formatHelpFieldDescription(field), - })).concat(collected.dynamicFields.flatMap((field) => formatDynamicHelpFields(field, casing))); + const optionRows = fields + .map((field) => ({ + flags: formatHelpFieldFlags(field, globalLongOptionFlags), + description: formatHelpFieldDescription(field) + })) + .concat(collected.dynamicFields.flatMap((field) => formatDynamicHelpFields(field, casing))); if (optionRows.length > 0) { - sections.push(`${text.sectionHeader("Options")}\n${formatOptionList(optionRows)}`); + sections.push(`${text.sectionHeader("Options")}\n${formatHelpOptionList(optionRows)}`); } - sections.push(`${text.sectionHeader("Options")}\n${formatOptionList(formatGlobalOptionRows(globalOptions))}`); + sections.push( + `${text.sectionHeader("Options")}\n${formatHelpOptionList(formatGlobalOptionRows(globalOptions))}` + ); const secretRows = formatSecretRows(command.secrets); if (secretRows.length > 0) { - sections.push(`${text.sectionHeader("Secrets (environment)")}\n${formatOptionList(secretRows)}`); + sections.push( + `${text.sectionHeader("Secrets (environment)")}\n${formatHelpOptionList(secretRows)}` + ); } const positionalFields = fields.filter((f) => f.positionalIndex !== undefined); - const usageSuffix = positionalFields.length > 0 - ? `[options] ${positionalFields.map(formatPositionalToken).join(" ")}` - : "[options]"; + const usageSuffix = + positionalFields.length > 0 + ? `[options] ${positionalFields.map(formatPositionalToken).join(" ")}` + : "[options]"; return renderHelpDocument({ breadcrumb, + rootUsageName, usageLine: buildUsageLine(breadcrumb, rootUsageName, usageSuffix), description: command.description, requiresAuth: command.requires?.auth === true, - sections, + sections }); } function renderHelpDocument(input: { breadcrumb: string[]; - usageLine?: string; + rootUsageName: string; + usageLine: string; description?: string; requiresAuth: boolean; sections: string[]; }): string { - const lines = [text.heading(input.breadcrumb.join(" ")), ""]; + const title = + input.breadcrumb.filter((segment) => segment.length > 0).join(" ") || input.rootUsageName; + const description = input.description ?? ""; + const sentenceEndIndex = description.indexOf(". "); + const headingDescription = + sentenceEndIndex === -1 ? description : description.slice(0, sentenceEndIndex + 1); + const remainingDescription = + sentenceEndIndex === -1 ? "" : description.slice(sentenceEndIndex + 2); + const heading = headingDescription.length > 0 ? `${title} — ${headingDescription}` : title; + const lines = [text.heading(heading), ""]; - if (input.usageLine !== undefined) { - lines.push(`${text.section("Usage:")} ${text.usageCommand(input.usageLine)}`, ""); + if (remainingDescription.length > 0) { + lines.push(remainingDescription, ""); } - if (input.description !== undefined) { - lines.push(input.description); - } + lines.push(`Usage: ${text.usageCommand(input.usageLine)}`, ""); if (input.requiresAuth) { lines.push("Requires: authentication"); } - if (input.description !== undefined || input.requiresAuth) { + if (input.requiresAuth) { lines.push(""); } @@ -1475,6 +1582,7 @@ async function renderGeneratedHelp( const target = resolveHelpTarget(root, argv, "cli", options.rootDisplayName); const output = resolveHelpOutput(argv); const casing = options.casing ?? "kebab"; + const rootUsageName = options.rootUsageName ?? inferProgramName(argv); await withOutputFormat(output, async () => { const rendered = @@ -1486,9 +1594,9 @@ async function renderGeneratedHelp( casing, { showVersion: options.version !== undefined, - presetsEnabled: options.presets === true, + presetsEnabled: options.presets === true }, - options.rootUsageName + rootUsageName ) : renderLeafHelp( target.node, @@ -1496,9 +1604,9 @@ async function renderGeneratedHelp( casing, { showVersion: options.version !== undefined, - presetsEnabled: options.presets === true, + presetsEnabled: options.presets === true }, - options.rootUsageName + rootUsageName ); process.stdout.write(rendered); @@ -1562,7 +1670,7 @@ function createNodeCommand( presetsEnabled, rawArgv: actionCommand.args, actionCommand, - variants: collected.variants, + variants: collected.variants }); }); @@ -1574,7 +1682,16 @@ function createNodeCommand( } const visibleChildren = node.children - .map((child) => createNodeCommand(child, casing, globalLongOptionFlags, execute, presetsEnabled, nextPathSegments)) + .map((child) => + createNodeCommand( + child, + casing, + globalLongOptionFlags, + execute, + presetsEnabled, + nextPathSegments + ) + ) .filter((child): child is CommanderCommand => child !== null); const group = new CommanderCommand(node.name); @@ -1614,7 +1731,9 @@ function addGlobalOptions(command: CommanderCommand, presetsEnabled: boolean): v return "md"; } - throw new InvalidArgumentError('Invalid value for "--output". Expected one of: rich, md, markdown, json.'); + throw new InvalidArgumentError( + 'Invalid value for "--output". Expected one of: rich, md, markdown, json.' + ); }) .option("--verbose", "Print stack traces for unexpected errors."); } @@ -1661,12 +1780,12 @@ async function promptForField(field: FieldDefinition): Promise { ? await schema.loadOptions() : schema.values.map((value) => ({ label: schema.labels?.[String(value)] ?? String(value), - value, + value })); const selected = await select({ message: field.description ?? field.displayPath, options, - initialValue: field.hasDefault ? field.defaultValue : undefined, + initialValue: field.hasDefault ? field.defaultValue : undefined }); if (isCancel(selected)) { @@ -1680,7 +1799,7 @@ async function promptForField(field: FieldDefinition): Promise { if (field.schema.kind === "boolean") { const selected = await confirm({ message: field.displayPath, - initialValue: field.hasDefault ? Boolean(field.defaultValue) : undefined, + initialValue: field.hasDefault ? Boolean(field.defaultValue) : undefined }); if (isCancel(selected)) { @@ -1696,7 +1815,7 @@ async function promptForField(field: FieldDefinition): Promise { initialValue: field.hasDefault && field.defaultValue !== undefined ? formatResolvedValue(field.defaultValue) - : undefined, + : undefined }); if (isCancel(entered)) { @@ -1742,7 +1861,7 @@ function resolveOutput(resolvedFlags: ResolvedFlags): OutputMode { const DESIGN_SYSTEM_OUTPUT_BY_MODE = { rich: "terminal", md: "markdown", - json: "json", + json: "json" } as const satisfies Record; function toDesignSystemOutput(output: OutputMode): "terminal" | "markdown" | "json" { @@ -1768,8 +1887,7 @@ async function withOutputFormat(output: OutputMode, fn: () => Promise): Pr function createFs(): HandlerFs { return { - readFile: async (path: string, encoding = "utf8") => - readFile(path, { encoding }), + readFile: async (path: string, encoding = "utf8") => readFile(path, { encoding }), writeFile: async (path: string, contents: string) => { await writeFile(path, contents); }, @@ -1780,7 +1898,7 @@ function createFs(): HandlerFs { } catch { return false; } - }, + } }; } @@ -1788,7 +1906,7 @@ function createEnv(values: Record = process.env): Ha return { get(key: string): string | undefined { return values[key]; - }, + } }; } @@ -1865,7 +1983,6 @@ function validatePresetScalarValue( } break; } - } throw new UserError( @@ -1883,7 +2000,12 @@ function validatePresetFieldValue( } if (field.schema.kind !== "array") { - return validatePresetScalarValue(value, field.schema as ScalarSchema, field.displayPath, presetPath); + return validatePresetScalarValue( + value, + field.schema as ScalarSchema, + field.displayPath, + presetPath + ); } const itemSchema = unwrapOptional(field.schema.item); @@ -1911,22 +2033,15 @@ async function loadPresetValues( try { rawPreset = await readFile(presetPath, { - encoding: "utf8", + encoding: "utf8" }); } catch (error) { - if ( - typeof error === "object" && - error !== null && - "code" in error && - error.code === "ENOENT" - ) { + if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") { throw new UserError(`Preset file "${presetPath}" was not found.`); } const message = - error instanceof Error && error.message.length > 0 - ? error.message - : "Unknown read error."; + error instanceof Error && error.message.length > 0 ? error.message : "Unknown read error."; throw new UserError(`Preset file "${presetPath}" could not be read: ${message}`); } @@ -2050,7 +2165,9 @@ function matchesFixtureValue(expected: unknown, actual: unknown): boolean { return false; } - return Object.entries(expected).every(([key, value]) => matchesFixtureValue(value, actual[key])); + return Object.entries(expected).every(([key, value]) => + matchesFixtureValue(value, actual[key]) + ); } return Object.is(expected, actual); @@ -2075,14 +2192,14 @@ function createFixtureResponse(response: FixtureFetchResponse): Response { if (response.body === undefined) { return new Response(null, { status, - headers, + headers }); } if (typeof response.body === "string") { return new Response(response.body, { status, - headers, + headers }); } @@ -2092,13 +2209,15 @@ function createFixtureResponse(response: FixtureFetchResponse): Response { return new Response(JSON.stringify(response.body), { status, - headers, + headers }); } function createFixtureFetch(entries: FixtureFetchEntry[] | undefined): typeof globalThis.fetch { return async (input: RequestInfo | URL, init?: RequestInit) => { - const method = normalizeHttpMethod(init?.method ?? (input instanceof Request ? input.method : undefined)); + const method = normalizeHttpMethod( + init?.method ?? (input instanceof Request ? input.method : undefined) + ); const url = getFetchUrl(input); const match = entries?.find((entry) => { const requestMethod = normalizeHttpMethod(entry.request.method); @@ -2114,7 +2233,7 @@ function createFixtureFetch(entries: FixtureFetchEntry[] | undefined): typeof gl } return new Response(null, { - status: 204, + status: 204 }); }; } @@ -2139,7 +2258,7 @@ function createFixtureFs(definition: unknown): HandlerFs { } return Object.prototype.hasOwnProperty.call(readFileEntries, filePath); - }, + } }; } @@ -2158,7 +2277,9 @@ function resolveFixtureMethodResult( const matcher = explicitMatcher ?? Object.fromEntries( - Object.entries(entry).filter(([key]) => key !== "result" && key !== "response" && key !== "error") + Object.entries(entry).filter( + ([key]) => key !== "result" && key !== "response" && key !== "error" + ) ); const firstArg = args[0]; @@ -2198,7 +2319,10 @@ function resolveFixtureMethodResult( if (isPlainObject(definition)) { const firstArg = args[0]; - if (typeof firstArg === "string" && Object.prototype.hasOwnProperty.call(definition, firstArg)) { + if ( + typeof firstArg === "string" && + Object.prototype.hasOwnProperty.call(definition, firstArg) + ) { return Promise.resolve(definition[firstArg]); } } @@ -2222,8 +2346,9 @@ function createFixtureService(definition: unknown): Record { } const methodName = String(property); - return async (...args: unknown[]) => resolveFixtureMethodResult(methodName, methods[methodName], args); - }, + return async (...args: unknown[]) => + resolveFixtureMethodResult(methodName, methods[methodName], args); + } } ); } @@ -2256,11 +2381,16 @@ function selectFixtureScenario(scenarios: FixtureScenario[], selector: string): return scenario; } -async function loadFixtureScenario(command: Command, selector: string): Promise { +async function loadFixtureScenario( + command: Command, + selector: string +): Promise { const commandPath = getCommandSourcePath(command); if (commandPath === undefined) { - throw new UserError(`Fixture mode could not determine the source file for command "${command.name}".`); + throw new UserError( + `Fixture mode could not determine the source file for command "${command.name}".` + ); } const fixturePath = resolveFixturePath(commandPath); @@ -2268,7 +2398,7 @@ async function loadFixtureScenario(command: Command, selecto try { rawFixture = await readFile(fixturePath, { - encoding: "utf8", + encoding: "utf8" }); } catch { throw new UserError( @@ -2295,10 +2425,12 @@ function resolveFixtureSecrets(command: Command): Record [name, "fixture-secret"])); } -function createFixtureEnvValues(command: Command): Record { +function createFixtureEnvValues( + command: Command +): Record { const values: Record = { ...process.env, - POE_API_KEY: process.env.POE_API_KEY ?? "fixture-secret", + POE_API_KEY: process.env.POE_API_KEY ?? "fixture-secret" }; for (const secret of Object.values(command.secrets)) { @@ -2323,7 +2455,7 @@ async function resolveFixtureRuntime( isFixture: false, requirementOptions, secrets: resolveCommandSecrets(command), - services, + services }; } @@ -2331,7 +2463,7 @@ async function resolveFixtureRuntime( const scenarioServices = isPlainObject(scenario.services) ? scenario.services : {}; const customServiceNames = new Set([ ...Object.keys(services as Record), - ...Object.keys(scenarioServices).filter((name) => !RESERVED_SERVICE_NAMES.has(name)), + ...Object.keys(scenarioServices).filter((name) => !RESERVED_SERVICE_NAMES.has(name)) ]); const fixtureServices = Object.fromEntries( [...customServiceNames].map((name) => [name, createFixtureService(scenarioServices[name])]) @@ -2345,10 +2477,10 @@ async function resolveFixtureRuntime( isFixture: true, requirementOptions: { ...requirementOptions, - env: fixtureEnvValues, + env: fixtureEnvValues }, secrets: resolveFixtureSecrets(command), - services: fixtureServices, + services: fixtureServices }; } @@ -2430,7 +2562,7 @@ function consumeFieldValue( if (inlineValue !== undefined) { return { nextIndex: index, - value: parseScalarValue(inlineValue, schema, label), + value: parseScalarValue(inlineValue, schema, label) }; } @@ -2438,20 +2570,20 @@ function consumeFieldValue( if (next === "true" || next === "false" || (schema.nullable === true && next === "null")) { return { nextIndex: index + 1, - value: parseScalarValue(next, schema, label), + value: parseScalarValue(next, schema, label) }; } return { nextIndex: index, - value: true, + value: true }; } if (inlineValue !== undefined) { return { nextIndex: index, - value: parseFieldInputValue(inlineValue, schema, label), + value: parseFieldInputValue(inlineValue, schema, label) }; } @@ -2470,7 +2602,7 @@ function consumeFieldValue( if (parsed === null) { return { nextIndex: cursor, - value: null, + value: null }; } @@ -2485,7 +2617,7 @@ function consumeFieldValue( return { nextIndex, - value: values, + value: values }; } @@ -2496,7 +2628,7 @@ function consumeFieldValue( return { nextIndex: index + 1, - value: parseFieldInputValue(next, schema, label), + value: parseFieldInputValue(next, schema, label) }; } @@ -2525,7 +2657,7 @@ function resolveDynamicLeaf( return { displayPath: toDisplayPath(displayPath), path: outputPath, - schema: unwrappedSchema as FieldSchema, + schema: unwrappedSchema as FieldSchema }; } @@ -2536,12 +2668,20 @@ function resolveDynamicLeaf( case "object": { const [head, ...rest] = rawSegments; - for (const [key, childSchema] of Object.entries(unwrappedSchema.shape) as Array<[string, AnySchema]>) { + for (const [key, childSchema] of Object.entries(unwrappedSchema.shape) as Array< + [string, AnySchema] + >) { if (formatSegment(key, casing) !== head) { continue; } - return resolveDynamicLeaf(childSchema, rest, casing, [...outputPath, key], [...displayPath, key]); + return resolveDynamicLeaf( + childSchema, + rest, + casing, + [...outputPath, key], + [...displayPath, key] + ); } throw new UserError(`Unknown parameter "${[...displayPath, head].join(".")}".`); @@ -2561,15 +2701,25 @@ function resolveDynamicLeaf( case "array": { const itemSchema = unwrapOptional(unwrappedSchema.item); if (itemSchema.kind !== "object") { - throw new UserError(`Array parameter "${toDisplayPath(displayPath)}" must use object items.`); + throw new UserError( + `Array parameter "${toDisplayPath(displayPath)}" must use object items.` + ); } const [head, ...rest] = rawSegments; if (head === undefined || !isNumericFixtureSelector(head)) { - throw new UserError(`Array parameter "${toDisplayPath(displayPath)}" must use numeric indices.`); + throw new UserError( + `Array parameter "${toDisplayPath(displayPath)}" must use numeric indices.` + ); } - return resolveDynamicLeaf(itemSchema, rest, casing, [...outputPath, head], [...displayPath, head]); + return resolveDynamicLeaf( + itemSchema, + rest, + casing, + [...outputPath, head], + [...displayPath, head] + ); } default: @@ -2615,7 +2765,9 @@ function finalizeDynamicValue(schema: AnySchema, value: unknown, displayPath: st for (let index = 0; index < indices.length; index += 1) { if (indices[index] !== index) { - throw new UserError(`Array parameter "${displayPath}" must use contiguous indices starting at 0.`); + throw new UserError( + `Array parameter "${displayPath}" must use contiguous indices starting at 0.` + ); } } @@ -2634,7 +2786,9 @@ function finalizeDynamicValue(schema: AnySchema, value: unknown, displayPath: st } const result: Record = {}; - for (const [key, rawChildSchema] of Object.entries(unwrappedSchema.shape) as Array<[string, AnySchema]>) { + for (const [key, rawChildSchema] of Object.entries(unwrappedSchema.shape) as Array< + [string, AnySchema] + >) { const childSchema = unwrapOptional(rawChildSchema); const childValue = value[key]; const childDisplayPath = displayPath.length === 0 ? key : `${displayPath}.${key}`; @@ -2670,7 +2824,7 @@ function finalizeDynamicValue(schema: AnySchema, value: unknown, displayPath: st unwrappedSchema.value, entryValue, displayPath.length === 0 ? key : `${displayPath}.${key}` - ), + ) ]) ); } @@ -2690,7 +2844,9 @@ function parseDynamicValues( } { const rawValues = new Map>(); const providedFieldIds = new Set(); - const sortedFields = [...dynamicFields].sort((left, right) => right.optionPath.length - left.optionPath.length); + const sortedFields = [...dynamicFields].sort( + (left, right) => right.optionPath.length - left.optionPath.length + ); for (let index = 0; index < rawArgv.length; index += 1) { const token = rawArgv[index] ?? ""; @@ -2725,7 +2881,7 @@ function parseDynamicValues( negated && leaf.schema.kind === "boolean" ? { nextIndex: index, - value: false, + value: false } : consumeFieldValue(rawArgv, index, leaf.schema, label, inlineValue); @@ -2746,9 +2902,9 @@ function parseDynamicValues( field.schema.kind === "record" ? field.schema : field.schema, rawValues.get(field.id), field.displayPath - ), + ) ]) - ), + ) }; } @@ -2809,7 +2965,9 @@ async function enforceVariantConstraints( } } - const invalidDynamicFieldId = branch.dynamicFieldIds.find((fieldId) => providedDynamicFieldIds.has(fieldId)); + const invalidDynamicFieldId = branch.dynamicFieldIds.find((fieldId) => + providedDynamicFieldIds.has(fieldId) + ); if (invalidDynamicFieldId !== undefined) { const field = dynamicFieldById.get(invalidDynamicFieldId); if (field !== undefined) { @@ -2961,7 +3119,7 @@ async function resolveParams( ? parseDynamicValues(dynamicFields, rawArgv, casing) : { providedFieldIds: new Set(), - values: new Map(), + values: new Map() }; for (const field of dynamicFields) { @@ -3012,7 +3170,7 @@ async function executeCommand( logger, renderTable, getTheme, - note, + note }; const optionValues = state.actionCommand.optsWithGlobals() as Record; const resolvedFlags = optionValues as ResolvedFlags; @@ -3027,7 +3185,7 @@ async function executeCommand( env: runtime.env, progress(message: string): void { logger.info(message); - }, + } }; await withOutputFormat(output, async () => { @@ -3047,10 +3205,15 @@ async function executeCommand( const context = { ...preflightContext, - params, + params } as HandlerContext; - if (state.command.confirm && !state.command.humanInLoop && !resolvedFlags.yes && process.stdin.isTTY) { + if ( + state.command.confirm && + !state.command.humanInLoop && + !resolvedFlags.yes && + process.stdin.isTTY + ) { for (const field of state.fields) { const value = field.path.reduce( (current, segment) => @@ -3067,7 +3230,7 @@ async function executeCommand( const proceed = await confirm({ message: "Proceed?", - initialValue: true, + initialValue: true }); if (isCancel(proceed)) { @@ -3080,7 +3243,12 @@ async function executeCommand( } } - const result = await invokeWithHumanInLoop(state.command, context, runtimeOptions, state.commandPath); + const result = await invokeWithHumanInLoop( + state.command, + context, + runtimeOptions, + state.commandPath + ); if (output === "rich" && runtime.isFixture) { writeRichHeader(`${state.command.name} (fixture)`); @@ -3135,10 +3303,10 @@ export async function runCLI> const servicesWithBuiltIns = { ...services, runtimeOptions, - root, + root } as TServices; const requirementOptions = { - apiVersion: options.apiVersion, + apiVersion: options.apiVersion } satisfies CommandRequirementOptions; validateServices(services as Record); @@ -3168,7 +3336,13 @@ export async function runCLI> }; for (const child of root.children) { - const command = createNodeCommand(child, casing, globalLongOptionFlags, execute, presetsEnabled); + const command = createNodeCommand( + child, + casing, + globalLongOptionFlags, + execute, + presetsEnabled + ); if (command === null) { continue; } @@ -3191,7 +3365,9 @@ export async function runCLI> handleRunError( error, - lastActionCommand ? Boolean(getResolvedFlags(lastActionCommand).verbose) : process.argv.includes("--verbose") + lastActionCommand + ? Boolean(getResolvedFlags(lastActionCommand).verbose) + : process.argv.includes("--verbose") ); } } diff --git a/src/cli/commands/__snapshots__/runtime-help.test.ts.snap b/src/cli/commands/__snapshots__/runtime-help.test.ts.snap index c1b3e4284d..db56b7bd16 100644 --- a/src/cli/commands/__snapshots__/runtime-help.test.ts.snap +++ b/src/cli/commands/__snapshots__/runtime-help.test.ts.snap @@ -94,12 +94,10 @@ Options: `; exports[`runtime option help > snapshots superintendent help 1`] = ` -"Poe - poe-code superintendent run +"Poe - poe-code superintendent run — Run the full superintendent loop. Usage: poe-code superintendent run [options] [doc] -Run the full superintendent loop. - OPTIONS [doc] Path to the superintendent markdown document --agent Override the builder agent for this run. Precedence: --agent > plan From 07e7fd64ba7f0ef9b39752a358a031bca9575d17 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 04:34:29 -0500 Subject: [PATCH 082/111] fix: unwrap toolcraft mcp results --- .../toolcraft-help-and-result-rendering.md | 8 +- ...oolcraft-help-and-result-rendering.md.lock | 2 +- packages/toolcraft/src/cli.test.ts | 30 ++++ packages/toolcraft/src/cli.ts | 5 +- .../src/mcp-proxy-integration.test.ts | 4 +- packages/toolcraft/src/renderer.test.ts | 137 ++++++++++++++++++ packages/toolcraft/src/renderer.ts | 100 ++++++++++++- 7 files changed, 273 insertions(+), 13 deletions(-) create mode 100644 packages/toolcraft/src/renderer.test.ts diff --git a/docs/plans/toolcraft-help-and-result-rendering.md b/docs/plans/toolcraft-help-and-result-rendering.md index b15aabc286..fdb5a29894 100644 --- a/docs/plans/toolcraft-help-and-result-rendering.md +++ b/docs/plans/toolcraft-help-and-result-rendering.md @@ -306,7 +306,7 @@ tasks: status: implement: done test: done - commit: open + commit: done - id: toolcraft-renderer-mcp-unwrap title: Auto-unwrap MCP CallToolResult in renderer @@ -380,9 +380,9 @@ tasks: ({content,structuredContent,isError,customKey}) is NOT treated as an envelope and renders as-is status: - implement: open - test: open - commit: open + implement: done + test: done + commit: done - id: toolcraft-renderer-yaml-fallback title: String/string[] shortcuts plus YAML fallback in autoRender diff --git a/docs/plans/toolcraft-help-and-result-rendering.md.lock b/docs/plans/toolcraft-help-and-result-rendering.md.lock index 04331d6469..81907f9a91 100644 --- a/docs/plans/toolcraft-help-and-result-rendering.md.lock +++ b/docs/plans/toolcraft-help-and-result-rendering.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T09:27:34.906Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T09:32:54.698Z"} \ No newline at end of file diff --git a/packages/toolcraft/src/cli.test.ts b/packages/toolcraft/src/cli.test.ts index d041752bf5..13a861f0b1 100644 --- a/packages/toolcraft/src/cli.test.ts +++ b/packages/toolcraft/src/cli.test.ts @@ -294,6 +294,10 @@ function readStdout(stdoutWrite: ReturnType): string { return stdoutWrite.mock.calls.map(([chunk]) => String(chunk)).join(""); } +function readStderr(stderrWrite: ReturnType): string { + return stderrWrite.mock.calls.map(([chunk]) => String(chunk)).join(""); +} + describe("runCLI", () => { beforeEach(() => { vi.clearAllMocks(); @@ -1169,6 +1173,32 @@ describe("runCLI", () => { expect(readStdout(stdoutWrite)).toBe("rendered markdown\n"); }); + it("sets exitCode when rendering an MCP error result", async () => { + const stdoutWrite = vi.spyOn(process.stdout, "write").mockImplementation(() => true); + const stderrWrite = vi.spyOn(process.stderr, "write").mockImplementation(() => true); + const deploy = defineCommand({ + name: "deploy", + params: S.Object({}), + handler: async () => ({ + content: [{ type: "text", text: "tool failed" }], + isError: true + }) + }); + + const root = defineGroup({ + name: "toolcraft", + children: [deploy] + }); + + process.argv = ["node", "toolcraft", "deploy", "--yes"]; + + await runCLI(root); + + expect(readStdout(stdoutWrite)).toBe(""); + expect(readStderr(stderrWrite)).toBe("tool failed\n"); + expect(process.exitCode).toBe(1); + }); + it.each([ { argv: ["node", "toolcraft", "deploy", "--yes"], diff --git a/packages/toolcraft/src/cli.ts b/packages/toolcraft/src/cli.ts index 6a304e866f..2eb395b8ca 100644 --- a/packages/toolcraft/src/cli.ts +++ b/packages/toolcraft/src/cli.ts @@ -3259,7 +3259,10 @@ async function executeCommand( return; } - renderResult(state.command, result, output, primitives); + const renderStatus = renderResult(state.command, result, output, primitives); + if (renderStatus.mcpError) { + process.exitCode = 1; + } }); } diff --git a/packages/toolcraft/src/mcp-proxy-integration.test.ts b/packages/toolcraft/src/mcp-proxy-integration.test.ts index 3e17082c0e..2180429435 100644 --- a/packages/toolcraft/src/mcp-proxy-integration.test.ts +++ b/packages/toolcraft/src/mcp-proxy-integration.test.ts @@ -882,7 +882,9 @@ describe("mcp proxy integration", () => { await runCLI(cliRoot); - expect(readOutput(stdoutWrite)).toContain('"text": "khoor"'); + expect(JSON.parse(readOutput(stdoutWrite))).toEqual({ + result: "khoor", + }); const sdk = createSDK(createProxyRoot(harness, { rename }).root) as { github: { diff --git a/packages/toolcraft/src/renderer.test.ts b/packages/toolcraft/src/renderer.test.ts new file mode 100644 index 0000000000..026fd089ad --- /dev/null +++ b/packages/toolcraft/src/renderer.test.ts @@ -0,0 +1,137 @@ +import { describe, expect, it, vi } from "vitest"; +import { S } from "toolcraft-schema"; +import { defineCommand } from "./index.js"; +import { renderResult } from "./renderer.js"; +import type { RenderPrimitives } from "./index.js"; +import type { OutputMode } from "./renderer.js"; + +function createPrimitives(): RenderPrimitives { + return { + logger: { + info: vi.fn(), + success: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + resolved: vi.fn(), + errorResolved: vi.fn(), + message: vi.fn(), + }, + renderTable: vi.fn((options: { columns: Array<{ name: string; title: string }>; rows: Record[] }) => + JSON.stringify({ + columns: options.columns.map((column) => ({ name: column.name, title: column.title })), + rows: options.rows, + }) + ), + getTheme: vi.fn(() => ({ + header: (value: string) => value, + muted: (value: string) => value, + })), + note: vi.fn(), + }; +} + +function createCommand(result: unknown, render?: Parameters[0]["render"]) { + return defineCommand({ + name: "demo", + params: S.Object({}), + handler: async () => result, + render, + }); +} + +function render(result: unknown, output: OutputMode = "rich") { + const command = createCommand(result); + const primitives = createPrimitives(); + let stdout = ""; + let stderr = ""; + const status = renderResult(command, result, output, primitives, (chunk, stream = "stdout") => { + if (stream === "stderr") { + stderr += chunk; + return; + } + + stdout += chunk; + }); + + return { stdout, stderr, status }; +} + +describe("renderResult MCP call tool envelopes", () => { + it("unwraps structuredContent.result before rendering", () => { + const result = { + structuredContent: { + result: "- Daily Focus", + }, + }; + + expect(render(result).stdout).toBe("- Daily Focus\n"); + expect(render(result).status.mcpError).toBe(false); + }); + + it("passes structuredContent without result to downstream renderers", () => { + const markdown = vi.fn(() => "rendered"); + const result = { + structuredContent: { + foo: 1, + bar: 2, + }, + }; + const command = createCommand(result, { markdown }); + const primitives = createPrimitives(); + let stdout = ""; + + renderResult(command, result, "md", primitives, (chunk) => { + stdout += chunk; + }); + + expect(markdown).toHaveBeenCalledWith({ foo: 1, bar: 2 }, primitives); + expect(stdout).toBe("rendered\n"); + }); + + it("joins text content when structuredContent is absent", () => { + const result = { + content: [ + { type: "text", text: "hello" }, + { type: "text", text: "world" }, + ], + }; + + expect(render(result).stdout).toBe("hello\nworld\n"); + }); + + it("falls back to the empty-result renderer when text content is empty", () => { + const result = { + content: [], + }; + + expect(render(result).stdout).toBe("Done.\n"); + }); + + it("writes error envelopes to stderr and marks the result as an MCP error", () => { + const result = { + content: [{ type: "text", text: "failed" }], + isError: true, + }; + + const rendered = render(result); + + expect(rendered.stdout).toBe(""); + expect(rendered.stderr).toBe("failed\n"); + expect(rendered.status.mcpError).toBe(true); + }); + + it("does not unwrap objects with extra keys", () => { + const result = { + content: [], + structuredContent: { + result: "inner", + }, + isError: false, + customKey: "keep", + }; + + expect(render(result, "json").stdout).toBe( + '{\n "content": [],\n "structuredContent": {\n "result": "inner"\n },\n "isError": false,\n "customKey": "keep"\n}\n' + ); + }); +}); diff --git a/packages/toolcraft/src/renderer.ts b/packages/toolcraft/src/renderer.ts index b03618ec89..6312eb995e 100644 --- a/packages/toolcraft/src/renderer.ts +++ b/packages/toolcraft/src/renderer.ts @@ -2,12 +2,83 @@ import type { Command, RenderPrimitives } from "./index.js"; export type OutputMode = "rich" | "md" | "json"; -type WriteFn = (chunk: string) => void; +type WriteStream = "stdout" | "stderr"; +type WriteFn = (chunk: string, stream?: WriteStream) => void; + +export interface RenderResultStatus { + mcpError: boolean; +} + +interface McpCallToolResult { + content?: unknown[]; + structuredContent?: unknown; + isError?: boolean; + _meta?: unknown; +} + +interface McpTextContent { + type: "text"; + text: string; +} function isObject(value: unknown): value is Record { return value !== null && typeof value === "object" && !Array.isArray(value); } +function isMcpCallToolResult(value: unknown): value is McpCallToolResult { + if (!isObject(value)) { + return false; + } + + const hasContent = Array.isArray(value.content); + const hasStructured = value.structuredContent !== undefined; + if (!hasContent && !hasStructured) { + return false; + } + + return Object.keys(value).every( + (key) => + key === "content" || key === "structuredContent" || key === "isError" || key === "_meta" + ); +} + +function isMcpTextContent(value: unknown): value is McpTextContent { + return isObject(value) && value.type === "text" && typeof value.text === "string"; +} + +function extractMcpPayload(envelope: McpCallToolResult): unknown { + const structuredContent = envelope.structuredContent; + if (isObject(structuredContent) && "result" in structuredContent) { + return structuredContent.result; + } + + if (structuredContent !== undefined) { + return structuredContent; + } + + if (Array.isArray(envelope.content)) { + const text = envelope.content + .filter(isMcpTextContent) + .map((block) => block.text) + .join("\n"); + + return text.length > 0 ? text : undefined; + } + + return undefined; +} + +function unwrapMcpEnvelope(result: unknown): { result: unknown; mcpError: boolean } { + if (!isMcpCallToolResult(result)) { + return { result, mcpError: false }; + } + + return { + result: extractMcpPayload(result), + mcpError: result.isError === true, + }; +} + function isArrayOfObjects(value: unknown): value is Array> { return Array.isArray(value) && value.every((entry) => isObject(entry)); } @@ -173,16 +244,32 @@ export function renderResult( result: unknown, output: OutputMode, primitives: RenderPrimitives, - write: WriteFn = (chunk) => { + write: WriteFn = (chunk, stream = "stdout") => { + if (stream === "stderr") { + process.stderr.write(chunk); + return; + } + process.stdout.write(chunk); } -): void { +): RenderResultStatus { + const unwrapped = unwrapMcpEnvelope(result); + result = unwrapped.result; + + if (unwrapped.mcpError) { + const payload = autoRender(result, output, primitives); + if (payload.length > 0) { + write(`${payload}\n`, "stderr"); + } + return { mcpError: true }; + } + if (output === "json" && command.render?.json) { const payload = command.render.json(result, primitives); if (payload !== undefined) { write(`${stringifyJson(payload, 2)}\n`); } - return; + return { mcpError: false }; } if (output === "md" && command.render?.markdown) { @@ -190,16 +277,17 @@ export function renderResult( if (typeof payload === "string" && payload.length > 0) { write(`${payload}\n`); } - return; + return { mcpError: false }; } if (output === "rich" && command.render?.rich) { command.render.rich(result, primitives); - return; + return { mcpError: false }; } const payload = autoRender(result, output, primitives); if (payload.length > 0) { write(`${payload}\n`); } + return { mcpError: false }; } From 920ef356baa91e7733821f9780397eb89953d784 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 04:39:42 -0500 Subject: [PATCH 083/111] fix(toolcraft): render rich objects as yaml --- .../toolcraft-help-and-result-rendering.md | 4 +- ...oolcraft-help-and-result-rendering.md.lock | 2 +- package-lock.json | 3 +- packages/toolcraft/package.json | 3 +- packages/toolcraft/src/renderer.test.ts | 71 ++++++++++++++++++- packages/toolcraft/src/renderer.ts | 23 +++--- packages/toolcraft/src/toolcraft.test.ts | 10 +-- 7 files changed, 94 insertions(+), 22 deletions(-) diff --git a/docs/plans/toolcraft-help-and-result-rendering.md b/docs/plans/toolcraft-help-and-result-rendering.md index fdb5a29894..6989aa29d9 100644 --- a/docs/plans/toolcraft-help-and-result-rendering.md +++ b/docs/plans/toolcraft-help-and-result-rendering.md @@ -432,8 +432,8 @@ tasks: based on the old object/array table being the default. Tables now appear only via Command.render.rich, never automatically. status: - implement: open - test: open + implement: done + test: done commit: open - id: toolcraft-help-output-qa diff --git a/docs/plans/toolcraft-help-and-result-rendering.md.lock b/docs/plans/toolcraft-help-and-result-rendering.md.lock index 81907f9a91..822d6847b5 100644 --- a/docs/plans/toolcraft-help-and-result-rendering.md.lock +++ b/docs/plans/toolcraft-help-and-result-rendering.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T09:32:54.698Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T09:38:55.643Z"} \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index d5d717a3e1..55418e80d2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7837,7 +7837,8 @@ "commander": "^14.0.3", "console-table-printer": "^2.15.0", "tiny-stdio-mcp-server": "^0.1.0", - "toolcraft-schema": "^0.0.1" + "toolcraft-schema": "^0.0.1", + "yaml": "^2.8.2" }, "engines": { "node": ">=20" diff --git a/packages/toolcraft/package.json b/packages/toolcraft/package.json index d4f6438978..9d37118afa 100644 --- a/packages/toolcraft/package.json +++ b/packages/toolcraft/package.json @@ -45,7 +45,8 @@ "chalk": "^5.6.2", "commander": "^14.0.3", "console-table-printer": "^2.15.0", - "tiny-stdio-mcp-server": "^0.1.0" + "tiny-stdio-mcp-server": "^0.1.0", + "yaml": "^2.8.2" }, "files": [ "dist" diff --git a/packages/toolcraft/src/renderer.test.ts b/packages/toolcraft/src/renderer.test.ts index 026fd089ad..d317be802f 100644 --- a/packages/toolcraft/src/renderer.test.ts +++ b/packages/toolcraft/src/renderer.test.ts @@ -1,5 +1,6 @@ -import { describe, expect, it, vi } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; import { S } from "toolcraft-schema"; +import YAML from "yaml"; import { defineCommand } from "./index.js"; import { renderResult } from "./renderer.js"; import type { RenderPrimitives } from "./index.js"; @@ -56,6 +57,74 @@ function render(result: unknown, output: OutputMode = "rich") { return { stdout, stderr, status }; } +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe("renderResult auto renderer", () => { + it("renders strings as-is", () => { + expect(render("hello").stdout).toBe("hello\n"); + }); + + it("renders string arrays joined with newlines", () => { + expect(render(["hello", "world"]).stdout).toBe("hello\nworld\n"); + }); + + it("renders objects as YAML by default", () => { + expect(render({ foo: 1, bar: [1, 2] }).stdout).toMatchInlineSnapshot(` + "foo: 1 + bar: + - 1 + - 2 + + " + `); + }); + + it("renders arrays of objects as YAML by default", () => { + expect(render([{ foo: 1 }, { bar: [1, 2] }]).stdout).toMatchInlineSnapshot(` + "- foo: 1 + - bar: + - 1 + - 2 + + " + `); + }); + + it("invokes Command.render.rich and bypasses YAML", () => { + const stringifyYaml = vi.spyOn(YAML, "stringify"); + const rich = vi.fn(); + const command = createCommand({ foo: 1 }, { rich }); + const primitives = createPrimitives(); + let stdout = ""; + + renderResult(command, { foo: 1 }, "rich", primitives, (chunk) => { + stdout += chunk; + }); + + expect(rich).toHaveBeenCalledWith({ foo: 1 }, primitives); + expect(stdout).toBe(""); + expect(stringifyYaml).not.toHaveBeenCalled(); + }); + + it("uses the markdown renderer for --output md and bypasses YAML", () => { + const stringifyYaml = vi.spyOn(YAML, "stringify"); + + expect(render({ foo: 1, bar: [1, 2] }, "md").stdout).toBe("- foo: 1\n- bar: [1,2]\n"); + expect(stringifyYaml).not.toHaveBeenCalled(); + }); + + it("uses the JSON renderer for --output json and bypasses YAML", () => { + const stringifyYaml = vi.spyOn(YAML, "stringify"); + + expect(render({ foo: 1, bar: [1, 2] }, "json").stdout).toBe( + '{\n "foo": 1,\n "bar": [\n 1,\n 2\n ]\n}\n' + ); + expect(stringifyYaml).not.toHaveBeenCalled(); + }); +}); + describe("renderResult MCP call tool envelopes", () => { it("unwraps structuredContent.result before rendering", () => { const result = { diff --git a/packages/toolcraft/src/renderer.ts b/packages/toolcraft/src/renderer.ts index 6312eb995e..d8e1d1cd4d 100644 --- a/packages/toolcraft/src/renderer.ts +++ b/packages/toolcraft/src/renderer.ts @@ -1,3 +1,4 @@ +import YAML from "yaml"; import type { Command, RenderPrimitives } from "./index.js"; export type OutputMode = "rich" | "md" | "json"; @@ -107,7 +108,7 @@ function stringifyJson(value: unknown, spaces?: number): string { } } -function renderObjectTable(result: Record, primitives: RenderPrimitives): string { +export function renderObjectTable(result: Record, primitives: RenderPrimitives): string { const rows = Object.entries(result).map(([key, value]) => ({ key, value: stringifyValue(value), @@ -151,7 +152,7 @@ function getColumnNames(rows: Array>): string[] { return [...names]; } -function renderArrayTable(result: Array>, primitives: RenderPrimitives): string { +export function renderArrayTable(result: Array>, primitives: RenderPrimitives): string { if (result.length === 0) { return "[]"; } @@ -195,7 +196,7 @@ function renderArrayMarkdown(result: Array>): string { return [header, separator, ...rows].join("\n"); } -function autoRender(result: unknown, output: OutputMode, primitives: RenderPrimitives): string { +function autoRender(result: unknown, output: OutputMode, _primitives: RenderPrimitives): string { if (result === null || result === undefined) { if (output === "json") { return stringifyJson({ ok: true }, 2); @@ -212,16 +213,18 @@ function autoRender(result: unknown, output: OutputMode, primitives: RenderPrimi return result; } - if (isObject(result)) { - if (output === "rich") { - return renderObjectTable(result, primitives); - } + if (output === "rich" && Array.isArray(result) && result.every((value) => typeof value === "string")) { + return result.join("\n"); + } + if (isObject(result)) { if (output === "md") { return renderObjectMarkdown(result); } - return stringifyJson(result, 2); + if (output === "json") { + return stringifyJson(result, 2); + } } if (isArrayOfObjects(result)) { @@ -232,8 +235,10 @@ function autoRender(result: unknown, output: OutputMode, primitives: RenderPrimi if (output === "json") { return stringifyJson(result, 2); } + } - return renderArrayTable(result, primitives); + if (output === "rich") { + return YAML.stringify(result); } return stringifyJson(result, 2); diff --git a/packages/toolcraft/src/toolcraft.test.ts b/packages/toolcraft/src/toolcraft.test.ts index b601b918b1..16f86afbeb 100644 --- a/packages/toolcraft/src/toolcraft.test.ts +++ b/packages/toolcraft/src/toolcraft.test.ts @@ -1544,8 +1544,7 @@ describe("renderResult", () => { label: "object in rich", output: "rich" as const, result: { name: "demo", count: 2 }, - expected: - '{"columns":[{"name":"key","title":"Key"},{"name":"value","title":"Value"}],"rows":[{"key":"name","value":"demo"},{"key":"count","value":"2"}]}\n', + expected: "name: demo\ncount: 2\n\n", }, { label: "object in markdown", @@ -1566,8 +1565,7 @@ describe("renderResult", () => { { name: "alpha", count: 1 }, { name: "beta", count: 2 }, ], - expected: - '{"columns":[{"name":"name","title":"name"},{"name":"count","title":"count"}],"rows":[{"name":"alpha","count":"1"},{"name":"beta","count":"2"}]}\n', + expected: "- name: alpha\n count: 1\n- name: beta\n count: 2\n\n", }, { label: "array of objects in markdown", @@ -1670,9 +1668,7 @@ describe("renderResult", () => { ], "rich" ) - ).toBe( - '{"columns":[{"name":"name","title":"name"},{"name":"count","title":"count"},{"name":"enabled","title":"enabled"}],"rows":[{"name":"alpha|beta","count":"1","enabled":""},{"name":"","count":"2","enabled":"true"}]}\n' - ); + ).toBe("- name: alpha|beta\n count: 1\n- enabled: true\n count: 2\n\n"); expect( runRender( From f39e7d02e9d1f367837f2318f9cca4fc61535f9d Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 04:43:01 -0500 Subject: [PATCH 084/111] docs: add toolcraft help output QA --- .../toolcraft-help-and-result-rendering.md | 6 +- ...oolcraft-help-and-result-rendering.md.lock | 2 +- packages/toolcraft/QA-help-output.md | 229 ++++++++++++++++++ 3 files changed, 233 insertions(+), 4 deletions(-) create mode 100644 packages/toolcraft/QA-help-output.md diff --git a/docs/plans/toolcraft-help-and-result-rendering.md b/docs/plans/toolcraft-help-and-result-rendering.md index 6989aa29d9..21372b1f6e 100644 --- a/docs/plans/toolcraft-help-and-result-rendering.md +++ b/docs/plans/toolcraft-help-and-result-rendering.md @@ -434,7 +434,7 @@ tasks: status: implement: done test: done - commit: open + commit: done - id: toolcraft-help-output-qa title: Markdown QA for help output at multiple terminal widths @@ -492,8 +492,8 @@ tasks: Do NOT write a test runner. The QA is human-executed. status: - implement: open - commit: open + implement: done + commit: done - id: toolcraft-release-and-vendor-refresh title: Release toolcraft 0.0.4 and refresh ashby-mcp vendor stub diff --git a/docs/plans/toolcraft-help-and-result-rendering.md.lock b/docs/plans/toolcraft-help-and-result-rendering.md.lock index 822d6847b5..6c70e51a45 100644 --- a/docs/plans/toolcraft-help-and-result-rendering.md.lock +++ b/docs/plans/toolcraft-help-and-result-rendering.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T09:38:55.643Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T09:41:55.223Z"} \ No newline at end of file diff --git a/packages/toolcraft/QA-help-output.md b/packages/toolcraft/QA-help-output.md new file mode 100644 index 0000000000..b000dc36bf --- /dev/null +++ b/packages/toolcraft/QA-help-output.md @@ -0,0 +1,229 @@ +# Help Output QA + +This is an ad-hoc manual QA walkthrough. It is not a test runner and should be executed by a human. + +## Example Consumer + +Run from the `packages/toolcraft` package: + +```sh +cd packages/toolcraft +npm run build +npm run build -w tiny-stdio-mcp-test-server +``` + +Create this temporary one-file consumer as `QA-help-example.ts` inside `packages/toolcraft`. It uses only local workspace packages and does not depend on `ashby-mcp`. + +```ts +import { fileURLToPath } from "node:url"; +import { S, defineCommand, defineGroup } from "./src/index.js"; +import { runCLI } from "./src/cli.js"; + +const serverCli = fileURLToPath( + new URL("../tiny-stdio-mcp-test-server/dist/cli.js", import.meta.url) +); + +const daily = defineCommand({ + name: "daily", + description: + "Build a daily operational report with a deliberately long description so wrapping can be inspected at narrow terminal widths.", + positional: ["accountId"], + params: S.Object({ + accountId: S.String({ + description: "Account id to inspect" + }), + dryRun: S.Boolean({ + description: "Plan the report without writing output", + default: false + }), + date: S.String({ + description: + "Report date used for selecting records and aligning all time-based metrics in the generated output.", + pattern: "^\\d{4}-\\d{2}-\\d{2}$" + }) + }), + secrets: { + reportToken: { + env: "TOOLCRAFT_QA_TOKEN", + description: "Token used by the report backend." + } + }, + handler: async ({ params }) => ({ + accountId: params.accountId, + date: params.date, + dryRun: params.dryRun + }) +}); + +const renderString = defineCommand({ + name: "string", + description: "Return a plain string.", + params: S.Object({}), + handler: async () => "plain string" +}); + +const renderLines = defineCommand({ + name: "lines", + description: "Return multiple lines.", + params: S.Object({}), + handler: async () => ["first line", "second line"] +}); + +const renderObject = defineCommand({ + name: "object", + description: "Return an object.", + params: S.Object({}), + handler: async () => ({ status: "ok", count: 2, nested: { enabled: true } }) +}); + +const renderErrorEnvelope = defineCommand({ + name: "error-envelope", + description: "Return an MCP CallToolResult with isError true.", + params: S.Object({}), + handler: async () => ({ + content: [{ type: "text", text: "upstream failure" }], + isError: true + }) +}); + +const reports = defineGroup({ + name: "reports", + description: "Report commands", + children: [daily] +}); + +const render = defineGroup({ + name: "render", + description: "Renderer examples", + children: [renderString, renderLines, renderObject, renderErrorEnvelope] +}); + +const upstream = defineGroup({ + name: "upstream", + description: "Local MCP proxy examples", + mcp: { + transport: "stdio", + command: process.execPath, + args: [serverCli, "serve", "word-of-the-day"] + }, + children: [] +}); + +const root = defineGroup({ + name: "toolcraft-qa", + description: "Help output QA fixture", + children: [reports, render, upstream] +}); + +await runCLI(root, { + presets: true, + rootDisplayName: "toolcraft-qa", + rootUsageName: "toolcraft-qa", + version: "0.1.0" +}); +``` + +Use this command shape for all examples below: + +```sh +npm exec -- tsx QA-help-example.ts -- +``` + +When finished, remove the temporary file and local MCP cache: + +```sh +rm -f QA-help-example.ts +rm -rf .toolcraft +``` + +## Help Capture + +For each width below, resize the terminal to the target width and confirm it with `tput cols`. Capture the screen or terminal output for all three commands. + +### 60 Columns + +```sh +tput cols +npm exec -- tsx QA-help-example.ts -- --help +npm exec -- tsx QA-help-example.ts -- reports --help +npm exec -- tsx QA-help-example.ts -- reports daily --help +``` + +### 100 Columns + +```sh +tput cols +npm exec -- tsx QA-help-example.ts -- --help +npm exec -- tsx QA-help-example.ts -- reports --help +npm exec -- tsx QA-help-example.ts -- reports daily --help +``` + +### 160 Columns + +```sh +tput cols +npm exec -- tsx QA-help-example.ts -- --help +npm exec -- tsx QA-help-example.ts -- reports --help +npm exec -- tsx QA-help-example.ts -- reports daily --help +``` + +## Help Acceptance Checklist + +Apply this checklist to every captured root, group, and leaf help screen. + +- [ ] Heading is ` — ` with no leading space and no blank heading line +- [ ] `Usage:` line is present +- [ ] Section header is `Commands` / `Options` / `Secrets (environment)` — no trailing colons +- [ ] `-h, --help` is NOT listed under Options +- [ ] `--preset` is listed only when `presets:true` was passed +- [ ] `--version` is listed only when `version` is set +- [ ] Boolean flags render as `--flag`, not `--flag [value]` +- [ ] Pattern-constrained scalar renders the human token, such as ``, not `` +- [ ] Description column wraps at the right edge; continuation lines align with the description column + +## Run Output + +Set the required report secret once before running output checks: + +```sh +export TOOLCRAFT_QA_TOKEN=qa-secret +``` + +Run a command whose handler returns a string: + +```sh +npm exec -- tsx QA-help-example.ts -- render string +``` + +Run a command whose handler returns `string[]`: + +```sh +npm exec -- tsx QA-help-example.ts -- render lines +``` + +Run a command whose handler returns an object: + +```sh +npm exec -- tsx QA-help-example.ts -- render object +``` + +Run a command whose handler is an MCP proxy returning a `CallToolResult`: + +```sh +npm exec -- tsx QA-help-example.ts -- upstream word-of-the-day +``` + +Run a command whose handler returns `isError:true`: + +```sh +npm exec -- tsx QA-help-example.ts -- render error-envelope +echo $? +``` + +## Run Output Acceptance Checklist + +- [ ] `string` -> printed as-is +- [ ] `string[]` -> one per line +- [ ] `object` -> YAML +- [ ] MCP envelope -> unwrapped to its payload, then rendered per the rules above +- [ ] `isError` -> payload to stderr, process exit code 1 From 6058f06897e7e1b2ddccd8db6dd94fc3747d99e0 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 04:49:00 -0500 Subject: [PATCH 085/111] chore(toolcraft): prepare help renderer release --- package-lock.json | 10 +++++----- packages/design-system/package.json | 2 +- packages/toolcraft-openapi/package.json | 4 ++-- packages/toolcraft/package.json | 4 ++-- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/package-lock.json b/package-lock.json index 55418e80d2..e940972d18 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7390,7 +7390,7 @@ }, "packages/design-system": { "name": "@poe-code/design-system", - "version": "0.0.1", + "version": "0.0.2", "peerDependencies": { "@clack/prompts": "^1.0.0", "chalk": "^5.3.0", @@ -7817,7 +7817,7 @@ } }, "packages/toolcraft": { - "version": "0.0.1", + "version": "0.0.4", "bundleDependencies": [ "@poe-code/design-system", "@poe-code/agent-mcp-config", @@ -7848,7 +7848,7 @@ "@poe-code/agent-human-in-loop": "*", "@poe-code/agent-mcp-config": "*", "@poe-code/config-mutations": "*", - "@poe-code/design-system": "^0.0.1", + "@poe-code/design-system": "^0.0.2", "@poe-code/file-lock": "*", "@poe-code/task-list": "*", "auth-store": "*", @@ -7865,11 +7865,11 @@ "dependencies": { "@clack/core": "^1.0.0", "@clack/prompts": "^1.0.0", - "@poe-code/design-system": "^0.0.1", + "@poe-code/design-system": "^0.0.2", "auth-store": "^0.0.1", "chalk": "^5.6.2", "console-table-printer": "^2.15.0", - "toolcraft": "^0.0.1", + "toolcraft": "^0.0.4", "yaml": "^2.8.2" }, "bin": { diff --git a/packages/design-system/package.json b/packages/design-system/package.json index cce78d4231..bc5c9b6df7 100644 --- a/packages/design-system/package.json +++ b/packages/design-system/package.json @@ -1,6 +1,6 @@ { "name": "@poe-code/design-system", - "version": "0.0.1", + "version": "0.0.2", "type": "module", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/packages/toolcraft-openapi/package.json b/packages/toolcraft-openapi/package.json index 4ba8f577fc..2a974f7606 100644 --- a/packages/toolcraft-openapi/package.json +++ b/packages/toolcraft-openapi/package.json @@ -26,11 +26,11 @@ "dependencies": { "@clack/core": "^1.0.0", "@clack/prompts": "^1.0.0", - "@poe-code/design-system": "^0.0.1", - "toolcraft": "^0.0.1", + "@poe-code/design-system": "^0.0.2", "auth-store": "^0.0.1", "chalk": "^5.6.2", "console-table-printer": "^2.15.0", + "toolcraft": "^0.0.4", "yaml": "^2.8.2" }, "engines": { diff --git a/packages/toolcraft/package.json b/packages/toolcraft/package.json index 9d37118afa..72b7505608 100644 --- a/packages/toolcraft/package.json +++ b/packages/toolcraft/package.json @@ -1,6 +1,6 @@ { "name": "toolcraft", - "version": "0.0.1", + "version": "0.0.4", "type": "module", "main": "dist/index.js", "types": "dist/index.d.ts", @@ -72,7 +72,7 @@ "auth-store" ], "optionalDependencies": { - "@poe-code/design-system": "^0.0.1", + "@poe-code/design-system": "^0.0.2", "@poe-code/agent-mcp-config": "*", "@poe-code/agent-human-in-loop": "*", "@poe-code/task-list": "*", From af6f1535b9f58d38b95d7000c368862cd81d4498 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 04:50:41 -0500 Subject: [PATCH 086/111] docs: mark toolcraft help task done --- docs/plans/toolcraft-help-and-result-rendering.md | 2 +- docs/plans/toolcraft-help-and-result-rendering.md.lock | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/plans/toolcraft-help-and-result-rendering.md b/docs/plans/toolcraft-help-and-result-rendering.md index 21372b1f6e..05344c769b 100644 --- a/docs/plans/toolcraft-help-and-result-rendering.md +++ b/docs/plans/toolcraft-help-and-result-rendering.md @@ -555,7 +555,7 @@ tasks: calendar.meeting create / edit). Only --help and known read-only commands. status: - implement: open + implement: done commit: open --- diff --git a/docs/plans/toolcraft-help-and-result-rendering.md.lock b/docs/plans/toolcraft-help-and-result-rendering.md.lock index 6c70e51a45..922ee3daa9 100644 --- a/docs/plans/toolcraft-help-and-result-rendering.md.lock +++ b/docs/plans/toolcraft-help-and-result-rendering.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T09:41:55.223Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T09:50:22.340Z"} \ No newline at end of file From 9d39d715b643cd247011eb6708c94ed59a45725c Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 04:51:33 -0500 Subject: [PATCH 087/111] docs: archive toolcraft help plan --- docs/plans/{ => archive}/toolcraft-help-and-result-rendering.md | 2 +- docs/plans/toolcraft-help-and-result-rendering.md.lock | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename docs/plans/{ => archive}/toolcraft-help-and-result-rendering.md (99%) diff --git a/docs/plans/toolcraft-help-and-result-rendering.md b/docs/plans/archive/toolcraft-help-and-result-rendering.md similarity index 99% rename from docs/plans/toolcraft-help-and-result-rendering.md rename to docs/plans/archive/toolcraft-help-and-result-rendering.md index 05344c769b..6f2cbb3c78 100644 --- a/docs/plans/toolcraft-help-and-result-rendering.md +++ b/docs/plans/archive/toolcraft-help-and-result-rendering.md @@ -556,7 +556,7 @@ tasks: read-only commands. status: implement: done - commit: open + commit: done --- ## Toolcraft help and result rendering overhaul diff --git a/docs/plans/toolcraft-help-and-result-rendering.md.lock b/docs/plans/toolcraft-help-and-result-rendering.md.lock index 922ee3daa9..36b6a3245a 100644 --- a/docs/plans/toolcraft-help-and-result-rendering.md.lock +++ b/docs/plans/toolcraft-help-and-result-rendering.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T09:50:22.340Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T09:50:57.066Z"} \ No newline at end of file From 18be78572ec6f49bbf7ba7725e51e94b6e13a313 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 04:56:13 -0500 Subject: [PATCH 088/111] feat(task-list): pass markdown dir open options --- ...oolcraft-help-and-result-rendering.md.lock | 1 - docs/plans/zharness-plans-via-task-list.md | 6 +++--- .../zharness-plans-via-task-list.md.lock | 1 + packages/task-list/src/open-task-list.test.ts | 19 +++++++++++++++++++ packages/task-list/src/open.ts | 7 ++++++- packages/task-list/src/types.ts | 4 ++++ 6 files changed, 33 insertions(+), 5 deletions(-) delete mode 100644 docs/plans/toolcraft-help-and-result-rendering.md.lock create mode 100644 docs/plans/zharness-plans-via-task-list.md.lock diff --git a/docs/plans/toolcraft-help-and-result-rendering.md.lock b/docs/plans/toolcraft-help-and-result-rendering.md.lock deleted file mode 100644 index 36b6a3245a..0000000000 --- a/docs/plans/toolcraft-help-and-result-rendering.md.lock +++ /dev/null @@ -1 +0,0 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T09:50:57.066Z"} \ No newline at end of file diff --git a/docs/plans/zharness-plans-via-task-list.md b/docs/plans/zharness-plans-via-task-list.md index f7b8178188..dfd8a898e9 100644 --- a/docs/plans/zharness-plans-via-task-list.md +++ b/docs/plans/zharness-plans-via-task-list.md @@ -42,9 +42,9 @@ tasks: prefix or a small no-op read; the next task uses them.) - Do not modify `gh-issues` types or any other backend. status: - implement: open - test: open - commit: open + implement: done + test: done + commit: done - id: markdown-dir-single-list title: markdown-dir singleList layout — root is the list diff --git a/docs/plans/zharness-plans-via-task-list.md.lock b/docs/plans/zharness-plans-via-task-list.md.lock new file mode 100644 index 0000000000..14a09806a7 --- /dev/null +++ b/docs/plans/zharness-plans-via-task-list.md.lock @@ -0,0 +1 @@ +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T09:55:06.273Z"} \ No newline at end of file diff --git a/packages/task-list/src/open-task-list.test.ts b/packages/task-list/src/open-task-list.test.ts index c962ec1a97..86905d2545 100644 --- a/packages/task-list/src/open-task-list.test.ts +++ b/packages/task-list/src/open-task-list.test.ts @@ -69,6 +69,8 @@ describe("openTaskList", () => { expect(spy).toHaveBeenCalledWith({ path: "/repo/tasks", + singleList: undefined, + frontmatterMode: "strict", defaults: { metadata: {} }, @@ -93,6 +95,8 @@ describe("openTaskList", () => { expect(spy).toHaveBeenCalledWith({ path: "/repo/tasks.yaml", + singleList: undefined, + frontmatterMode: "strict", defaults: { metadata: {} }, @@ -257,6 +261,21 @@ describe("openTaskList", () => { ); }); + it("opens markdown-dir with single-list passthrough frontmatter options", async () => { + const { fs } = createFs(); + + await expect( + openTaskList({ + type: "markdown-dir", + path: "/repo/tasks", + create: true, + fs, + singleList: "plans", + frontmatterMode: "passthrough" + }) + ).resolves.toEqual(expect.objectContaining({ list: expect.any(Function) })); + }); + for (const backend of BACKENDS) { it(`uses the default state machine for ${backend.name} when none is passed`, async () => { const { fs } = createFs(); diff --git a/packages/task-list/src/open.ts b/packages/task-list/src/open.ts index d0e9ecb540..564dc582fe 100644 --- a/packages/task-list/src/open.ts +++ b/packages/task-list/src/open.ts @@ -19,7 +19,10 @@ import type { const DEFAULT_LOCK_STALE_MS = 30_000; const DEFAULT_LOCK_RETRIES = 20; -type FileBackendOptions = OpenMarkdownDirOptions | OpenYamlFileOptions; +type FileBackendOptions = (OpenMarkdownDirOptions | OpenYamlFileOptions) & { + singleList?: string; + frontmatterMode?: "strict" | "passthrough"; +}; export const backendFactories: Record = { "markdown-dir": markdownDirBackend, @@ -49,6 +52,8 @@ async function openFileBackend(options: FileBackendOptions): Promise { const deps: BackendDeps = { path: options.path, + singleList: options.singleList, + frontmatterMode: options.frontmatterMode ?? "strict", defaults: { metadata: { ...(options.defaults?.metadata ?? {}) } }, diff --git a/packages/task-list/src/types.ts b/packages/task-list/src/types.ts index e375e29fb1..90ecced758 100644 --- a/packages/task-list/src/types.ts +++ b/packages/task-list/src/types.ts @@ -103,6 +103,8 @@ export type OpenTaskListOptions = export interface OpenMarkdownDirOptions { type: "markdown-dir"; path: string; + singleList?: string; + frontmatterMode?: "strict" | "passthrough"; defaults?: TaskDefaults; create?: boolean; lockStaleMs?: number; @@ -133,6 +135,8 @@ export interface OpenGhIssuesOptions { export interface BackendDeps { path: string; + singleList?: string; + frontmatterMode: "strict" | "passthrough"; defaults: Required; lockStaleMs: number; lockRetries: number; From 2d1f3b68f401d47143a9424eda41b0d65d361776 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 05:01:46 -0500 Subject: [PATCH 089/111] feat(task-list): support single-list markdown dirs --- docs/plans/zharness-plans-via-task-list.md | 6 +- .../zharness-plans-via-task-list.md.lock | 2 +- .../src/backends/markdown-dir.test.ts | 158 ++++++++++++++++++ .../task-list/src/backends/markdown-dir.ts | 129 ++++++++++---- 4 files changed, 259 insertions(+), 36 deletions(-) diff --git a/docs/plans/zharness-plans-via-task-list.md b/docs/plans/zharness-plans-via-task-list.md index dfd8a898e9..621ed824a0 100644 --- a/docs/plans/zharness-plans-via-task-list.md +++ b/docs/plans/zharness-plans-via-task-list.md @@ -105,9 +105,9 @@ tasks: - Do not change `move`/`reorder`/`fire` semantics yet beyond what the layout helpers require. status: - implement: open - refactor: open - test: open + implement: done + refactor: done + test: done commit: open - id: markdown-dir-passthrough diff --git a/docs/plans/zharness-plans-via-task-list.md.lock b/docs/plans/zharness-plans-via-task-list.md.lock index 14a09806a7..347d8a0dbb 100644 --- a/docs/plans/zharness-plans-via-task-list.md.lock +++ b/docs/plans/zharness-plans-via-task-list.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T09:55:06.273Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T10:00:49.538Z"} \ No newline at end of file diff --git a/packages/task-list/src/backends/markdown-dir.test.ts b/packages/task-list/src/backends/markdown-dir.test.ts index 828b2a8341..c9345a3eb2 100644 --- a/packages/task-list/src/backends/markdown-dir.test.ts +++ b/packages/task-list/src/backends/markdown-dir.test.ts @@ -18,6 +18,15 @@ function parseFrontmatter(content: string): Record { return document.toJS() as Record; } +function taskDocument(name: string, state = "draft"): string { + return `--- +name: ${name} +state: ${state} +--- + +`; +} + describe("markdownDirBackend", () => { afterEach(() => { vi.useRealTimers(); @@ -185,6 +194,155 @@ state: draft await expect(taskList.lists()).resolves.toEqual(["alpha"]); }); + it("uses the root directory as the only list in single-list mode", async () => { + const { fs } = createFs({ + "/repo/tasks/foo.md": taskDocument("Foo"), + "/repo/tasks/01-bar.md": taskDocument("Bar") + }); + const taskList = await markdownDirBackend({ + path: "/repo/tasks", + singleList: "plans", + frontmatterMode: "strict", + defaults: { + metadata: {} + }, + lockStaleMs: 30_000, + lockRetries: 20, + create: false, + fs + }); + + await expect(taskList.lists()).resolves.toEqual(["plans"]); + await expect(taskList.list("plans").all()).resolves.toEqual([ + expect.objectContaining({ + id: "bar", + list: "plans", + qualifiedId: "plans/bar", + name: "Bar" + }), + expect.objectContaining({ + id: "foo", + list: "plans", + qualifiedId: "plans/foo", + name: "Foo" + }) + ]); + }); + + it("rejects unknown lists in single-list mode", async () => { + const { fs } = createFs({ + "/repo/tasks/.keep": "" + }); + const taskList = await markdownDirBackend({ + path: "/repo/tasks", + singleList: "plans", + frontmatterMode: "strict", + defaults: { + metadata: {} + }, + lockStaleMs: 30_000, + lockRetries: 20, + create: false, + fs + }); + + expect(() => taskList.list("other")).toThrow('Task list "other" not found.'); + }); + + it("does not support moving between lists in single-list mode", async () => { + const { fs } = createFs({ + "/repo/tasks/foo.md": taskDocument("Foo") + }); + const taskList = await markdownDirBackend({ + path: "/repo/tasks", + singleList: "plans", + frontmatterMode: "strict", + defaults: { + metadata: {} + }, + lockStaleMs: 30_000, + lockRetries: 20, + create: false, + fs + }); + + await expect(taskList.moveBetweenLists("plans/foo", "plans")).rejects.toThrow( + "moveBetweenLists is unsupported in single-list mode." + ); + }); + + it("creates and archives tasks at the root in single-list mode", async () => { + const { fs, rawFs } = createFs({ + "/repo/tasks/.keep": "" + }); + const taskList = await markdownDirBackend({ + path: "/repo/tasks", + singleList: "plans", + frontmatterMode: "strict", + defaults: { + metadata: {} + }, + lockStaleMs: 30_000, + lockRetries: 20, + create: false, + fs + }); + + await taskList.list("plans").create({ + id: "write-root", + name: "Write root" + }); + + await expect(rawFs.readFile("/repo/tasks/01-write-root.md", "utf8")).resolves.toContain( + "name: Write root" + ); + await expect(rawFs.stat("/repo/tasks/plans")).rejects.toMatchObject({ + code: "ENOENT" + }); + + await taskList.list("plans").fire("write-root", "archive"); + + await expect(rawFs.stat("/repo/tasks/01-write-root.md")).rejects.toMatchObject({ + code: "ENOENT" + }); + await expect(rawFs.readFile("/repo/tasks/archive/write-root.md", "utf8")).resolves.toContain( + "state: archived" + ); + await expect(taskList.list("plans").get("write-root")).resolves.toMatchObject({ + id: "write-root", + list: "plans", + state: "archived" + }); + }); + + it("ignores root subdirectories when reading active tasks in single-list mode", async () => { + const { fs } = createFs({ + "/repo/tasks/foo.md": taskDocument("Foo"), + "/repo/tasks/poe-agent/ignored.md": taskDocument("Ignored") + }); + const taskList = await markdownDirBackend({ + path: "/repo/tasks", + singleList: "plans", + frontmatterMode: "strict", + defaults: { + metadata: {} + }, + lockStaleMs: 30_000, + lockRetries: 20, + create: false, + fs + }); + + await expect(taskList.list("plans").all()).resolves.toEqual([ + expect.objectContaining({ + id: "foo", + list: "plans", + qualifiedId: "plans/foo", + name: "Foo" + }) + ]); + }); + it('rejects the reserved "archive" list name', async () => { const { fs } = createFs({ "/repo/tasks/.keep": "" diff --git a/packages/task-list/src/backends/markdown-dir.ts b/packages/task-list/src/backends/markdown-dir.ts index b2416cb7d5..f579905afa 100644 --- a/packages/task-list/src/backends/markdown-dir.ts +++ b/packages/task-list/src/backends/markdown-dir.ts @@ -63,6 +63,12 @@ type TaskLocation = { path: string; }; +type ListLayout = { kind: "multi" } | { kind: "single"; name: string }; + +function resolveListLayout(deps: BackendDeps): ListLayout { + return deps.singleList ? { kind: "single", name: deps.singleList } : { kind: "multi" }; +} + function validateListName(name: string): string { if ( name.length === 0 || @@ -98,20 +104,28 @@ function parseQualifiedId(qualifiedId: string): { }; } -function listPath(rootPath: string, list: string): string { +function listPath(rootPath: string, layout: ListLayout, list: string): string { + if (layout.kind === "single") { + return rootPath; + } + return path.join(rootPath, list); } -function archiveDirectoryPath(rootPath: string, list: string): string { - return path.join(listPath(rootPath, list), ARCHIVE_DIRECTORY_NAME); +function archiveDirectoryPath(rootPath: string, layout: ListLayout, list: string): string { + if (layout.kind === "single") { + return path.join(rootPath, ARCHIVE_DIRECTORY_NAME); + } + + return path.join(rootPath, list, ARCHIVE_DIRECTORY_NAME); } function activeTaskFilename(id: string, order: number, width: number): string { return `${String(order).padStart(width, "0")}-${id}${MARKDOWN_EXTENSION}`; } -function archivedTaskPath(rootPath: string, list: string, id: string): string { - return path.join(archiveDirectoryPath(rootPath, list), `${id}${MARKDOWN_EXTENSION}`); +function archivedTaskPath(rootPath: string, layout: ListLayout, list: string, id: string): string { + return path.join(archiveDirectoryPath(rootPath, layout, list), `${id}${MARKDOWN_EXTENSION}`); } function isMarkdownFile(entryName: string): boolean { @@ -127,7 +141,13 @@ function isLockFile(entryName: string): boolean { } function isValidTaskIdShape(id: string): boolean { - return id.length > 0 && !id.startsWith(".") && !id.includes("/") && !id.includes("\\") && !id.includes(".."); + return ( + id.length > 0 && + !id.startsWith(".") && + !id.includes("/") && + !id.includes("\\") && + !id.includes("..") + ); } function parseActiveFilename(entryName: string): { id: string; order: number | null } | undefined { @@ -161,7 +181,10 @@ function stripTrailingCarriageReturn(line: string): string { return line.endsWith("\r") ? line.slice(0, -1) : line; } -function splitTaskDocument(content: string, filePath: string): { +function splitTaskDocument( + content: string, + filePath: string +): { body: string; frontmatter: string; } { @@ -333,10 +356,11 @@ async function findActiveTaskFilename( async function findTaskLocation( fs: TaskListFs, rootPath: string, + layout: ListLayout, list: string, id: string ): Promise { - const listDirectoryPath = listPath(rootPath, list); + const listDirectoryPath = listPath(rootPath, layout, list); const activeName = await findActiveTaskFilename(fs, listDirectoryPath, id); if (activeName) { const activePath = path.join(listDirectoryPath, activeName); @@ -346,7 +370,7 @@ async function findTaskLocation( } } - const archivedPath = archivedTaskPath(rootPath, list, id); + const archivedPath = archivedTaskPath(rootPath, layout, list, id); const archivedStat = await statIfExists(fs, archivedPath); if (archivedStat?.isFile()) { return { archived: true, path: archivedPath }; @@ -358,11 +382,12 @@ async function findTaskLocation( async function readTaskAtLocation( fs: TaskListFs, rootPath: string, + layout: ListLayout, list: string, id: string, validStates: ReadonlySet ): Promise { - const location = await findTaskLocation(fs, rootPath, list, id); + const location = await findTaskLocation(fs, rootPath, layout, list, id); if (!location) { throw new TaskNotFoundError(`Task "${list}/${id}" not found.`); @@ -423,7 +448,11 @@ function updatedFrontmatter( return nextFrontmatter; } -function transitionedFrontmatter(existingFrontmatter: TaskRecord, task: Task, to: string): TaskRecord { +function transitionedFrontmatter( + existingFrontmatter: TaskRecord, + task: Task, + to: string +): TaskRecord { return { ...existingFrontmatter, $schema: existingFrontmatter.$schema ?? TASK_SCHEMA_ID, @@ -477,8 +506,8 @@ interface ActiveEntry { filename: string; } -function createTasksView(deps: BackendDeps, list: string): Tasks { - const listDirectoryPath = listPath(deps.path, list); +function createTasksView(deps: BackendDeps, layout: ListLayout, list: string): Tasks { + const listDirectoryPath = listPath(deps.path, layout, list); const stateMachine = resolveStateMachine(deps.stateMachine); const validStates = new Set(stateMachine.states); @@ -508,7 +537,10 @@ function createTasksView(deps: BackendDeps, list: string): Tasks { return result; } - async function readActiveTasks(): Promise<{ entries: ActiveEntry[]; tasks: Map }> { + async function readActiveTasks(): Promise<{ + entries: ActiveEntry[]; + tasks: Map; + }> { const entries = await readActiveEntries(); const tasks = new Map(); @@ -522,7 +554,7 @@ function createTasksView(deps: BackendDeps, list: string): Tasks { } async function readArchivedTasks(): Promise<{ task: Task; raw: TaskRecord }[]> { - const archivePath = archiveDirectoryPath(deps.path, list); + const archivePath = archiveDirectoryPath(deps.path, layout, list); const entries = await readDirectoryNames(deps.fs, archivePath); const result: { task: Task; raw: TaskRecord }[] = []; @@ -538,7 +570,9 @@ function createTasksView(deps: BackendDeps, list: string): Tasks { result.push({ task: file.task, raw: file.frontmatter }); } - return result.sort((left, right) => left.task.qualifiedId.localeCompare(right.task.qualifiedId)); + return result.sort((left, right) => + left.task.qualifiedId.localeCompare(right.task.qualifiedId) + ); } async function rewriteListPrefixes(orderedIds: readonly string[]): Promise { @@ -554,7 +588,10 @@ function createTasksView(deps: BackendDeps, list: string): Tasks { const desiredFilename = activeTaskFilename(id, index + 1, width); if (entry.filename !== desiredFilename) { const fromPath = path.join(listDirectoryPath, entry.filename); - const stagingPath = path.join(listDirectoryPath, `${desiredFilename}.staging-${process.pid}-${index}`); + const stagingPath = path.join( + listDirectoryPath, + `${desiredFilename}.staging-${process.pid}-${index}` + ); await deps.fs.rename(fromPath, stagingPath); entry.filename = path.basename(stagingPath); } @@ -595,7 +632,7 @@ function createTasksView(deps: BackendDeps, list: string): Tasks { async function getTaskFile(id: string): Promise { validateTaskId(id); - return readTaskAtLocation(deps.fs, deps.path, list, id, validStates); + return readTaskAtLocation(deps.fs, deps.path, layout, list, id, validStates); } function assertFireableTaskEvent(task: Task, eventName: string) { @@ -645,7 +682,7 @@ function createTasksView(deps: BackendDeps, list: string): Tasks { await deps.fs.mkdir(listDirectoryPath, { recursive: true }); return withListLock(async () => { - const existing = await findTaskLocation(deps.fs, deps.path, list, input.id); + const existing = await findTaskLocation(deps.fs, deps.path, layout, list, input.id); if (existing) { throw new TaskAlreadyExistsError(`Task "${list}/${input.id}" already exists.`); } @@ -676,9 +713,13 @@ function createTasksView(deps: BackendDeps, list: string): Tasks { const nextFrontmatter = updatedFrontmatter(existing.frontmatter, existing.task, patch); const description = patch.description ?? existing.task.description; - await writeAtomically(deps.fs, existing.path, serializeTaskDocument(nextFrontmatter, description)); + await writeAtomically( + deps.fs, + existing.path, + serializeTaskDocument(nextFrontmatter, description) + ); - return createTask(list,id, nextFrontmatter, description); + return createTask(list, id, nextFrontmatter, description); }); }, async fire(id: string, eventName: string, opts?: TaskFireOptions): Promise { @@ -704,18 +745,18 @@ function createTasksView(deps: BackendDeps, list: string): Tasks { event.to, opts?.metadataPatch ); - const nextTask = createTask(list,id, nextFrontmatter, existing.task.description); + const nextTask = createTask(list, id, nextFrontmatter, existing.task.description); const serializedTask = serializeTaskDocument(nextFrontmatter, existing.task.description); if (event.to === "archived") { - const targetPath = archivedTaskPath(deps.path, list, id); + const targetPath = archivedTaskPath(deps.path, layout, list, id); const archivedTargetExists = await statIfExists(deps.fs, targetPath); if (archivedTargetExists?.isFile()) { throw new TaskAlreadyExistsError(`Task "${list}/${id}" already exists in archive.`); } await writeAtomically(deps.fs, existing.path, serializedTask); - await deps.fs.mkdir(archiveDirectoryPath(deps.path, list), { recursive: true }); + await deps.fs.mkdir(archiveDirectoryPath(deps.path, layout, list), { recursive: true }); await deps.fs.rename(existing.path, targetPath); await event.onEnter?.(nextTask); @@ -744,7 +785,7 @@ function createTasksView(deps: BackendDeps, list: string): Tasks { }, async delete(id: string): Promise { await withTaskLock(id, async () => { - const location = await findTaskLocation(deps.fs, deps.path, list, id); + const location = await findTaskLocation(deps.fs, deps.path, layout, list, id); if (!location) { throw new TaskNotFoundError(`Task "${list}/${id}" not found.`); } @@ -810,15 +851,28 @@ function createTasksView(deps: BackendDeps, list: string): Tasks { export async function markdownDirBackend(deps: BackendDeps): Promise { await ensureRootPath(deps); + const layout = resolveListLayout(deps); const stateMachine = resolveStateMachine(deps.stateMachine); const validStates = new Set(stateMachine.states); const list = (name: string): Tasks => { + if (layout.kind === "single") { + if (name !== layout.name) { + throw new Error(`Task list "${name}" not found.`); + } + + return createTasksView(deps, layout, layout.name); + } + const listName = validateListName(name); - return createTasksView(deps, listName); + return createTasksView(deps, layout, listName); }; const lists = async (): Promise => { + if (layout.kind === "single") { + return [layout.name]; + } + const entries = await readDirectoryNames(deps.fs, deps.path); const result: string[] = []; @@ -858,25 +912,36 @@ export async function markdownDirBackend(deps: BackendDeps): Promise { }; const moveBetweenLists = async (qualifiedId: string, targetList: string): Promise => { + if (layout.kind === "single") { + throw new Error("moveBetweenLists is unsupported in single-list mode."); + } + const { list: sourceListName, id } = parseQualifiedId(qualifiedId); const targetListName = validateListName(targetList); if (sourceListName === targetListName) { - const file = await readTaskAtLocation(deps.fs, deps.path, sourceListName, id, validStates); + const file = await readTaskAtLocation( + deps.fs, + deps.path, + layout, + sourceListName, + id, + validStates + ); return file.task; } - const targetExisting = await findTaskLocation(deps.fs, deps.path, targetListName, id); + const targetExisting = await findTaskLocation(deps.fs, deps.path, layout, targetListName, id); if (targetExisting) { throw new TaskAlreadyExistsError(`Task "${targetListName}/${id}" already exists.`); } - const sourceLocation = await findTaskLocation(deps.fs, deps.path, sourceListName, id); + const sourceLocation = await findTaskLocation(deps.fs, deps.path, layout, sourceListName, id); if (!sourceLocation) { throw new TaskNotFoundError(`Task "${sourceListName}/${id}" not found.`); } - const targetListDir = listPath(deps.path, targetListName); + const targetListDir = listPath(deps.path, layout, targetListName); await deps.fs.mkdir(targetListDir, { recursive: true }); const targetEntries = await (async () => { @@ -892,9 +957,9 @@ export async function markdownDirBackend(deps: BackendDeps): Promise { })(); if (sourceLocation.archived) { - const archivedTargetDir = archiveDirectoryPath(deps.path, targetListName); + const archivedTargetDir = archiveDirectoryPath(deps.path, layout, targetListName); await deps.fs.mkdir(archivedTargetDir, { recursive: true }); - const archivedTargetPath = archivedTaskPath(deps.path, targetListName, id); + const archivedTargetPath = archivedTaskPath(deps.path, layout, targetListName, id); await deps.fs.rename(sourceLocation.path, archivedTargetPath); const file = await readTaskFile(deps.fs, targetListName, id, archivedTargetPath, validStates); return file.task; From d30936af8e5fd0eb77ae0d2db2ba2c946918cb04 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 05:12:19 -0500 Subject: [PATCH 090/111] feat(task-list): support passthrough markdown frontmatter --- docs/plans/zharness-plans-via-task-list.md | 8 +- .../zharness-plans-via-task-list.md.lock | 2 +- .../src/backends/markdown-dir.test.ts | 217 ++++++++++++ .../task-list/src/backends/markdown-dir.ts | 317 ++++++++++++++---- 4 files changed, 466 insertions(+), 78 deletions(-) diff --git a/docs/plans/zharness-plans-via-task-list.md b/docs/plans/zharness-plans-via-task-list.md index 621ed824a0..d6bef9cfa2 100644 --- a/docs/plans/zharness-plans-via-task-list.md +++ b/docs/plans/zharness-plans-via-task-list.md @@ -108,7 +108,7 @@ tasks: implement: done refactor: done test: done - commit: open + commit: done - id: markdown-dir-passthrough title: markdown-dir frontmatterMode passthrough — read and write loose frontmatter @@ -167,9 +167,9 @@ tasks: - Filename → id translation (strip `NN-`) is already handled by `parseActiveFilename`; reuse it for the synthesized name default. status: - implement: open - refactor: open - test: open + implement: done + refactor: done + test: done commit: open - id: markdown-dir-archive-repack diff --git a/docs/plans/zharness-plans-via-task-list.md.lock b/docs/plans/zharness-plans-via-task-list.md.lock index 347d8a0dbb..1d10276ffc 100644 --- a/docs/plans/zharness-plans-via-task-list.md.lock +++ b/docs/plans/zharness-plans-via-task-list.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T10:00:49.538Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T10:10:57.463Z"} \ No newline at end of file diff --git a/packages/task-list/src/backends/markdown-dir.test.ts b/packages/task-list/src/backends/markdown-dir.test.ts index c9345a3eb2..aea2154367 100644 --- a/packages/task-list/src/backends/markdown-dir.test.ts +++ b/packages/task-list/src/backends/markdown-dir.test.ts @@ -160,6 +160,223 @@ Broken` await expect(taskList.list("planning").get("bad")).rejects.toBeInstanceOf(MalformedTaskError); }); + it("rejects non-task frontmatter in strict mode", async () => { + const { fs } = createFs({ + "/repo/tasks/planning/pipeline.md": `--- +kind: pipeline +name: Pipeline plan +state: draft +--- +` + }); + const taskList = await markdownDirBackend({ + path: "/repo/tasks", + defaults: { + metadata: {} + }, + lockStaleMs: 30_000, + lockRetries: 20, + create: false, + fs + }); + + await expect(taskList.list("planning").get("pipeline")).rejects.toBeInstanceOf( + MalformedTaskError + ); + await expect(taskList.list("planning").get("pipeline")).rejects.toThrow('"kind"'); + }); + + it("reads and updates non-task frontmatter in passthrough mode", async () => { + const pipelineSchema = + "https://poe-platform.github.io/poe-code/schemas/plans/pipeline.schema.json"; + const { fs, rawFs } = createFs({ + "/repo/tasks/foo.md": `--- +$schema: ${pipelineSchema} +kind: pipeline +version: 1 +--- + +` + }); + const taskList = await markdownDirBackend({ + path: "/repo/tasks", + singleList: "plans", + frontmatterMode: "passthrough", + defaults: { + metadata: {} + }, + lockStaleMs: 30_000, + lockRetries: 20, + create: false, + fs + }); + + await expect(taskList.list("plans").get("foo")).resolves.toMatchObject({ + state: "draft", + name: "foo", + metadata: { + $schema: pipelineSchema, + kind: "pipeline", + version: 1 + } + }); + + await taskList.list("plans").fire("foo", "plan"); + + const content = await rawFs.readFile("/repo/tasks/foo.md", "utf8"); + expect(parseFrontmatter(content)).toMatchObject({ + $schema: pipelineSchema, + kind: "pipeline", + version: 1, + state: "planned" + }); + expect(parseFrontmatter(content)).not.toHaveProperty("name"); + }); + + it("uses the parsed filename id for passthrough synthesized names without persisting them", async () => { + const { fs, rawFs } = createFs({ + "/repo/tasks/07-prefixed.md": `--- +kind: pipeline +state: not-a-state +--- + +` + }); + const taskList = await markdownDirBackend({ + path: "/repo/tasks", + singleList: "plans", + frontmatterMode: "passthrough", + defaults: { + metadata: {} + }, + lockStaleMs: 30_000, + lockRetries: 20, + create: false, + fs + }); + + await expect(taskList.list("plans").get("prefixed")).resolves.toMatchObject({ + id: "prefixed", + name: "prefixed", + state: "draft", + metadata: { + kind: "pipeline" + } + }); + + await taskList.list("plans").fire("prefixed", "plan"); + + const frontmatter = parseFrontmatter( + await rawFs.readFile("/repo/tasks/07-prefixed.md", "utf8") + ); + expect(frontmatter).toMatchObject({ + kind: "pipeline", + state: "planned" + }); + expect(frontmatter).not.toHaveProperty("name"); + }); + + it("updates passthrough metadata without injecting synthesized fields", async () => { + const pipelineSchema = + "https://poe-platform.github.io/poe-code/schemas/plans/pipeline.schema.json"; + const { fs, rawFs } = createFs({ + "/repo/tasks/foo.md": `--- +$schema: ${pipelineSchema} +kind: pipeline +version: 1 +--- + +` + }); + const taskList = await markdownDirBackend({ + path: "/repo/tasks", + singleList: "plans", + frontmatterMode: "passthrough", + defaults: { + metadata: {} + }, + lockStaleMs: 30_000, + lockRetries: 20, + create: false, + fs + }); + + await expect( + taskList.list("plans").update("foo", { + description: "Updated body", + metadata: { + owner: "kj" + } + }) + ).resolves.toMatchObject({ + name: "foo", + state: "draft", + description: "Updated body", + metadata: { + $schema: pipelineSchema, + kind: "pipeline", + version: 1, + owner: "kj" + } + }); + + const content = await rawFs.readFile("/repo/tasks/foo.md", "utf8"); + const frontmatter = parseFrontmatter(content); + expect(frontmatter).toMatchObject({ + $schema: pipelineSchema, + kind: "pipeline", + version: 1, + owner: "kj" + }); + expect(frontmatter).not.toHaveProperty("name"); + expect(frontmatter).not.toHaveProperty("state"); + expect(content).toContain("Updated body"); + }); + + it("does not inject task envelope fields when creating passthrough markdown", async () => { + const { fs, rawFs } = createFs({ + "/repo/tasks/.keep": "" + }); + const taskList = await markdownDirBackend({ + path: "/repo/tasks", + singleList: "plans", + frontmatterMode: "passthrough", + defaults: { + metadata: {} + }, + lockStaleMs: 30_000, + lockRetries: 20, + create: false, + fs + }); + + await expect( + taskList.list("plans").create({ + id: "new-plan", + name: "New plan", + metadata: { + kind: "pipeline" + } + }) + ).resolves.toMatchObject({ + metadata: { + kind: "pipeline" + } + }); + + const frontmatter = parseFrontmatter( + await rawFs.readFile("/repo/tasks/01-new-plan.md", "utf8") + ); + expect(frontmatter).toMatchObject({ + name: "New plan", + state: "draft", + kind: "pipeline" + }); + expect(frontmatter).not.toHaveProperty("$schema"); + expect(frontmatter).not.toHaveProperty("version"); + expect(frontmatter).not.toHaveProperty("created"); + }); + it("ignores hidden entries, lockfiles, and the reserved archive directory at the root", async () => { const { fs } = createFs({ "/repo/tasks/alpha/one.md": `--- diff --git a/packages/task-list/src/backends/markdown-dir.ts b/packages/task-list/src/backends/markdown-dir.ts index f579905afa..dde25d5c51 100644 --- a/packages/task-list/src/backends/markdown-dir.ts +++ b/packages/task-list/src/backends/markdown-dir.ts @@ -49,9 +49,15 @@ const RESERVED_FRONTMATTER_KEYS = new Set([ "state", "version" ]); +const PASSTHROUGH_RESERVED_FRONTMATTER_KEYS = new Set(["description", "name", "state"]); type TaskRecord = Record; +type TaskFields = { + name: string; + state: string; +}; + type TaskFile = { task: Task; frontmatter: TaskRecord; @@ -268,11 +274,19 @@ function assertValidTaskRecord( } } -function metadataFromFrontmatter(frontmatter: TaskRecord): Record { +function reservedFrontmatterKeys(mode: BackendDeps["frontmatterMode"]): ReadonlySet { + return mode === "passthrough" ? PASSTHROUGH_RESERVED_FRONTMATTER_KEYS : RESERVED_FRONTMATTER_KEYS; +} + +function metadataFromFrontmatterForMode( + frontmatter: TaskRecord, + mode: BackendDeps["frontmatterMode"] +): Record { const metadata: Record = {}; + const reservedKeys = reservedFrontmatterKeys(mode); for (const [key, value] of Object.entries(frontmatter)) { - if (!RESERVED_FRONTMATTER_KEYS.has(key)) { + if (!reservedKeys.has(key)) { metadata[key] = value; } } @@ -280,15 +294,45 @@ function metadataFromFrontmatter(frontmatter: TaskRecord): Record, + initialState: string, + frontmatterMode: BackendDeps["frontmatterMode"] +): TaskFields { + if (frontmatterMode === "strict") { + return { + name: frontmatter.name as string, + state: frontmatter.state as string + }; + } + + return { + name: typeof frontmatter.name === "string" ? frontmatter.name : fallbackName, + state: + typeof frontmatter.state === "string" && validStates.has(frontmatter.state) + ? frontmatter.state + : initialState }; } @@ -322,18 +366,30 @@ async function readTaskFile( list: string, id: string, filePath: string, - validStates: ReadonlySet + validStates: ReadonlySet, + initialState: string, + frontmatterMode: BackendDeps["frontmatterMode"] ): Promise { const content = await fs.readFile(filePath, "utf8"); const document = splitTaskDocument(content, filePath); const frontmatter = readFrontmatter(document.frontmatter, filePath); - assertValidTaskRecord(frontmatter, filePath, validStates); + if (frontmatterMode === "strict") { + assertValidTaskRecord(frontmatter, filePath, validStates); + } + const parsed = parseActiveFilename(path.basename(filePath)); + const fields = taskFieldsFromFrontmatter( + frontmatter, + parsed?.id ?? id, + validStates, + initialState, + frontmatterMode + ); return { path: filePath, frontmatter, - task: createTask(list, id, frontmatter, document.body) + task: createTask(list, id, frontmatter, document.body, frontmatterMode, fields) }; } @@ -385,7 +441,9 @@ async function readTaskAtLocation( layout: ListLayout, list: string, id: string, - validStates: ReadonlySet + validStates: ReadonlySet, + initialState: string, + frontmatterMode: BackendDeps["frontmatterMode"] ): Promise { const location = await findTaskLocation(fs, rootPath, layout, list, id); @@ -393,54 +451,75 @@ async function readTaskAtLocation( throw new TaskNotFoundError(`Task "${list}/${id}" not found.`); } - return readTaskFile(fs, list, id, location.path, validStates); + return readTaskFile(fs, list, id, location.path, validStates, initialState, frontmatterMode); } function createdFrontmatter( defaults: BackendDeps["defaults"], input: TaskCreate, - initialState: string + initialState: string, + frontmatterMode: BackendDeps["frontmatterMode"] ): TaskRecord { - const frontmatter: TaskRecord = { - $schema: TASK_SCHEMA_ID, - kind: TASK_KIND, - version: TASK_VERSION, - name: input.name, - state: initialState - }; + const frontmatter: TaskRecord = + frontmatterMode === "strict" + ? { + $schema: TASK_SCHEMA_ID, + kind: TASK_KIND, + version: TASK_VERSION, + name: input.name, + state: initialState + } + : { + name: input.name, + state: initialState + }; + const reservedKeys = reservedFrontmatterKeys(frontmatterMode); for (const [key, value] of Object.entries(defaults.metadata)) { - if (!RESERVED_FRONTMATTER_KEYS.has(key)) { + if (!reservedKeys.has(key)) { frontmatter[key] = value; } } for (const [key, value] of Object.entries(input.metadata ?? {})) { - if (!RESERVED_FRONTMATTER_KEYS.has(key)) { + if (!reservedKeys.has(key)) { frontmatter[key] = value; } } - frontmatter.created = new Date().toISOString(); + if (frontmatterMode === "strict") { + frontmatter.created = new Date().toISOString(); + } return frontmatter; } function updatedFrontmatter( existingFrontmatter: TaskRecord, task: Task, - patch: TaskUpdate + patch: TaskUpdate, + frontmatterMode: BackendDeps["frontmatterMode"] ): TaskRecord { - const nextFrontmatter: TaskRecord = { - ...existingFrontmatter, - $schema: existingFrontmatter.$schema ?? TASK_SCHEMA_ID, - kind: existingFrontmatter.kind ?? TASK_KIND, - version: existingFrontmatter.version ?? TASK_VERSION, - name: patch.name ?? task.name, - state: task.state - }; + const nextFrontmatter: TaskRecord = + frontmatterMode === "strict" + ? { + ...existingFrontmatter, + $schema: existingFrontmatter.$schema ?? TASK_SCHEMA_ID, + kind: existingFrontmatter.kind ?? TASK_KIND, + version: existingFrontmatter.version ?? TASK_VERSION, + name: patch.name ?? task.name, + state: task.state + } + : { + ...existingFrontmatter + }; + + if (frontmatterMode === "passthrough" && patch.name !== undefined) { + nextFrontmatter.name = patch.name; + } + const reservedKeys = reservedFrontmatterKeys(frontmatterMode); for (const [key, value] of Object.entries(patch.metadata ?? {})) { - if (!RESERVED_FRONTMATTER_KEYS.has(key)) { + if (!reservedKeys.has(key)) { nextFrontmatter[key] = value; } } @@ -451,28 +530,36 @@ function updatedFrontmatter( function transitionedFrontmatter( existingFrontmatter: TaskRecord, task: Task, - to: string + to: string, + frontmatterMode: BackendDeps["frontmatterMode"] ): TaskRecord { - return { - ...existingFrontmatter, - $schema: existingFrontmatter.$schema ?? TASK_SCHEMA_ID, - kind: existingFrontmatter.kind ?? TASK_KIND, - version: existingFrontmatter.version ?? TASK_VERSION, - name: task.name, - state: to - }; + return frontmatterMode === "strict" + ? { + ...existingFrontmatter, + $schema: existingFrontmatter.$schema ?? TASK_SCHEMA_ID, + kind: existingFrontmatter.kind ?? TASK_KIND, + version: existingFrontmatter.version ?? TASK_VERSION, + name: task.name, + state: to + } + : { + ...existingFrontmatter, + state: to + }; } function firedFrontmatter( existingFrontmatter: TaskRecord, task: Task, to: string, + frontmatterMode: BackendDeps["frontmatterMode"], metadataPatch?: Record ): TaskRecord { - const nextFrontmatter = transitionedFrontmatter(existingFrontmatter, task, to); + const nextFrontmatter = transitionedFrontmatter(existingFrontmatter, task, to, frontmatterMode); + const reservedKeys = reservedFrontmatterKeys(frontmatterMode); for (const [key, value] of Object.entries(metadataPatch ?? {})) { - if (!RESERVED_FRONTMATTER_KEYS.has(key)) { + if (!reservedKeys.has(key)) { nextFrontmatter[key] = value; } } @@ -546,7 +633,15 @@ function createTasksView(deps: BackendDeps, layout: ListLayout, list: string): T for (const entry of entries) { const filePath = path.join(listDirectoryPath, entry.filename); - const file = await readTaskFile(deps.fs, list, entry.id, filePath, validStates); + const file = await readTaskFile( + deps.fs, + list, + entry.id, + filePath, + validStates, + stateMachine.initial, + deps.frontmatterMode + ); tasks.set(entry.id, { task: file.task, raw: file.frontmatter }); } @@ -566,7 +661,15 @@ function createTasksView(deps: BackendDeps, layout: ListLayout, list: string): T if (!entryStat?.isFile()) continue; const id = entryName.slice(0, -MARKDOWN_EXTENSION.length); - const file = await readTaskFile(deps.fs, list, id, entryPath, validStates); + const file = await readTaskFile( + deps.fs, + list, + id, + entryPath, + validStates, + stateMachine.initial, + deps.frontmatterMode + ); result.push({ task: file.task, raw: file.frontmatter }); } @@ -632,7 +735,16 @@ function createTasksView(deps: BackendDeps, layout: ListLayout, list: string): T async function getTaskFile(id: string): Promise { validateTaskId(id); - return readTaskAtLocation(deps.fs, deps.path, layout, list, id, validStates); + return readTaskAtLocation( + deps.fs, + deps.path, + layout, + list, + id, + validStates, + stateMachine.initial, + deps.frontmatterMode + ); } function assertFireableTaskEvent(task: Task, eventName: string) { @@ -697,12 +809,17 @@ function createTasksView(deps: BackendDeps, layout: ListLayout, list: string): T const filename = activeTaskFilename(input.id, nextOrder, width); const targetPath = path.join(listDirectoryPath, filename); - const frontmatter = createdFrontmatter(deps.defaults, input, stateMachine.initial); + const frontmatter = createdFrontmatter( + deps.defaults, + input, + stateMachine.initial, + deps.frontmatterMode + ); const description = input.description ?? ""; await writeAtomically(deps.fs, targetPath, serializeTaskDocument(frontmatter, description)); - return createTask(list, input.id, frontmatter, description); + return createTask(list, input.id, frontmatter, description, deps.frontmatterMode); }); }, async update(id: string, patch: TaskUpdate): Promise { @@ -710,8 +827,17 @@ function createTasksView(deps: BackendDeps, layout: ListLayout, list: string): T return withTaskLock(id, async () => { const existing = await getTaskFile(id); - const nextFrontmatter = updatedFrontmatter(existing.frontmatter, existing.task, patch); + const nextFrontmatter = updatedFrontmatter( + existing.frontmatter, + existing.task, + patch, + deps.frontmatterMode + ); const description = patch.description ?? existing.task.description; + const fields = { + name: patch.name ?? existing.task.name, + state: existing.task.state + }; await writeAtomically( deps.fs, @@ -719,7 +845,7 @@ function createTasksView(deps: BackendDeps, layout: ListLayout, list: string): T serializeTaskDocument(nextFrontmatter, description) ); - return createTask(list, id, nextFrontmatter, description); + return createTask(list, id, nextFrontmatter, description, deps.frontmatterMode, fields); }); }, async fire(id: string, eventName: string, opts?: TaskFireOptions): Promise { @@ -743,9 +869,20 @@ function createTasksView(deps: BackendDeps, layout: ListLayout, list: string): T existing.frontmatter, existing.task, event.to, + deps.frontmatterMode, opts?.metadataPatch ); - const nextTask = createTask(list, id, nextFrontmatter, existing.task.description); + const nextTask = createTask( + list, + id, + nextFrontmatter, + existing.task.description, + deps.frontmatterMode, + { + name: existing.task.name, + state: event.to + } + ); const serializedTask = serializeTaskDocument(nextFrontmatter, existing.task.description); if (event.to === "archived") { @@ -851,8 +988,12 @@ function createTasksView(deps: BackendDeps, layout: ListLayout, list: string): T export async function markdownDirBackend(deps: BackendDeps): Promise { await ensureRootPath(deps); - const layout = resolveListLayout(deps); - const stateMachine = resolveStateMachine(deps.stateMachine); + const backendDeps: BackendDeps = { + ...deps, + frontmatterMode: deps.frontmatterMode ?? "strict" + }; + const layout = resolveListLayout(backendDeps); + const stateMachine = resolveStateMachine(backendDeps.stateMachine); const validStates = new Set(stateMachine.states); const list = (name: string): Tasks => { @@ -861,11 +1002,11 @@ export async function markdownDirBackend(deps: BackendDeps): Promise { throw new Error(`Task list "${name}" not found.`); } - return createTasksView(deps, layout, layout.name); + return createTasksView(backendDeps, layout, layout.name); } const listName = validateListName(name); - return createTasksView(deps, layout, listName); + return createTasksView(backendDeps, layout, listName); }; const lists = async (): Promise => { @@ -873,7 +1014,7 @@ export async function markdownDirBackend(deps: BackendDeps): Promise { return [layout.name]; } - const entries = await readDirectoryNames(deps.fs, deps.path); + const entries = await readDirectoryNames(backendDeps.fs, backendDeps.path); const result: string[] = []; for (const entryName of entries) { @@ -885,8 +1026,8 @@ export async function markdownDirBackend(deps: BackendDeps): Promise { continue; } - const entryPath = path.join(deps.path, entryName); - const entryStat = await statIfExists(deps.fs, entryPath); + const entryPath = path.join(backendDeps.path, entryName); + const entryStat = await statIfExists(backendDeps.fs, entryPath); if (entryStat?.isDirectory()) { result.push(entryName); } @@ -921,32 +1062,46 @@ export async function markdownDirBackend(deps: BackendDeps): Promise { if (sourceListName === targetListName) { const file = await readTaskAtLocation( - deps.fs, - deps.path, + backendDeps.fs, + backendDeps.path, layout, sourceListName, id, - validStates + validStates, + stateMachine.initial, + backendDeps.frontmatterMode ); return file.task; } - const targetExisting = await findTaskLocation(deps.fs, deps.path, layout, targetListName, id); + const targetExisting = await findTaskLocation( + backendDeps.fs, + backendDeps.path, + layout, + targetListName, + id + ); if (targetExisting) { throw new TaskAlreadyExistsError(`Task "${targetListName}/${id}" already exists.`); } - const sourceLocation = await findTaskLocation(deps.fs, deps.path, layout, sourceListName, id); + const sourceLocation = await findTaskLocation( + backendDeps.fs, + backendDeps.path, + layout, + sourceListName, + id + ); if (!sourceLocation) { throw new TaskNotFoundError(`Task "${sourceListName}/${id}" not found.`); } - const targetListDir = listPath(deps.path, layout, targetListName); - await deps.fs.mkdir(targetListDir, { recursive: true }); + const targetListDir = listPath(backendDeps.path, layout, targetListName); + await backendDeps.fs.mkdir(targetListDir, { recursive: true }); const targetEntries = await (async () => { const out: ActiveEntry[] = []; - const names = await readDirectoryNames(deps.fs, targetListDir); + const names = await readDirectoryNames(backendDeps.fs, targetListDir); for (const entryName of names) { if (isHiddenEntry(entryName) || isLockFile(entryName)) continue; const parsed = parseActiveFilename(entryName); @@ -957,11 +1112,19 @@ export async function markdownDirBackend(deps: BackendDeps): Promise { })(); if (sourceLocation.archived) { - const archivedTargetDir = archiveDirectoryPath(deps.path, layout, targetListName); - await deps.fs.mkdir(archivedTargetDir, { recursive: true }); - const archivedTargetPath = archivedTaskPath(deps.path, layout, targetListName, id); - await deps.fs.rename(sourceLocation.path, archivedTargetPath); - const file = await readTaskFile(deps.fs, targetListName, id, archivedTargetPath, validStates); + const archivedTargetDir = archiveDirectoryPath(backendDeps.path, layout, targetListName); + await backendDeps.fs.mkdir(archivedTargetDir, { recursive: true }); + const archivedTargetPath = archivedTaskPath(backendDeps.path, layout, targetListName, id); + await backendDeps.fs.rename(sourceLocation.path, archivedTargetPath); + const file = await readTaskFile( + backendDeps.fs, + targetListName, + id, + archivedTargetPath, + validStates, + stateMachine.initial, + backendDeps.frontmatterMode + ); return file.task; } @@ -973,8 +1136,16 @@ export async function markdownDirBackend(deps: BackendDeps): Promise { const targetFilename = activeTaskFilename(id, maxOrder + 1, width); const targetPath = path.join(targetListDir, targetFilename); - await deps.fs.rename(sourceLocation.path, targetPath); - const file = await readTaskFile(deps.fs, targetListName, id, targetPath, validStates); + await backendDeps.fs.rename(sourceLocation.path, targetPath); + const file = await readTaskFile( + backendDeps.fs, + targetListName, + id, + targetPath, + validStates, + stateMachine.initial, + backendDeps.frontmatterMode + ); return file.task; }; From 5caa5f1d58260944957ebdb3487243b7df02bc9d Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 05:19:52 -0500 Subject: [PATCH 091/111] fix(task-list): repack prefixes after archive --- docs/plans/zharness-plans-via-task-list.md | 8 +- .../zharness-plans-via-task-list.md.lock | 2 +- .../src/backends/markdown-dir.test.ts | 225 +++++++++++++++++- .../task-list/src/backends/markdown-dir.ts | 114 +++++---- 4 files changed, 295 insertions(+), 54 deletions(-) diff --git a/docs/plans/zharness-plans-via-task-list.md b/docs/plans/zharness-plans-via-task-list.md index d6bef9cfa2..5d8e2f1952 100644 --- a/docs/plans/zharness-plans-via-task-list.md +++ b/docs/plans/zharness-plans-via-task-list.md @@ -170,7 +170,7 @@ tasks: implement: done refactor: done test: done - commit: open + commit: done - id: markdown-dir-archive-repack title: markdown-dir fire(archive) repacks remaining prefixes @@ -220,9 +220,9 @@ tasks: - Strict-mode tests with the default state machine continue to pass. - Do not change behavior for non-archive `fire` calls. status: - implement: open - test: open - commit: open + implement: done + test: done + commit: done - id: agent-harness-tools-plans title: agent-harness-tools — discoverPlans / archivePlan / openPlanList diff --git a/docs/plans/zharness-plans-via-task-list.md.lock b/docs/plans/zharness-plans-via-task-list.md.lock index 1d10276ffc..bc7d1103c4 100644 --- a/docs/plans/zharness-plans-via-task-list.md.lock +++ b/docs/plans/zharness-plans-via-task-list.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T10:10:57.463Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T10:18:52.356Z"} \ No newline at end of file diff --git a/packages/task-list/src/backends/markdown-dir.test.ts b/packages/task-list/src/backends/markdown-dir.test.ts index aea2154367..3ee39bf8cd 100644 --- a/packages/task-list/src/backends/markdown-dir.test.ts +++ b/packages/task-list/src/backends/markdown-dir.test.ts @@ -1,9 +1,12 @@ +import path from "node:path"; import { parseDocument } from "yaml"; import { afterEach, describe, expect, it, vi } from "vitest"; import { openTaskList } from "../open.js"; -import { MalformedTaskError } from "../types.js"; +import { MalformedTaskError, type TaskListFs } from "../types.js"; import { markdownDirBackend } from "./markdown-dir.js"; -import { createDeferred, createFs, waitForCondition } from "./test-helpers.js"; +import { createDeferred, createFs, flushMicrotasks, waitForCondition } from "./test-helpers.js"; + +type TestFs = ReturnType["rawFs"]; function parseFrontmatter(content: string): Record { const lines = content.split("\n"); @@ -27,6 +30,37 @@ state: ${state} `; } +async function markdownEntries(rawFs: TestFs, directoryPath: string): Promise { + const entries = await rawFs.readdir(directoryPath); + return entries + .filter((entryName) => entryName.endsWith(".md")) + .sort((left, right) => left.localeCompare(right)); +} + +async function recursiveListing( + rawFs: TestFs, + directoryPath: string, + prefix = "" +): Promise { + const entries = await rawFs.readdir(directoryPath); + const listing: string[] = []; + + for (const entryName of entries.sort((left, right) => left.localeCompare(right))) { + const relativePath = prefix === "" ? entryName : `${prefix}/${entryName}`; + const entryPath = path.join(directoryPath, entryName); + const entryStat = await rawFs.stat(entryPath); + + if (entryStat.isDirectory()) { + listing.push(`${relativePath}/`); + listing.push(...(await recursiveListing(rawFs, entryPath, relativePath))); + } else { + listing.push(relativePath); + } + } + + return listing; +} + describe("markdownDirBackend", () => { afterEach(() => { vi.useRealTimers(); @@ -607,6 +641,193 @@ state: draft ).resolves.toContain("state: archived"); }); + it("re-packs active prefixes when archiving a multi-list task", async () => { + const { fs, rawFs } = createFs({ + "/repo/tasks/planning/01-foo.md": taskDocument("Foo"), + "/repo/tasks/planning/02-bar.md": taskDocument("Bar"), + "/repo/tasks/planning/03-baz.md": taskDocument("Baz") + }); + const taskList = await markdownDirBackend({ + path: "/repo/tasks", + defaults: { + metadata: {} + }, + lockStaleMs: 30_000, + lockRetries: 20, + create: false, + fs + }); + + await taskList.list("planning").fire("bar", "archive"); + + await expect(markdownEntries(rawFs, "/repo/tasks/planning")).resolves.toEqual([ + "01-foo.md", + "02-baz.md" + ]); + await expect(markdownEntries(rawFs, "/repo/tasks/planning/archive")).resolves.toEqual([ + "bar.md" + ]); + await expect(recursiveListing(rawFs, "/repo/tasks/planning")).resolves.toMatchInlineSnapshot(` + [ + "01-foo.md", + "02-baz.md", + "archive/", + "archive/bar.md", + ] + `); + }); + + it("re-packs active prefixes when archiving a single-list root task", async () => { + const { fs, rawFs } = createFs({ + "/repo/tasks/01-foo.md": taskDocument("Foo"), + "/repo/tasks/02-bar.md": taskDocument("Bar"), + "/repo/tasks/03-baz.md": taskDocument("Baz") + }); + const taskList = await markdownDirBackend({ + path: "/repo/tasks", + singleList: "plans", + frontmatterMode: "passthrough", + defaults: { + metadata: {} + }, + lockStaleMs: 30_000, + lockRetries: 20, + create: false, + fs + }); + + await taskList.list("plans").fire("bar", "archive"); + + await expect(markdownEntries(rawFs, "/repo/tasks")).resolves.toEqual([ + "01-foo.md", + "02-baz.md" + ]); + await expect(markdownEntries(rawFs, "/repo/tasks/archive")).resolves.toEqual(["bar.md"]); + await expect(recursiveListing(rawFs, "/repo/tasks")).resolves.toMatchInlineSnapshot(` + [ + "01-foo.md", + "02-baz.md", + "archive/", + "archive/bar.md", + ] + `); + }); + + it("leaves no active markdown files when archiving the only single-list task", async () => { + const { fs, rawFs } = createFs({ + "/repo/tasks/01-only.md": taskDocument("Only") + }); + const taskList = await markdownDirBackend({ + path: "/repo/tasks", + singleList: "plans", + frontmatterMode: "passthrough", + defaults: { + metadata: {} + }, + lockStaleMs: 30_000, + lockRetries: 20, + create: false, + fs + }); + + await taskList.list("plans").fire("only", "archive"); + + await expect(markdownEntries(rawFs, "/repo/tasks")).resolves.toEqual([]); + await expect(markdownEntries(rawFs, "/repo/tasks/archive")).resolves.toEqual(["only.md"]); + }); + + it("leaves only the archive directory when archiving the only multi-list task", async () => { + const { fs, rawFs } = createFs({ + "/repo/tasks/planning/01-only.md": taskDocument("Only") + }); + const taskList = await markdownDirBackend({ + path: "/repo/tasks", + defaults: { + metadata: {} + }, + lockStaleMs: 30_000, + lockRetries: 20, + create: false, + fs + }); + + await taskList.list("planning").fire("only", "archive"); + + await expect(rawFs.readdir("/repo/tasks/planning")).resolves.toEqual(["archive"]); + await expect(markdownEntries(rawFs, "/repo/tasks/planning/archive")).resolves.toEqual([ + "only.md" + ]); + }); + + it("serializes concurrent archive prefix re-packs under the list lock", async () => { + vi.useFakeTimers(); + vi.spyOn(Math, "random").mockReturnValue(0); + + const baseFs = createFs({ + "/repo/tasks/planning/01-foo.md": taskDocument("Foo"), + "/repo/tasks/planning/02-bar.md": taskDocument("Bar"), + "/repo/tasks/planning/03-baz.md": taskDocument("Baz"), + "/repo/tasks/planning/04-qux.md": taskDocument("Qux") + }); + const archiveRenames = [createDeferred(), createDeferred()]; + const startedArchiveIds: string[] = []; + const fs: TaskListFs = { + ...baseFs.fs, + rename: async (oldPath, newPath) => { + const archivePrefix = "/repo/tasks/planning/archive/"; + const targetPath = String(newPath); + + if ( + targetPath.startsWith(archivePrefix) && + targetPath.endsWith(".md") && + startedArchiveIds.length < archiveRenames.length + ) { + const archiveId = path.basename(targetPath, ".md"); + const blockerIndex = startedArchiveIds.length; + startedArchiveIds.push(archiveId); + await archiveRenames[blockerIndex].promise; + } + + return baseFs.rawFs.rename(oldPath, newPath); + } + }; + const taskList = await markdownDirBackend({ + path: "/repo/tasks", + defaults: { + metadata: {} + }, + lockStaleMs: 30_000, + lockRetries: 20, + create: false, + fs + }); + const tasks = taskList.list("planning"); + + const firstArchive = tasks.fire("foo", "archive"); + const secondArchive = tasks.fire("bar", "archive"); + + await waitForCondition(() => startedArchiveIds.length === 1); + expect(startedArchiveIds).toEqual(["foo"]); + + archiveRenames[0].resolve(); + await flushMicrotasks(); + await vi.advanceTimersByTimeAsync(25); + await waitForCondition(() => startedArchiveIds.length === 2); + expect(startedArchiveIds).toEqual(["foo", "bar"]); + + archiveRenames[1].resolve(); + await Promise.all([firstArchive, secondArchive]); + + await expect(markdownEntries(baseFs.rawFs, "/repo/tasks/planning")).resolves.toEqual([ + "01-baz.md", + "02-qux.md" + ]); + await expect(markdownEntries(baseFs.rawFs, "/repo/tasks/planning/archive")).resolves.toEqual([ + "bar.md", + "foo.md" + ]); + }); + it("does not contend for updates to different task paths", async () => { const baseFs = createFs({ "/repo/tasks/.keep": "" diff --git a/packages/task-list/src/backends/markdown-dir.ts b/packages/task-list/src/backends/markdown-dir.ts index dde25d5c51..5e5d3ba919 100644 --- a/packages/task-list/src/backends/markdown-dir.ts +++ b/packages/task-list/src/backends/markdown-dir.ts @@ -730,7 +730,18 @@ function createTasksView(deps: BackendDeps, layout: ListLayout, list: string): T async function withTaskLock(id: string, action: () => Promise): Promise { validateTaskId(id); - return withListLock(action); + await deps.fs.mkdir(listDirectoryPath, { recursive: true }); + const release = await acquireFileLock(path.join(listDirectoryPath, `${id}.task`), { + fs: deps.fs, + staleMs: deps.lockStaleMs, + retries: deps.lockRetries + }); + + try { + return await action(); + } finally { + await release(); + } } async function getTaskFile(id: string): Promise { @@ -849,62 +860,71 @@ function createTasksView(deps: BackendDeps, layout: ListLayout, list: string): T }); }, async fire(id: string, eventName: string, opts?: TaskFireOptions): Promise { - return withTaskLock(id, async () => { - const existing = await getTaskFile(id); - const event = assertFireableTaskEvent(existing.task, eventName); - const guardResult = event.guard?.(existing.task) ?? true; - - if (guardResult !== true) { - throw new InvalidTransitionError({ - task: existing.task, - event: eventName, - to: event.to, - reason: guardResult - }); - } - - await event.onExit?.(existing.task); - - const nextFrontmatter = firedFrontmatter( - existing.frontmatter, - existing.task, - event.to, - deps.frontmatterMode, - opts?.metadataPatch - ); - const nextTask = createTask( - list, - id, - nextFrontmatter, - existing.task.description, - deps.frontmatterMode, - { - name: existing.task.name, - state: event.to + const runFire = async (): Promise => + withTaskLock(id, async () => { + const existing = await getTaskFile(id); + const event = assertFireableTaskEvent(existing.task, eventName); + const guardResult = event.guard?.(existing.task) ?? true; + + if (guardResult !== true) { + throw new InvalidTransitionError({ + task: existing.task, + event: eventName, + to: event.to, + reason: guardResult + }); } - ); - const serializedTask = serializeTaskDocument(nextFrontmatter, existing.task.description); - if (event.to === "archived") { - const targetPath = archivedTaskPath(deps.path, layout, list, id); - const archivedTargetExists = await statIfExists(deps.fs, targetPath); - if (archivedTargetExists?.isFile()) { - throw new TaskAlreadyExistsError(`Task "${list}/${id}" already exists in archive.`); + await event.onExit?.(existing.task); + + const nextFrontmatter = firedFrontmatter( + existing.frontmatter, + existing.task, + event.to, + deps.frontmatterMode, + opts?.metadataPatch + ); + const nextTask = createTask( + list, + id, + nextFrontmatter, + existing.task.description, + deps.frontmatterMode, + { + name: existing.task.name, + state: event.to + } + ); + const serializedTask = serializeTaskDocument(nextFrontmatter, existing.task.description); + + if (event.to === "archived") { + const targetPath = archivedTaskPath(deps.path, layout, list, id); + const archivedTargetExists = await statIfExists(deps.fs, targetPath); + if (archivedTargetExists?.isFile()) { + throw new TaskAlreadyExistsError(`Task "${list}/${id}" already exists in archive.`); + } + + await writeAtomically(deps.fs, existing.path, serializedTask); + await deps.fs.mkdir(archiveDirectoryPath(deps.path, layout, list), { recursive: true }); + await deps.fs.rename(existing.path, targetPath); + const { entries: remainingEntries } = await readActiveTasks(); + await rewriteListPrefixes(remainingEntries.map((entry) => entry.id)); + await event.onEnter?.(nextTask); + + return nextTask; } await writeAtomically(deps.fs, existing.path, serializedTask); - await deps.fs.mkdir(archiveDirectoryPath(deps.path, layout, list), { recursive: true }); - await deps.fs.rename(existing.path, targetPath); await event.onEnter?.(nextTask); return nextTask; - } + }); - await writeAtomically(deps.fs, existing.path, serializedTask); - await event.onEnter?.(nextTask); + if (stateMachine.events[eventName]?.to === "archived") { + return withListLock(runFire); + } - return nextTask; - }); + return runFire(); }, async canFire(id: string, eventName: string): Promise { const task = (await getTaskFile(id)).task; From 349617bb462620c14bd0234b0ff723c4f81e4ffa Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 05:29:36 -0500 Subject: [PATCH 092/111] feat(agent-harness-tools): add plan helpers --- docs/plans/zharness-plans-via-task-list.md | 8 +- .../zharness-plans-via-task-list.md.lock | 2 +- package-lock.json | 1 + packages/agent-harness-tools/package.json | 1 + packages/agent-harness-tools/src/index.ts | 9 + .../agent-harness-tools/src/plans.test.ts | 291 ++++++++++++++++++ packages/agent-harness-tools/src/plans.ts | 223 ++++++++++++++ 7 files changed, 530 insertions(+), 5 deletions(-) create mode 100644 packages/agent-harness-tools/src/plans.test.ts create mode 100644 packages/agent-harness-tools/src/plans.ts diff --git a/docs/plans/zharness-plans-via-task-list.md b/docs/plans/zharness-plans-via-task-list.md index 5d8e2f1952..d2046d880b 100644 --- a/docs/plans/zharness-plans-via-task-list.md +++ b/docs/plans/zharness-plans-via-task-list.md @@ -336,10 +336,10 @@ tasks: - No `@modelcontextprotocol/sdk`, no `child_process`. - No new env vars or CLI flags. status: - implement: open - refactor: open - test: open - commit: open + implement: done + refactor: done + test: done + commit: done - id: agent-harness-tools-export title: Re-export plans API from agent-harness-tools index diff --git a/docs/plans/zharness-plans-via-task-list.md.lock b/docs/plans/zharness-plans-via-task-list.md.lock index bc7d1103c4..97ebba70e7 100644 --- a/docs/plans/zharness-plans-via-task-list.md.lock +++ b/docs/plans/zharness-plans-via-task-list.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T10:18:52.356Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T10:28:04.391Z"} \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index e940972d18..2945b30f95 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7289,6 +7289,7 @@ "@poe-code/agent-defs": "*", "@poe-code/design-system": "*", "@poe-code/file-lock": "*", + "@poe-code/task-list": "workspace:*", "@poe-code/poe-code-config": "*", "@poe-code/process-runner": "*" } diff --git a/packages/agent-harness-tools/package.json b/packages/agent-harness-tools/package.json index 8e355d23c7..83161503ca 100644 --- a/packages/agent-harness-tools/package.json +++ b/packages/agent-harness-tools/package.json @@ -23,6 +23,7 @@ "@poe-code/agent-defs": "*", "@poe-code/design-system": "*", "@poe-code/file-lock": "*", + "@poe-code/task-list": "workspace:*", "@poe-code/poe-code-config": "*", "@poe-code/process-runner": "*" } diff --git a/packages/agent-harness-tools/src/index.ts b/packages/agent-harness-tools/src/index.ts index 02df75e678..9f279de112 100644 --- a/packages/agent-harness-tools/src/index.ts +++ b/packages/agent-harness-tools/src/index.ts @@ -3,6 +3,15 @@ export { resolveWorkflowPath, type DiscoverDocsOptions } from "./paths.js"; +export { + archivePlan, + discoverPlans, + openPlanList, + type ArchivePlanOptions, + type DiscoverPlansOptions, + type OpenPlanListOptions, + type PlanRef +} from "./plans.js"; export { normalizeParticipantConfig, selectParticipantAgent, diff --git a/packages/agent-harness-tools/src/plans.test.ts b/packages/agent-harness-tools/src/plans.test.ts new file mode 100644 index 0000000000..9ff17ccd1d --- /dev/null +++ b/packages/agent-harness-tools/src/plans.test.ts @@ -0,0 +1,291 @@ +import { createFsFromVolume, Volume } from "memfs"; +import { describe, expect, it } from "vitest"; +import { TaskNotFoundError, type TaskListFs } from "@poe-code/task-list"; +import { + archivePlan, + discoverPlans, + openPlanList, + type DiscoverPlansOptions +} from "./plans.js"; + +const cwd = "/repo"; +const homeDir = "/home/test"; +const planDirectory = ".poe-code/plans"; + +type TestFs = TaskListFs; + +function createFs( + files: Record, + directories: string[] = [] +): { + fs: TestFs; + rawFs: ReturnType; +} { + const volume = Volume.fromJSON(files, "/"); + + volume.mkdirSync(cwd, { recursive: true }); + volume.mkdirSync(homeDir, { recursive: true }); + + for (const directory of directories) { + volume.mkdirSync(directory, { recursive: true }); + } + + const rawFs = createFsFromVolume(volume); + return { fs: rawFs.promises as unknown as TestFs, rawFs }; +} + +function planDocument(options: { name?: string; kind?: string; state?: string } = {}): string { + const lines = ["---"]; + + if (options.name !== undefined) { + lines.push(`name: ${options.name}`); + } + + if (options.kind !== undefined) { + lines.push(`kind: ${options.kind}`); + } + + if (options.state !== undefined) { + lines.push(`state: ${options.state}`); + } + + lines.push("---", "", ""); + return lines.join("\n"); +} + +function discoverOptions(fs: TestFs): DiscoverPlansOptions { + return { + cwd, + homeDir, + planDirectory, + fs + }; +} + +async function markdownEntries( + rawFs: ReturnType, + directoryPath: string +): Promise { + const entries = await rawFs.promises.readdir(directoryPath); + return entries + .filter((entryName) => entryName.endsWith(".md")) + .sort((left, right) => left.localeCompare(right)); +} + +describe("plans", () => { + it("discovers plans with kind from frontmatter metadata", async () => { + const { fs } = createFs({ + "/repo/.poe-code/plans/01-build-pipeline.md": planDocument({ + kind: "pipeline" + }), + "/repo/.poe-code/plans/02-plain-plan.md": planDocument({ + name: "Plain plan" + }) + }); + + await expect(discoverPlans(discoverOptions(fs))).resolves.toEqual([ + { + id: "build-pipeline", + name: "build-pipeline", + kind: "pipeline", + absolutePath: "/repo/.poe-code/plans/01-build-pipeline.md", + displayPath: ".poe-code/plans/01-build-pipeline.md" + }, + { + id: "plain-plan", + name: "Plain plan", + kind: "plan", + absolutePath: "/repo/.poe-code/plans/02-plain-plan.md", + displayPath: ".poe-code/plans/02-plain-plan.md" + } + ]); + }); + + it("filters discovered plans by kind", async () => { + const { fs } = createFs({ + "/repo/.poe-code/plans/01-build-pipeline.md": planDocument({ + kind: "pipeline" + }), + "/repo/.poe-code/plans/02-plain-plan.md": planDocument({ + kind: "plan" + }) + }); + + const plans = await discoverPlans({ + ...discoverOptions(fs), + kinds: ["pipeline"] + }); + + expect(plans).toEqual([ + expect.objectContaining({ + id: "build-pipeline", + kind: "pipeline" + }) + ]); + }); + + it("filters discovered plans by the default plan kind", async () => { + const { fs } = createFs({ + "/repo/.poe-code/plans/01-build-pipeline.md": planDocument({ + kind: "pipeline" + }), + "/repo/.poe-code/plans/02-plain-plan.md": planDocument({ + name: "Plain plan" + }) + }); + + const plans = await discoverPlans({ + ...discoverOptions(fs), + kinds: ["plan"] + }); + + expect(plans).toEqual([ + expect.objectContaining({ + id: "plain-plan", + kind: "plan" + }) + ]); + }); + + it("keeps plan kind in task metadata when opening the underlying list", async () => { + const { fs } = createFs({ + "/repo/.poe-code/plans/01-build-pipeline.md": planDocument({ + kind: "pipeline" + }) + }); + + const taskList = await openPlanList(discoverOptions(fs)); + + await expect(taskList.list("plans").get("build-pipeline")).resolves.toEqual( + expect.objectContaining({ + metadata: expect.objectContaining({ + kind: "pipeline" + }) + }) + ); + }); + + it("returns an empty list when the plan directory does not exist", async () => { + const { fs } = createFs({}); + + await expect(discoverPlans(discoverOptions(fs))).resolves.toEqual([]); + }); + + it("uses home-relative display paths for plans outside the workspace under home", async () => { + const { fs } = createFs({ + "/home/test/.poe-code/plans/01-global.md": planDocument({ + name: "Global" + }) + }); + + await expect( + discoverPlans({ + cwd, + homeDir, + planDirectory: "~/.poe-code/plans", + fs + }) + ).resolves.toEqual([ + expect.objectContaining({ + absolutePath: "/home/test/.poe-code/plans/01-global.md", + displayPath: "~/.poe-code/plans/01-global.md" + }) + ]); + }); + + it("uses absolute display paths for plans outside the workspace and home", async () => { + const { fs } = createFs({ + "/tmp/plans/01-external.md": planDocument({ + name: "External" + }) + }); + + await expect( + discoverPlans({ + cwd, + homeDir, + planDirectory: "/tmp/plans", + fs + }) + ).resolves.toEqual([ + expect.objectContaining({ + absolutePath: "/tmp/plans/01-external.md", + displayPath: "/tmp/plans/01-external.md" + }) + ]); + }); + + it("ignores archive and non-plan subdirectories", async () => { + const { fs } = createFs({ + "/repo/.poe-code/plans/01-active.md": planDocument({ + kind: "plan" + }), + "/repo/.poe-code/plans/archive/archived.md": planDocument({ + kind: "pipeline", + state: "archived" + }), + "/repo/.poe-code/plans/notes/ignored.md": planDocument({ + kind: "pipeline" + }) + }); + + await expect(discoverPlans(discoverOptions(fs))).resolves.toEqual([ + expect.objectContaining({ + id: "active", + kind: "plan" + }) + ]); + }); + + it("archives plans and discovers renumbered active prefixes", async () => { + const { fs, rawFs } = createFs({ + "/repo/.poe-code/plans/01-alpha.md": planDocument({ + kind: "plan" + }), + "/repo/.poe-code/plans/02-beta.md": planDocument({ + kind: "pipeline" + }), + "/repo/.poe-code/plans/03-gamma.md": planDocument({ + kind: "plan" + }) + }); + + await archivePlan({ + ...discoverOptions(fs), + id: "beta" + }); + + await expect(markdownEntries(rawFs, "/repo/.poe-code/plans")).resolves.toEqual([ + "01-alpha.md", + "02-gamma.md" + ]); + await expect(markdownEntries(rawFs, "/repo/.poe-code/plans/archive")).resolves.toEqual([ + "beta.md" + ]); + await expect(discoverPlans(discoverOptions(fs))).resolves.toEqual([ + expect.objectContaining({ + id: "alpha", + absolutePath: "/repo/.poe-code/plans/01-alpha.md" + }), + expect.objectContaining({ + id: "gamma", + absolutePath: "/repo/.poe-code/plans/02-gamma.md" + }) + ]); + }); + + it("throws TaskNotFoundError when archiving an unknown plan id", async () => { + const { fs } = createFs({ + "/repo/.poe-code/plans/01-alpha.md": planDocument({ + kind: "plan" + }) + }); + + await expect( + archivePlan({ + ...discoverOptions(fs), + id: "missing" + }) + ).rejects.toBeInstanceOf(TaskNotFoundError); + }); +}); diff --git a/packages/agent-harness-tools/src/plans.ts b/packages/agent-harness-tools/src/plans.ts new file mode 100644 index 0000000000..2c04a6b5f7 --- /dev/null +++ b/packages/agent-harness-tools/src/plans.ts @@ -0,0 +1,223 @@ +import * as fsPromises from "node:fs/promises"; +import path from "node:path"; +import { openTaskList, type Task, type TaskList, type TaskListFs } from "@poe-code/task-list"; +import { resolveWorkflowPath } from "./paths.js"; + +export interface PlanRef { + id: string; + absolutePath: string; + displayPath: string; + kind: string; + name: string; +} + +export interface DiscoverPlansOptions { + cwd: string; + homeDir: string; + planDirectory: string; + kinds?: readonly string[]; + fs?: TaskListFs; +} + +export interface ArchivePlanOptions { + cwd: string; + homeDir: string; + planDirectory: string; + id: string; + fs?: TaskListFs; +} + +export interface OpenPlanListOptions { + cwd: string; + homeDir: string; + planDirectory: string; + fs?: TaskListFs; +} + +function defaultFs(): TaskListFs { + return fsPromises as unknown as TaskListFs; +} + +function isMissingDirectory(error: unknown): boolean { + return ( + !!error && + typeof error === "object" && + "code" in error && + ((error as { code?: unknown }).code === "ENOENT" || + (error as { code?: unknown }).code === "ENOTDIR") + ); +} + +function isUnderDirectory(directoryPath: string, filePath: string): boolean { + const relativePath = path.relative(directoryPath, filePath); + return relativePath === "" || (!relativePath.startsWith("..") && !path.isAbsolute(relativePath)); +} + +function displayPathFor(filePath: string, cwd: string, homeDir: string): string { + if (isUnderDirectory(cwd, filePath)) { + return path.relative(cwd, filePath); + } + + if (isUnderDirectory(homeDir, filePath)) { + const relativePath = path.relative(homeDir, filePath); + return relativePath === "" ? "~" : `~/${relativePath}`; + } + + return filePath; +} + +function isValidTaskIdShape(id: string): boolean { + return ( + id.length > 0 && + !id.startsWith(".") && + !id.includes("/") && + !id.includes("\\") && + !id.includes("..") + ); +} + +function isNumericPrefix(prefix: string): boolean { + if (prefix.length === 0) { + return false; + } + + for (const char of prefix) { + if (char < "0" || char > "9") { + return false; + } + } + + return true; +} + +function idFromActivePlanFilename(fileName: string): string | undefined { + if (!fileName.endsWith(".md")) { + return undefined; + } + + const stem = fileName.slice(0, -".md".length); + const separatorIndex = stem.indexOf("-"); + + if (separatorIndex > 0) { + const prefix = stem.slice(0, separatorIndex); + const id = stem.slice(separatorIndex + 1); + + if (isNumericPrefix(prefix) && isValidTaskIdShape(id)) { + return id; + } + } + + return isValidTaskIdShape(stem) ? stem : undefined; +} + +async function activePlanFilePaths( + fs: TaskListFs, + planDirectory: string +): Promise | undefined> { + let entries: string[]; + + try { + entries = await fs.readdir(planDirectory); + } catch (error) { + if (isMissingDirectory(error)) { + return undefined; + } + + throw error; + } + + const filesById = new Map(); + + for (const entry of entries) { + const id = idFromActivePlanFilename(entry); + + if (id === undefined) { + continue; + } + + filesById.set(id, path.join(planDirectory, entry)); + } + + return filesById; +} + +function openPlansTaskList(planDirectory: string, fs: TaskListFs | undefined): Promise { + return openTaskList({ + type: "markdown-dir", + path: planDirectory, + singleList: "plans", + frontmatterMode: "passthrough", + fs + }); +} + +function planRefFromTask(options: { + task: Task; + absolutePath: string; + cwd: string; + homeDir: string; +}): PlanRef { + const kind = String(options.task.metadata.kind ?? "plan"); + + return { + id: options.task.id, + name: options.task.name, + kind, + absolutePath: options.absolutePath, + displayPath: displayPathFor(options.absolutePath, options.cwd, options.homeDir) + }; +} + +export async function discoverPlans(options: DiscoverPlansOptions): Promise { + const planDirectory = resolveWorkflowPath(options.planDirectory, options.cwd, options.homeDir); + const fs = options.fs ?? defaultFs(); + const filesById = await activePlanFilePaths(fs, planDirectory); + + if (filesById === undefined) { + return []; + } + + const taskList = await openPlansTaskList(planDirectory, options.fs); + const tasks = await taskList.list("plans").all(); + const kindFilter = options.kinds === undefined ? undefined : new Set(options.kinds); + const plans: PlanRef[] = []; + + for (const task of tasks) { + const kind = String(task.metadata.kind ?? "plan"); + + if (kindFilter !== undefined && !kindFilter.has(kind)) { + continue; + } + + const absolutePath = filesById.get(task.id); + + if (absolutePath === undefined) { + continue; + } + + plans.push( + planRefFromTask({ + task, + absolutePath, + cwd: options.cwd, + homeDir: options.homeDir + }) + ); + } + + return plans; +} + +export async function archivePlan(options: ArchivePlanOptions): Promise { + const planDirectory = resolveWorkflowPath(options.planDirectory, options.cwd, options.homeDir); + const taskList = await openPlansTaskList(planDirectory, options.fs); + + await taskList.list("plans").fire(options.id, "archive"); +} + +export function openPlanList(options: OpenPlanListOptions): Promise { + return openPlansTaskList( + resolveWorkflowPath(options.planDirectory, options.cwd, options.homeDir), + options.fs + ); +} From 31a399bf3154b0938d9371bafa09aa8cdb626a20 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 05:30:48 -0500 Subject: [PATCH 093/111] fix(agent-harness-tools): export plan types separately --- docs/plans/zharness-plans-via-task-list.md | 2 +- docs/plans/zharness-plans-via-task-list.md.lock | 2 +- packages/agent-harness-tools/src/index.ts | 14 ++++++++------ 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/docs/plans/zharness-plans-via-task-list.md b/docs/plans/zharness-plans-via-task-list.md index d2046d880b..8a4671fd0f 100644 --- a/docs/plans/zharness-plans-via-task-list.md +++ b/docs/plans/zharness-plans-via-task-list.md @@ -368,7 +368,7 @@ tasks: - Re-export only. No logic changes. - Verify with `npm run build --workspace @poe-code/agent-harness-tools`. status: - implement: open + implement: done commit: open - id: pipeline-migrate diff --git a/docs/plans/zharness-plans-via-task-list.md.lock b/docs/plans/zharness-plans-via-task-list.md.lock index 97ebba70e7..887c32f007 100644 --- a/docs/plans/zharness-plans-via-task-list.md.lock +++ b/docs/plans/zharness-plans-via-task-list.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T10:28:04.391Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T10:30:06.958Z"} \ No newline at end of file diff --git a/packages/agent-harness-tools/src/index.ts b/packages/agent-harness-tools/src/index.ts index 9f279de112..2e96938610 100644 --- a/packages/agent-harness-tools/src/index.ts +++ b/packages/agent-harness-tools/src/index.ts @@ -4,13 +4,15 @@ export { type DiscoverDocsOptions } from "./paths.js"; export { - archivePlan, discoverPlans, - openPlanList, - type ArchivePlanOptions, - type DiscoverPlansOptions, - type OpenPlanListOptions, - type PlanRef + archivePlan, + openPlanList +} from "./plans.js"; +export type { + PlanRef, + DiscoverPlansOptions, + ArchivePlanOptions, + OpenPlanListOptions } from "./plans.js"; export { normalizeParticipantConfig, From 49f0a051fd7eedc3a52f55e4f61db285f92e9384 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 05:37:13 -0500 Subject: [PATCH 094/111] fix(pipeline): use shared plan archive flow --- docs/plans/zharness-plans-via-task-list.md | 6 +- .../zharness-plans-via-task-list.md.lock | 2 +- packages/pipeline/src/pipeline.test.ts | 87 +++++++++++++++---- packages/pipeline/src/plan/discovery.ts | 83 ++++-------------- packages/pipeline/src/run/pipeline.ts | 40 +++++++-- packages/pipeline/src/testing/simulation.ts | 17 ++-- 6 files changed, 129 insertions(+), 106 deletions(-) diff --git a/docs/plans/zharness-plans-via-task-list.md b/docs/plans/zharness-plans-via-task-list.md index 8a4671fd0f..556dd61557 100644 --- a/docs/plans/zharness-plans-via-task-list.md +++ b/docs/plans/zharness-plans-via-task-list.md @@ -369,7 +369,7 @@ tasks: - Verify with `npm run build --workspace @poe-code/agent-harness-tools`. status: implement: done - commit: open + commit: done - id: pipeline-migrate title: Migrate pipeline harness to shared plan API @@ -431,8 +431,8 @@ tasks: happens in a later task. The shared API tolerates files without prefixes. status: - implement: open - test: open + implement: done + test: done commit: open - id: ralph-migrate diff --git a/docs/plans/zharness-plans-via-task-list.md.lock b/docs/plans/zharness-plans-via-task-list.md.lock index 887c32f007..71ba59ab2b 100644 --- a/docs/plans/zharness-plans-via-task-list.md.lock +++ b/docs/plans/zharness-plans-via-task-list.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T10:30:06.958Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T10:36:19.739Z"} \ No newline at end of file diff --git a/packages/pipeline/src/pipeline.test.ts b/packages/pipeline/src/pipeline.test.ts index e5e044de9b..3ecf7f0b84 100644 --- a/packages/pipeline/src/pipeline.test.ts +++ b/packages/pipeline/src/pipeline.test.ts @@ -1801,7 +1801,8 @@ describe("createPipelineSimulation", () => { vi.spyOn(Math, "random").mockReturnValue(0); const fs = createFs({ - "/repo/.poe-code/pipeline/plans/plan.yaml": [ + "/repo/docs/plans/plan.md": [ + "---", `$schema: ${pipelineDocumentSchemaId}`, "kind: pipeline", "version: 1", @@ -1810,11 +1811,12 @@ describe("createPipelineSimulation", () => { " title: Quick fix", " prompt: Fix the timeout regression", " status: open", + "---", "" ].join("\n") }); const onLockStatusChange = vi.fn(); - const initialUnlock = await lockWorkflow("/repo/.poe-code/pipeline/plans/plan.yaml", { + const initialUnlock = await lockWorkflow("/repo/docs/plans/plan.md", { fs, minTimeout: 10, maxTimeout: 10, @@ -1825,7 +1827,7 @@ describe("createPipelineSimulation", () => { agent: "codex", cwd: "/repo", homeDir: "/home/test", - plan: ".poe-code/pipeline/plans/plan.yaml", + plan: "docs/plans/plan.md", fs, onLockStatusChange, runAgent: async () => ({ @@ -1841,8 +1843,7 @@ describe("createPipelineSimulation", () => { await vi.advanceTimersByTimeAsync(1); expect(onLockStatusChange).toHaveBeenNthCalledWith(1, { state: "waiting", - message: - "Another pipeline run is holding the lock for .poe-code/pipeline/plans/plan.yaml. Waiting..." + message: "Another pipeline run is holding the lock for docs/plans/plan.md. Waiting..." }); await initialUnlock(); @@ -1852,7 +1853,7 @@ describe("createPipelineSimulation", () => { expect(onLockStatusChange).toHaveBeenNthCalledWith(2, { state: "acquired", - message: "Lock acquired for .poe-code/pipeline/plans/plan.yaml. Continuing." + message: "Lock acquired for docs/plans/plan.md. Continuing." }); expect(result.stopReason).toBe("completed"); }); @@ -1862,7 +1863,8 @@ describe("createPipelineSimulation", () => { vi.spyOn(Math, "random").mockReturnValue(0); const fs = createFs({ - "/repo/.poe-code/pipeline/plans/plan.yaml": [ + "/repo/docs/plans/plan.md": [ + "---", `$schema: ${pipelineDocumentSchemaId}`, "kind: pipeline", "version: 1", @@ -1871,11 +1873,12 @@ describe("createPipelineSimulation", () => { " title: Quick fix", " prompt: Fix the timeout regression", " status: open", + "---", "" ].join("\n") }); const onLockStatusChange = vi.fn(); - const initialUnlock = await lockWorkflow("/repo/.poe-code/pipeline/plans/plan.yaml", { + const initialUnlock = await lockWorkflow("/repo/docs/plans/plan.md", { fs, minTimeout: 10, maxTimeout: 10, @@ -1886,7 +1889,7 @@ describe("createPipelineSimulation", () => { agent: "codex", cwd: "/repo", homeDir: "/home/test", - plan: ".poe-code/pipeline/plans/plan.yaml", + plan: "docs/plans/plan.md", fs, onLockStatusChange, runAgent: async () => ({ @@ -2660,7 +2663,7 @@ describe("createPipelineSimulation", () => { expect((await readPlan()).tasks[0]?.status).toBe("failed"); }); - it("archives the plan file after all tasks complete", async () => { + it("archives the plan by id and renumbers remaining active plans after all tasks complete", async () => { const sim = createPipelineSimulation({ plan: { tasks: [ @@ -2672,18 +2675,64 @@ describe("createPipelineSimulation", () => { } ] }, - turns: [successTurn()] + turns: [successTurn()], + files: { + "docs/plans/02-follow-up.md": PIPELINE_MD_EMPTY + } }); const { result, fs } = await sim.run(); expect(result.stopReason).toBe("completed"); - const archiveEntries = await fs.readdir("/repo/.poe-code/pipeline/plans/archive"); - expect(archiveEntries).toContain("plan.yaml"); + const archiveEntries = await fs.readdir("/repo/docs/plans/archive"); + expect(archiveEntries).toContain("plan.md"); + + const activeEntries = await fs.readdir("/repo/docs/plans"); + expect(activeEntries.filter((entry) => entry.endsWith(".md")).sort()).toEqual([ + "01-follow-up.md" + ]); + }); - const originalEntries = await fs.readdir("/repo/.poe-code/pipeline/plans"); - expect(originalEntries).not.toContain("plan.yaml"); + it("archives prefixed plans to archive/.md and closes active numbering gaps", async () => { + const fs = createFs({ + "/repo/docs/plans/01-alpha.md": PIPELINE_MD_EMPTY, + "/repo/docs/plans/02-plan.md": [ + "---", + "kind: pipeline", + "tasks:", + " - id: quick-fix", + " title: Quick fix", + " prompt: Fix it", + " status: open", + "---", + "" + ].join("\n"), + "/repo/docs/plans/03-follow-up.md": PIPELINE_MD_EMPTY + }); + + const result = await runPipeline({ + agent: "codex", + cwd: "/repo", + homeDir: "/home/test", + plan: "docs/plans/02-plan.md", + fs, + runAgent: async () => ({ + stdout: "", + exitCode: 0 + }) + }); + + expect(result.stopReason).toBe("completed"); + + const archiveEntries = await fs.readdir("/repo/docs/plans/archive"); + expect(archiveEntries.filter((entry) => entry.endsWith(".md")).sort()).toEqual(["plan.md"]); + + const activeEntries = await fs.readdir("/repo/docs/plans"); + expect(activeEntries.filter((entry) => entry.endsWith(".md")).sort()).toEqual([ + "01-alpha.md", + "02-follow-up.md" + ]); }); it("does not archive when plan was already complete (nothing_to_run)", async () => { @@ -2705,8 +2754,8 @@ describe("createPipelineSimulation", () => { expect(result.stopReason).toBe("nothing_to_run"); - const entries = await fs.readdir("/repo/.poe-code/pipeline/plans"); - expect(entries).toContain("plan.yaml"); + const entries = await fs.readdir("/repo/docs/plans"); + expect(entries).toContain("plan.md"); }); it("uses per-step agent and model overrides", async () => { @@ -3020,10 +3069,10 @@ describe("createPipelineSimulation", () => { it("resolves a file-backed var and interpolates it into task prompt", async () => { const sim = createPipelineSimulation({ files: { - "docs/plans/my-feature.md": "# My Feature\nBuild the thing." + "docs/context/my-feature.md": "# My Feature\nBuild the thing." }, plan: { - vars: { plan_doc: "{{file 'docs/plans/my-feature.md'}}" }, + vars: { plan_doc: "{{file 'docs/context/my-feature.md'}}" }, tasks: [ { id: "task-1", diff --git a/packages/pipeline/src/plan/discovery.ts b/packages/pipeline/src/plan/discovery.ts index 57f80b2d76..7a456c9f25 100644 --- a/packages/pipeline/src/plan/discovery.ts +++ b/packages/pipeline/src/plan/discovery.ts @@ -1,11 +1,12 @@ import path from "node:path"; import * as fsPromises from "node:fs/promises"; -import { parse as parseYaml } from "yaml"; -import { getYamlContent, parsePlan } from "./parser.js"; +import { discoverPlans } from "@poe-code/agent-harness-tools"; +import { parsePlan } from "./parser.js"; import type { PipelineFileStat, PipelineFileSystem } from "../types.js"; -import { isNotFound, isRecord } from "../utils.js"; +import { isNotFound } from "../utils.js"; type DiscoveryFs = Pick; +type DiscoverPlansFs = NonNullable[0]["fs"]>; type PlanCandidate = { path: string; @@ -28,21 +29,6 @@ function createDefaultFs(): DiscoveryFs { }; } -function isMarkdownFile(name: string): boolean { - return name.toLowerCase().endsWith(".md"); -} - -function isPipelinePlan(content: string): boolean { - let parsed: unknown; - try { - parsed = parseYaml(getYamlContent(content)); - } catch { - return false; - } - - return isRecord(parsed) && parsed.kind === "pipeline"; -} - function countCompletedTasks(planPath: string, content: string): PlanCandidate { const plan = parsePlan(content); const total = plan.tasks.length; @@ -76,44 +62,6 @@ async function ensurePlanExists(fs: DiscoveryFs, cwd: string, planPath: string): } } -async function scanPlansDir( - fs: DiscoveryFs, - plansDir: string, - displayPrefix: string -): Promise { - let entries: string[]; - try { - entries = await fs.readdir(plansDir); - } catch (error) { - if (isNotFound(error)) { - return []; - } - throw error; - } - - const candidates: PlanCandidate[] = []; - for (const entry of entries) { - if (!isMarkdownFile(entry)) { - continue; - } - - const absolutePath = path.join(plansDir, entry); - const stat = await fs.stat(absolutePath); - if (!stat.isFile()) { - continue; - } - - const displayPath = path.join(displayPrefix, entry); - const content = await fs.readFile(absolutePath, "utf8"); - if (!isPipelinePlan(content)) { - continue; - } - candidates.push(countCompletedTasks(displayPath, content)); - } - - return candidates; -} - async function listPlanCandidates( fs: DiscoveryFs, cwd: string, @@ -121,21 +69,22 @@ async function listPlanCandidates( planDirectory?: string ): Promise { const dir = planDirectory?.trim() || "docs/plans"; - const candidates = await scanCustomPlanDir(fs, dir, cwd, homeDir); + const discovered = await discoverPlans({ + cwd, + homeDir, + planDirectory: dir, + kinds: ["pipeline"], + fs: fs as unknown as DiscoverPlansFs + }); + const candidates = await Promise.all( + discovered.map(async (candidate) => + countCompletedTasks(candidate.displayPath, await fs.readFile(candidate.absolutePath, "utf8")) + ) + ); candidates.sort((left, right) => left.path.localeCompare(right.path)); return candidates; } -async function scanCustomPlanDir( - fs: DiscoveryFs, - planDirectory: string, - cwd: string, - homeDir: string -): Promise { - const absoluteDir = resolveAbsoluteDirectory(planDirectory, cwd, homeDir); - return scanPlansDir(fs, absoluteDir, planDirectory); -} - function resolveAbsoluteDirectory(dir: string, cwd: string, homeDir: string): string { if (dir.startsWith("~/")) { return path.join(homeDir, dir.slice(2)); diff --git a/packages/pipeline/src/run/pipeline.ts b/packages/pipeline/src/run/pipeline.ts index 4ea104734d..ab5b98cffa 100644 --- a/packages/pipeline/src/run/pipeline.ts +++ b/packages/pipeline/src/run/pipeline.ts @@ -1,7 +1,12 @@ import path from "node:path"; import * as fsPromises from "node:fs/promises"; import { loadResolvedSteps } from "../config/loader.js"; -import { lockWorkflow, makeRunLogFileName, resolveRunLogDir } from "@poe-code/agent-harness-tools"; +import { + archivePlan as archivePlanShared, + lockWorkflow, + makeRunLogFileName, + resolveRunLogDir +} from "@poe-code/agent-harness-tools"; import { resolveAbsolutePlanPath, resolvePlanPath } from "../plan/discovery.js"; import { parsePlan } from "../plan/parser.js"; import { writeTaskStatus } from "../plan/writer.js"; @@ -147,16 +152,28 @@ function resolveMode( return step.mode; } -async function archivePlan(fs: PipelineFileSystem, absolutePlanPath: string): Promise { - const dir = path.dirname(absolutePlanPath); - const archiveDir = path.join(dir, "archive"); - const archivePath = path.join(archiveDir, path.basename(absolutePlanPath)); - await fs.mkdir(archiveDir, { recursive: true }); - await fs.rename(absolutePlanPath, archivePath); +function planIdFromPath(absolutePlanPath: string): string { + const extension = path.extname(absolutePlanPath); + const stem = path.basename(absolutePlanPath, extension); + const separatorIndex = stem.indexOf("-"); + + if (separatorIndex <= 0) { + return stem; + } + + const prefix = stem.slice(0, separatorIndex); + for (const char of prefix) { + if (char < "0" || char > "9") { + return stem; + } + } + + return stem.slice(separatorIndex + 1); } export async function runPipeline(options: PipelineRunOptions): Promise { const fs = options.fs ?? createDefaultFs(); + const configuredPlanDirectory = options.planDirectory?.trim() || undefined; const runAgent = options.runAgent; if (!runAgent) { throw new Error("runPipeline requires a runAgent implementation."); @@ -391,7 +408,14 @@ export async function runPipeline(options: PipelineRunOptions): Promise 0) { - await archivePlan(fs, absolutePlanPath); + const id = planIdFromPath(absolutePlanPath); + await archivePlanShared({ + cwd: options.cwd, + homeDir: options.homeDir, + planDirectory: configuredPlanDirectory ?? "docs/plans", + id, + fs: fs as unknown as NonNullable[0]["fs"]> + }); if (resolvedTeardown) { const { success, cancelled } = await runPhase( resolvedTeardown, diff --git a/packages/pipeline/src/testing/simulation.ts b/packages/pipeline/src/testing/simulation.ts index feab5327e7..d2e8fe92a3 100644 --- a/packages/pipeline/src/testing/simulation.ts +++ b/packages/pipeline/src/testing/simulation.ts @@ -73,14 +73,15 @@ export type SimulationResult = { }; function createSimulationFs(options: SimulationOptions): { fs: SimulationFs; planPath: string } { - const planPath = "/repo/.poe-code/pipeline/plans/plan.yaml"; + const planPath = "/repo/docs/plans/plan.md"; + const planContent = stringify({ + $schema: pipelineDocumentSchemaId, + kind: "pipeline", + version: 1, + ...options.plan + }); const files: Record = { - [planPath]: stringify({ - $schema: pipelineDocumentSchemaId, - kind: "pipeline", - version: 1, - ...options.plan - }), + [planPath]: ["---", planContent.trimEnd(), "---", ""].join("\n"), ...Object.fromEntries( Object.entries(options.files ?? {}).map(([filePath, content]) => [ path.join("/repo", filePath), @@ -221,7 +222,7 @@ export function createPipelineSimulation(options: SimulationOptions): { agent: "codex", cwd: "/repo", homeDir: "/home/test", - plan: ".poe-code/pipeline/plans/plan.yaml", + plan: "docs/plans/plan.md", maxRuns: options.config?.maxRuns, logDir: options.config?.logDir, onPlanReloadError: options.onPlanReloadError, From 2570d9203d15ac5a670bb453b991cc4697b3d401 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 05:45:23 -0500 Subject: [PATCH 095/111] fix(ralph): use shared plan discovery --- docs/plans/zharness-plans-via-task-list.md | 6 +- .../zharness-plans-via-task-list.md.lock | 2 +- packages/ralph/src/discovery/discovery.ts | 162 ++++-------------- packages/ralph/src/frontmatter/frontmatter.ts | 3 +- packages/ralph/src/ralph.test.ts | 86 ++++++++-- packages/ralph/src/run/ralph.ts | 27 +-- src/cli/commands/experiment-ralph.test.ts | 17 +- src/cli/commands/ralph.ts | 2 +- 8 files changed, 132 insertions(+), 173 deletions(-) diff --git a/docs/plans/zharness-plans-via-task-list.md b/docs/plans/zharness-plans-via-task-list.md index 556dd61557..768ce50262 100644 --- a/docs/plans/zharness-plans-via-task-list.md +++ b/docs/plans/zharness-plans-via-task-list.md @@ -433,7 +433,7 @@ tasks: status: implement: done test: done - commit: open + commit: done - id: ralph-migrate title: Migrate ralph harness to shared plan API @@ -486,8 +486,8 @@ tasks: If any existing ralph test asserted on a specific state machine, confirm the default has the `archive` event (it does). status: - implement: open - test: open + implement: done + test: done commit: open - id: experiment-loop-migrate diff --git a/docs/plans/zharness-plans-via-task-list.md.lock b/docs/plans/zharness-plans-via-task-list.md.lock index 71ba59ab2b..4872b5a89c 100644 --- a/docs/plans/zharness-plans-via-task-list.md.lock +++ b/docs/plans/zharness-plans-via-task-list.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T10:36:19.739Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T10:41:46.439Z"} \ No newline at end of file diff --git a/packages/ralph/src/discovery/discovery.ts b/packages/ralph/src/discovery/discovery.ts index 8442914db4..93c91c4b8d 100644 --- a/packages/ralph/src/discovery/discovery.ts +++ b/packages/ralph/src/discovery/discovery.ts @@ -1,19 +1,19 @@ -import path from "node:path"; import * as fsPromises from "node:fs/promises"; import { - discoverWorkflowDocs, - resolveWorkflowPath + discoverPlans, + type DiscoverPlansOptions } from "@poe-code/agent-harness-tools"; -import type { RalphFileStat } from "../types.js"; +import type { RalphFileSystem } from "../types.js"; -type DiscoveryFs = { - readdir(path: string): Promise; - stat(path: string): Promise; -}; +type DiscoveryFs = NonNullable; function createDefaultFs(): DiscoveryFs { return { + readFile: fsPromises.readFile as RalphFileSystem["readFile"], + writeFile: (filePath: string, content: string) => + fsPromises.writeFile(filePath, content, "utf8"), readdir: fsPromises.readdir, + open: (filePath: string, flags: string) => fsPromises.open(filePath, flags), stat: async (filePath) => { const stat = await fsPromises.stat(filePath); return { @@ -21,120 +21,17 @@ function createDefaultFs(): DiscoveryFs { isDirectory: () => stat.isDirectory(), mtimeMs: stat.mtimeMs }; + }, + unlink: async (filePath: string) => { + await fsPromises.unlink(filePath); + }, + mkdir: async (filePath: string, options?: { recursive?: boolean }) => { + await fsPromises.mkdir(filePath, options); + }, + rename: async (oldPath: string, newPath: string) => { + await fsPromises.rename(oldPath, newPath); } - }; -} - -function isNotFound(error: unknown): boolean { - return ( - !!error && - typeof error === "object" && - "code" in error && - (error as { code?: unknown }).code === "ENOENT" - ); -} - -function isMarkdownFile(entry: string): boolean { - return entry.toLowerCase().endsWith(".md"); -} - -async function scanDir( - fs: DiscoveryFs, - absoluteDir: string, - displayDir: string -): Promise> { - let entries: string[]; - try { - entries = await fs.readdir(absoluteDir); - } catch (error) { - if (isNotFound(error)) { - return []; - } - throw error; - } - - const docs: Array<{ path: string; displayPath: string }> = []; - - for (const entry of entries) { - if (!isMarkdownFile(entry)) { - continue; - } - - const absolutePath = path.join(absoluteDir, entry); - const stat = await fs.stat(absolutePath); - if (!stat.isFile()) { - continue; - } - - const displayPath = path.join(displayDir, entry); - docs.push({ - path: displayPath, - displayPath - }); - } - - return docs; -} - -function toDisplayPath(options: { - absolutePath: string; - cwd: string; - homeDir: string; -}): string { - const localDir = path.join(options.cwd, ".poe-code", "ralph", "plans"); - const globalDir = path.join(options.homeDir, ".poe-code", "ralph", "plans"); - - if (options.absolutePath.startsWith(`${localDir}${path.sep}`)) { - return path.join( - ".poe-code/ralph/plans", - path.relative(localDir, options.absolutePath) - ); - } - - if (options.absolutePath.startsWith(`${globalDir}${path.sep}`)) { - return path.join( - "~/.poe-code/ralph/plans", - path.relative(globalDir, options.absolutePath) - ); - } - - return options.absolutePath; -} - -async function scanCustomDir( - fs: DiscoveryFs, - planDirectory: string, - cwd: string, - homeDir: string -): Promise> { - const absoluteDir = resolveWorkflowPath(planDirectory, cwd, homeDir); - return scanDir(fs, absoluteDir, planDirectory); -} - -async function scanDefaultDirs( - fs: DiscoveryFs, - cwd: string, - homeDir: string -): Promise> { - const docs = await discoverWorkflowDocs({ - cwd, - homeDir, - subDirectory: "ralph/plans", - fs - }); - - return docs.map((absolutePath) => { - const displayPath = toDisplayPath({ - absolutePath, - cwd, - homeDir - }); - - return { - path: displayPath, - displayPath - }; - }); + } as DiscoveryFs; } export async function discoverDocs(options: { @@ -144,17 +41,16 @@ export async function discoverDocs(options: { fs?: DiscoveryFs; }): Promise> { const fs = options.fs ?? createDefaultFs(); - - const customDir = options.planDirectory?.trim(); - const docs = customDir - ? await scanCustomDir(fs, customDir, options.cwd, options.homeDir) - : await scanDefaultDirs(fs, options.cwd, options.homeDir); - - return docs.sort((left, right) => { - const leftName = path.basename(left.displayPath).toLowerCase(); - const rightName = path.basename(right.displayPath).toLowerCase(); - return leftName === rightName - ? left.displayPath.localeCompare(right.displayPath) - : leftName.localeCompare(rightName); + const docs = await discoverPlans({ + cwd: options.cwd, + homeDir: options.homeDir, + planDirectory: options.planDirectory?.trim() || ".poe-code/ralph/plans", + kinds: ["ralph"], + fs }); + + return docs.map((doc) => ({ + path: doc.displayPath, + displayPath: doc.displayPath + })); } diff --git a/packages/ralph/src/frontmatter/frontmatter.ts b/packages/ralph/src/frontmatter/frontmatter.ts index fd08446eef..0d6d547527 100644 --- a/packages/ralph/src/frontmatter/frontmatter.ts +++ b/packages/ralph/src/frontmatter/frontmatter.ts @@ -123,7 +123,8 @@ export function parseFrontmatter(content: string): { } const yamlBlock = content.slice(FENCE.length + 1, closingIndex); - const body = content.slice(closingIndex + FENCE.length + 2); + const bodyStart = closingIndex + FENCE.length + 2; + const body = content.slice(content.startsWith("\n", bodyStart) ? bodyStart + 1 : bodyStart); const parsed = parse(yamlBlock); return { diff --git a/packages/ralph/src/ralph.test.ts b/packages/ralph/src/ralph.test.ts index 97c51a85cc..200eb145a7 100644 --- a/packages/ralph/src/ralph.test.ts +++ b/packages/ralph/src/ralph.test.ts @@ -24,7 +24,16 @@ function createFs(files: Record) { const rawFs = createFsFromVolume(volume).promises; return { + readFile: (filePath: string, encoding: BufferEncoding) => + rawFs.readFile(filePath, encoding) as Promise, + writeFile: async (filePath: string, content: string) => { + await rawFs.mkdir(path.dirname(filePath), { + recursive: true + }); + await rawFs.writeFile(filePath, content, { encoding: "utf8" }); + }, readdir: (filePath: string) => rawFs.readdir(filePath) as Promise, + open: (filePath: string, flags: string) => rawFs.open(filePath, flags), stat: async (filePath: string) => { const stat = await rawFs.stat(filePath); return { @@ -32,6 +41,18 @@ function createFs(files: Record) { isDirectory: () => stat.isDirectory(), mtimeMs: Number(stat.mtimeMs) }; + }, + unlink: async (filePath: string) => { + await rawFs.unlink(filePath); + }, + mkdir: async (filePath: string, options?: { recursive?: boolean }) => { + await rawFs.mkdir(filePath, options); + }, + rename: async (oldPath: string, newPath: string) => { + await rawFs.mkdir(path.dirname(newPath), { + recursive: true + }); + await rawFs.rename(oldPath, newPath); } }; } @@ -80,6 +101,20 @@ function createRunFs(files: Record) { }; } +function ralphPlanDocument(body = "# Plan"): string { + return ["---", "kind: ralph", "---", body].join("\n"); +} + +async function markdownEntries( + fs: Pick, "readdir">, + directoryPath: string +): Promise { + const entries = await fs.readdir(directoryPath); + return entries + .filter((entryName) => entryName.endsWith(".md")) + .sort((left, right) => left.localeCompare(right)); +} + describe("@poe-code/ralph public exports", () => { it("re-exports the Ralph document schema from the package entrypoint", async () => { const pkg = await import("./index.js"); @@ -131,12 +166,17 @@ describe("@poe-code/ralph public exports", () => { }); describe("discoverDocs", () => { - it("finds local and global markdown docs and sorts them by file name", async () => { + it("finds local Ralph markdown docs from the shared plan API", async () => { const fs = createFs({ - "/repo/.poe-code/ralph/plans/zeta.md": "# zeta", + "/repo/.poe-code/ralph/plans/zeta.md": ralphPlanDocument("# zeta"), "/repo/.poe-code/ralph/plans/notes.txt": "ignore", - "/repo/.poe-code/ralph/plans/alpha.md": "# alpha", - "/home/test/.poe-code/ralph/plans/beta.md": "# beta" + "/repo/.poe-code/ralph/plans/alpha.md": ralphPlanDocument("# alpha"), + "/repo/.poe-code/ralph/plans/pipeline.md": [ + "---", + "kind: pipeline", + "---", + "# pipeline" + ].join("\n") }); await expect( @@ -150,10 +190,6 @@ describe("discoverDocs", () => { path: ".poe-code/ralph/plans/alpha.md", displayPath: ".poe-code/ralph/plans/alpha.md" }, - { - path: "~/.poe-code/ralph/plans/beta.md", - displayPath: "~/.poe-code/ralph/plans/beta.md" - }, { path: ".poe-code/ralph/plans/zeta.md", displayPath: ".poe-code/ralph/plans/zeta.md" @@ -173,30 +209,31 @@ describe("discoverDocs", () => { ).resolves.toEqual([]); }); - it("prefers the local doc when local and global docs share the same file name", async () => { + it("uses the configured planDirectory as the shared API discovery root", async () => { const fs = createFs({ - "/repo/.poe-code/ralph/plans/shared.md": "# local", - "/home/test/.poe-code/ralph/plans/shared.md": "# global" + "/repo/.poe-code/ralph/plans/shared.md": ralphPlanDocument("# local"), + "/home/test/.poe-code/ralph/plans/shared.md": ralphPlanDocument("# global") }); await expect( discoverDocs({ cwd: "/repo", homeDir: "/home/test", + planDirectory: "~/.poe-code/ralph/plans", fs }) ).resolves.toEqual([ { - path: ".poe-code/ralph/plans/shared.md", - displayPath: ".poe-code/ralph/plans/shared.md" + path: "~/.poe-code/ralph/plans/shared.md", + displayPath: "~/.poe-code/ralph/plans/shared.md" } ]); }); it("scans only the custom planDirectory when provided", async () => { const fs = createFs({ - "/repo/custom-plans/alpha.md": "# alpha", - "/repo/.poe-code/ralph/plans/default.md": "# default" + "/repo/custom-plans/alpha.md": ralphPlanDocument("# alpha"), + "/repo/.poe-code/ralph/plans/default.md": ralphPlanDocument("# default") }); const result = await discoverDocs({ @@ -213,7 +250,7 @@ describe("discoverDocs", () => { it("resolves absolute planDirectory paths", async () => { const fs = createFs({ - "/abs/plans/doc.md": "# doc" + "/abs/plans/doc.md": ralphPlanDocument("# doc") }); const result = await discoverDocs({ @@ -228,7 +265,7 @@ describe("discoverDocs", () => { it("resolves tilde planDirectory paths", async () => { const fs = createFs({ - "/home/test/my-plans/doc.md": "# doc" + "/home/test/my-plans/doc.md": ralphPlanDocument("# doc") }); const result = await discoverDocs({ @@ -731,11 +768,24 @@ describe("createRalphSimulation", () => { it("archives plan on max_iterations completion", async () => { const sim = createRalphSimulation({ docContent: "# Archive me", + docPath: ".poe-code/ralph/plans/02-plan.md", maxIterations: 2, + files: { + ".poe-code/ralph/plans/01-alpha.md": ralphPlanDocument("# Alpha"), + ".poe-code/ralph/plans/03-gamma.md": ralphPlanDocument("# Gamma") + }, turns: [successTurn(), successTurn()] }); - const { readFile } = await sim.run(); + const { fs, readFile } = await sim.run(); + + await expect(markdownEntries(fs, "/repo/.poe-code/ralph/plans")).resolves.toEqual([ + "01-alpha.md", + "02-gamma.md" + ]); + await expect(markdownEntries(fs, "/repo/.poe-code/ralph/plans/archive")).resolves.toEqual([ + "plan.md" + ]); const archived = await readFile(".poe-code/ralph/plans/archive/plan.md"); const { data, body } = parseFrontmatter(archived); diff --git a/packages/ralph/src/run/ralph.ts b/packages/ralph/src/run/ralph.ts index 4e4dd0ffce..7d35e8c44f 100644 --- a/packages/ralph/src/run/ralph.ts +++ b/packages/ralph/src/run/ralph.ts @@ -1,6 +1,7 @@ import path from "node:path"; import * as fsPromises from "node:fs/promises"; import { + archivePlan as archivePlanShared, makeRunLogFileName, resolveRunLogDir, resolveWorkflowPath, @@ -36,6 +37,8 @@ export async function runRalph(options: RalphRunOptions): Promise[0]["fs"]> + }); archived = true; stopReason = "max_iterations"; return; @@ -199,7 +208,13 @@ export async function runRalph(options: RalphRunOptions): Promise 0) { await updateFrontmatter(fs, absoluteDocPath, "completed", iterationsCompleted); - await archivePlan(fs, absoluteDocPath); + await archivePlanShared({ + cwd: options.cwd, + homeDir: options.homeDir, + planDirectory, + id: planId, + fs: fs as unknown as NonNullable[0]["fs"]> + }); } else if (stopReason === "cancelled" && !archived) { await updateFrontmatter(fs, absoluteDocPath, "open", iterationsCompleted); } @@ -448,11 +463,3 @@ async function updateFrontmatter( ); await fs.writeFile(absoluteDocPath, content); } - -async function archivePlan(fs: RalphFileSystem, absoluteDocPath: string): Promise { - const dir = path.dirname(absoluteDocPath); - const archiveDir = path.join(dir, "archive"); - const archivePath = path.join(archiveDir, path.basename(absoluteDocPath)); - await fs.mkdir(archiveDir, { recursive: true }); - await fs.rename(absoluteDocPath, archivePath); -} diff --git a/src/cli/commands/experiment-ralph.test.ts b/src/cli/commands/experiment-ralph.test.ts index 8fe5f3916c..f75bbf4d15 100644 --- a/src/cli/commands/experiment-ralph.test.ts +++ b/src/cli/commands/experiment-ralph.test.ts @@ -69,6 +69,10 @@ import { acp, createDashboard, withOutputFormat } from "@poe-code/design-system" const cwd = "/repo"; const homeDir = "/home/test"; +function ralphPlanDocument(body = "# Plan", frontmatter: string[] = []): string { + return ["---", "kind: ralph", ...frontmatter, "---", body].join("\n"); +} + function createMemFs(files: Record = {}): FileSystem { const volume = Volume.fromJSON(files, "/"); volume.mkdirSync(cwd, { recursive: true }); @@ -1978,8 +1982,8 @@ describe("ralph run command", () => { const container = createCliContainer({ fs: createMemFs({ - "/repo/docs/plans/plan-b.md": "# B", - "/repo/docs/plans/plan-a.md": "# A" + "/repo/docs/plans/plan-b.md": ralphPlanDocument("# B"), + "/repo/docs/plans/plan-a.md": ralphPlanDocument("# A") }), prompts: vi.fn().mockResolvedValue({}), env: { cwd, homeDir }, @@ -2027,6 +2031,7 @@ describe("ralph run command", () => { fs: createMemFs({ "/repo/docs/plans/plan-a.md": [ "---", + "kind: ralph", "agent: codex", "iterations: 3", "status:", @@ -2035,7 +2040,7 @@ describe("ralph run command", () => { "---", "# A" ].join("\n"), - "/repo/docs/plans/plan-b.md": "# B" + "/repo/docs/plans/plan-b.md": ralphPlanDocument("# B") }), prompts: vi.fn().mockResolvedValue({}), env: { cwd, homeDir }, @@ -2153,8 +2158,8 @@ describe("ralph run command", () => { it("uses defaults with --yes when frontmatter does not provide values", async () => { const container = createCliContainer({ fs: createMemFs({ - "/repo/docs/plans/plan-b.md": "# B", - "/repo/docs/plans/plan-a.md": "# A" + "/repo/docs/plans/plan-b.md": ralphPlanDocument("# B"), + "/repo/docs/plans/plan-a.md": ralphPlanDocument("# A") }), prompts: vi.fn().mockResolvedValue({}), env: { cwd, homeDir }, @@ -2830,7 +2835,7 @@ describe("ralph init command", () => { it("uses CLI prompts when agent and iterations are omitted", async () => { const fs = createMemFs({ - "/repo/docs/plans/plan-a.md": "# A" + "/repo/docs/plans/plan-a.md": ralphPlanDocument("# A") }); selectMock.mockResolvedValueOnce("docs/plans/plan-a.md").mockResolvedValueOnce("codex"); promptTextMock.mockResolvedValue("4"); diff --git a/src/cli/commands/ralph.ts b/src/cli/commands/ralph.ts index ec065b1caf..c9a329d717 100644 --- a/src/cli/commands/ralph.ts +++ b/src/cli/commands/ralph.ts @@ -360,7 +360,7 @@ async function resolveDocPath(options: { cwd: options.container.env.cwd, homeDir: options.container.env.homeDir, planDirectory: options.planDirectory, - fs: options.container.fs + fs: options.container.fs as unknown as NonNullable[0]["fs"]> }); if (docs.length === 0) { throw new ValidationError( From 3fdcd439e16b7d09b56c58abe510dca66aef8d7a Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 05:53:51 -0500 Subject: [PATCH 096/111] refactor: use shared plan discovery for experiments --- docs/plans/zharness-plans-via-task-list.md | 8 +- .../zharness-plans-via-task-list.md.lock | 2 +- packages/agent-harness-tools/src/plans.ts | 8 +- .../src/agent-kit-integration.test.ts | 20 +-- .../src/discovery/discovery.ts | 164 ++---------------- src/cli/commands/experiment-ralph.test.ts | 19 +- 6 files changed, 46 insertions(+), 175 deletions(-) diff --git a/docs/plans/zharness-plans-via-task-list.md b/docs/plans/zharness-plans-via-task-list.md index 768ce50262..63fee49200 100644 --- a/docs/plans/zharness-plans-via-task-list.md +++ b/docs/plans/zharness-plans-via-task-list.md @@ -488,7 +488,7 @@ tasks: status: implement: done test: done - commit: open + commit: done - id: experiment-loop-migrate title: Migrate experiment-loop harness to shared plan API @@ -523,9 +523,9 @@ tasks: - No CLI surface changes. - No new dependencies. status: - implement: open - test: open - commit: open + implement: done + test: done + commit: done - id: superintendent-migrate title: Migrate superintendent harness to shared plan discovery diff --git a/docs/plans/zharness-plans-via-task-list.md.lock b/docs/plans/zharness-plans-via-task-list.md.lock index 4872b5a89c..b7c6b5926d 100644 --- a/docs/plans/zharness-plans-via-task-list.md.lock +++ b/docs/plans/zharness-plans-via-task-list.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T10:41:46.439Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T10:50:37.055Z"} \ No newline at end of file diff --git a/packages/agent-harness-tools/src/plans.ts b/packages/agent-harness-tools/src/plans.ts index 2c04a6b5f7..babf69913a 100644 --- a/packages/agent-harness-tools/src/plans.ts +++ b/packages/agent-harness-tools/src/plans.ts @@ -3,6 +3,8 @@ import path from "node:path"; import { openTaskList, type Task, type TaskList, type TaskListFs } from "@poe-code/task-list"; import { resolveWorkflowPath } from "./paths.js"; +export type DiscoverPlansFs = Pick; + export interface PlanRef { id: string; absolutePath: string; @@ -16,7 +18,7 @@ export interface DiscoverPlansOptions { homeDir: string; planDirectory: string; kinds?: readonly string[]; - fs?: TaskListFs; + fs?: DiscoverPlansFs; } export interface ArchivePlanOptions { @@ -111,7 +113,7 @@ function idFromActivePlanFilename(fileName: string): string | undefined { } async function activePlanFilePaths( - fs: TaskListFs, + fs: DiscoverPlansFs, planDirectory: string ): Promise | undefined> { let entries: string[]; @@ -177,7 +179,7 @@ export async function discoverPlans(options: DiscoverPlansOptions): Promise undefined), @@ -42,22 +46,18 @@ function createExec(): ExecFn { } describe("experiment-loop agent-kit discovery", () => { - it("discovers default experiment docs from project and home directories", async () => { + it("discovers default experiment docs from the project directory", async () => { const docs = await discoverExperimentDocs({ cwd, homeDir, fs: createFs({ - "/repo/.poe-code/experiments/shared.md": "# project", - "/home/test/.poe-code/experiments/global.md": "# global", - "/home/test/.poe-code/experiments/shared.md": "# home" + "/repo/.poe-code/experiments/shared.md": createExperimentPlanDoc("# project"), + "/home/test/.poe-code/experiments/global.md": createExperimentPlanDoc("# global"), + "/home/test/.poe-code/experiments/shared.md": createExperimentPlanDoc("# home") }) }); expect(docs).toEqual([ - { - path: "~/.poe-code/experiments/global.md", - displayPath: "~/.poe-code/experiments/global.md" - }, { path: ".poe-code/experiments/shared.md", displayPath: ".poe-code/experiments/shared.md" @@ -71,8 +71,8 @@ describe("experiment-loop agent-kit discovery", () => { homeDir, planDirectory: "docs/experiments", fs: createFs({ - "/repo/docs/experiments/plan-b.md": "# B", - "/repo/docs/experiments/plan-a.md": "# A" + "/repo/docs/experiments/plan-b.md": createExperimentPlanDoc("# B"), + "/repo/docs/experiments/plan-a.md": createExperimentPlanDoc("# A") }) }); diff --git a/packages/experiment-loop/src/discovery/discovery.ts b/packages/experiment-loop/src/discovery/discovery.ts index ddb1fc44ee..ccffaa6442 100644 --- a/packages/experiment-loop/src/discovery/discovery.ts +++ b/packages/experiment-loop/src/discovery/discovery.ts @@ -1,18 +1,9 @@ -import path from "node:path"; -import * as fsPromises from "node:fs/promises"; import { - discoverWorkflowDocs, - resolveWorkflowPath + discoverPlans, + type DiscoverPlansOptions } from "@poe-code/agent-harness-tools"; -type DiscoveryFileStat = { - isFile(): boolean; -}; - -export type ExperimentDiscoveryFs = { - readdir(path: string): Promise; - stat(path: string): Promise; -}; +export type ExperimentDiscoveryFs = NonNullable; export interface DiscoverExperimentDocsOptions { cwd: string; @@ -21,146 +12,19 @@ export interface DiscoverExperimentDocsOptions { fs?: ExperimentDiscoveryFs; } -function createDefaultFs(): ExperimentDiscoveryFs { - return { - readdir: fsPromises.readdir, - stat: async (filePath) => { - const stat = await fsPromises.stat(filePath); - return { - isFile: () => stat.isFile() - }; - } - }; -} - -function isNotFound(error: unknown): boolean { - return ( - !!error && - typeof error === "object" && - "code" in error && - (error as { code?: unknown }).code === "ENOENT" - ); -} - -function isMarkdownFile(entry: string): boolean { - return entry.toLowerCase().endsWith(".md"); -} - -async function scanDir( - fs: ExperimentDiscoveryFs, - absoluteDir: string, - displayDir: string -): Promise> { - let entries: string[]; - try { - entries = await fs.readdir(absoluteDir); - } catch (error) { - if (isNotFound(error)) { - return []; - } - - throw error; - } - - const docs: Array<{ path: string; displayPath: string }> = []; - - for (const entry of entries) { - if (!isMarkdownFile(entry)) { - continue; - } - - const absolutePath = path.join(absoluteDir, entry); - const stat = await fs.stat(absolutePath); - if (!stat.isFile()) { - continue; - } - - const displayPath = path.join(displayDir, entry); - docs.push({ - path: displayPath, - displayPath - }); - } - - return docs; -} - -function toDisplayPath(options: { - absolutePath: string; - cwd: string; - homeDir: string; -}): string { - const localDir = path.join(options.cwd, ".poe-code", "experiments"); - const globalDir = path.join(options.homeDir, ".poe-code", "experiments"); - - if (options.absolutePath.startsWith(`${localDir}${path.sep}`)) { - return path.join( - ".poe-code/experiments", - path.relative(localDir, options.absolutePath) - ); - } - - if (options.absolutePath.startsWith(`${globalDir}${path.sep}`)) { - return path.join( - "~/.poe-code/experiments", - path.relative(globalDir, options.absolutePath) - ); - } - - return options.absolutePath; -} - -async function scanCustomDir( - fs: ExperimentDiscoveryFs, - planDirectory: string, - cwd: string, - homeDir: string -): Promise> { - const absoluteDir = resolveWorkflowPath(planDirectory, cwd, homeDir); - return scanDir(fs, absoluteDir, planDirectory); -} - -async function scanDefaultDirs( - fs: ExperimentDiscoveryFs, - cwd: string, - homeDir: string -): Promise> { - const docs = await discoverWorkflowDocs({ - cwd, - homeDir, - subDirectory: "experiments", - fs - }); - - return docs.map((absolutePath) => { - const displayPath = toDisplayPath({ - absolutePath, - cwd, - homeDir - }); - - return { - path: displayPath, - displayPath - }; - }); -} - export async function discoverExperimentDocs( options: DiscoverExperimentDocsOptions ): Promise> { - const fs = options.fs ?? createDefaultFs(); - const customDir = options.planDirectory?.trim(); - const docs = customDir - ? await scanCustomDir(fs, customDir, options.cwd, options.homeDir) - : await scanDefaultDirs(fs, options.cwd, options.homeDir); - - return docs.sort((left, right) => { - const leftName = path.basename(left.displayPath).toLowerCase(); - const rightName = path.basename(right.displayPath).toLowerCase(); - - return leftName === rightName - ? left.displayPath.localeCompare(right.displayPath) - : leftName.localeCompare(rightName); + const docs = await discoverPlans({ + cwd: options.cwd, + homeDir: options.homeDir, + planDirectory: options.planDirectory?.trim() || ".poe-code/experiments", + kinds: ["experiment"], + fs: options.fs }); + + return docs.map((doc) => ({ + path: doc.displayPath, + displayPath: doc.displayPath + })); } diff --git a/src/cli/commands/experiment-ralph.test.ts b/src/cli/commands/experiment-ralph.test.ts index f75bbf4d15..7ac52a38f1 100644 --- a/src/cli/commands/experiment-ralph.test.ts +++ b/src/cli/commands/experiment-ralph.test.ts @@ -73,6 +73,10 @@ function ralphPlanDocument(body = "# Plan", frontmatter: string[] = []): string return ["---", "kind: ralph", ...frontmatter, "---", body].join("\n"); } +function experimentPlanDocument(body = "# Plan", frontmatter: string[] = []): string { + return ["---", "kind: experiment", ...frontmatter, "---", body].join("\n"); +} + function createMemFs(files: Record = {}): FileSystem { const volume = Volume.fromJSON(files, "/"); volume.mkdirSync(cwd, { recursive: true }); @@ -314,8 +318,8 @@ describe("experiment run command", () => { it("discovers the first doc and default agent with --yes", async () => { const container = createCliContainer({ fs: createMemFs({ - "/repo/docs/plans/plan-b.md": "# B", - "/repo/docs/plans/plan-a.md": "# A" + "/repo/docs/plans/plan-b.md": experimentPlanDocument("# B"), + "/repo/docs/plans/plan-a.md": experimentPlanDocument("# A") }), prompts: vi.fn().mockResolvedValue({}), env: { cwd, homeDir }, @@ -411,7 +415,7 @@ describe("experiment run command", () => { "/repo/.poe-code/config.json": JSON.stringify({ plan: { plan_directory: "~/docs/plans" } }), - "/home/test/docs/plans/plan-a.md": "# A" + "/home/test/docs/plans/plan-a.md": experimentPlanDocument("# A") }), prompts: vi.fn().mockResolvedValue({}), env: { cwd, homeDir }, @@ -436,8 +440,8 @@ describe("experiment run command", () => { const container = createCliContainer({ fs: createMemFs({ - "/repo/docs/plans/plan-b.md": "# B", - "/repo/docs/plans/plan-a.md": "# A" + "/repo/docs/plans/plan-b.md": experimentPlanDocument("# B"), + "/repo/docs/plans/plan-a.md": experimentPlanDocument("# A") }), prompts: vi.fn().mockResolvedValue({}), env: { cwd, homeDir }, @@ -1288,8 +1292,8 @@ describe("experiment journal command", () => { it("discovers the first doc with --yes", async () => { const container = createCliContainer({ fs: createMemFs({ - "/repo/docs/plans/plan-b.md": "# B", - "/repo/docs/plans/plan-a.md": "# A" + "/repo/docs/plans/plan-b.md": experimentPlanDocument("# B"), + "/repo/docs/plans/plan-a.md": experimentPlanDocument("# A") }), prompts: vi.fn().mockResolvedValue({}), env: { cwd, homeDir }, @@ -1452,6 +1456,7 @@ describe("experiment validate command", () => { fs: createMemFs({ "/repo/docs/plans/plan-a.md": [ "---", + "kind: experiment", "agent: claude-code", "metric:", " name: tests", From 822342663ae3c003afa45a04f9465d7b97a3faf6 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 05:57:53 -0500 Subject: [PATCH 097/111] refactor(superintendent): reuse shared plan discovery --- docs/plans/zharness-plans-via-task-list.md | 6 +- .../zharness-plans-via-task-list.md.lock | 2 +- packages/superintendent/src/commands/run.ts | 94 ++----------------- 3 files changed, 12 insertions(+), 90 deletions(-) diff --git a/docs/plans/zharness-plans-via-task-list.md b/docs/plans/zharness-plans-via-task-list.md index 63fee49200..6bd3443163 100644 --- a/docs/plans/zharness-plans-via-task-list.md +++ b/docs/plans/zharness-plans-via-task-list.md @@ -572,9 +572,9 @@ tasks: - No CLI flag changes. - No prompt UX regressions. status: - implement: open - test: open - commit: open + implement: done + test: done + commit: done - id: rename-plan-files title: Rename existing plan files with NN- prefixes diff --git a/docs/plans/zharness-plans-via-task-list.md.lock b/docs/plans/zharness-plans-via-task-list.md.lock index b7c6b5926d..eb70ef0392 100644 --- a/docs/plans/zharness-plans-via-task-list.md.lock +++ b/docs/plans/zharness-plans-via-task-list.md.lock @@ -1 +1 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T10:50:37.055Z"} \ No newline at end of file +{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T10:57:03.929Z"} \ No newline at end of file diff --git a/packages/superintendent/src/commands/run.ts b/packages/superintendent/src/commands/run.ts index 3e22bfedd2..d11e8236ca 100644 --- a/packages/superintendent/src/commands/run.ts +++ b/packages/superintendent/src/commands/run.ts @@ -2,6 +2,7 @@ import path from "node:path"; import * as fsPromises from "node:fs/promises"; import { spawn as nodeSpawn, spawnSync as nodeSpawnSync } from "node:child_process"; import { + discoverPlans, resolveLoopAgent, resolveRunLogDir, resolveWorkflowPath, @@ -848,10 +849,11 @@ async function resolveDocPath(options: { options.env, options.fs )); - const docs = await discoverSuperintendentDocs({ + const docs = await discoverPlans({ cwd: options.cwd, homeDir: options.homeDir, planDirectory, + kinds: ["superintendent"], fs: options.fs }); @@ -860,16 +862,16 @@ async function resolveDocPath(options: { } if (options.assumeYes || !options.interactive) { - return docs[0]!; + return docs[0]!.absolutePath; } const selected = await options.selectPrompt({ message: "Select superintendent document", - options: docs.map((docPath) => ({ - label: displayPath(docPath, options.cwd, options.homeDir), - value: docPath + options: docs.map((doc) => ({ + label: doc.displayPath, + value: doc.absolutePath })), - initialValue: docs[0] + initialValue: docs[0]!.absolutePath }); if (isCancel(selected)) { @@ -880,66 +882,6 @@ async function resolveDocPath(options: { return selected; } -async function discoverSuperintendentDocs(options: { - cwd: string; - homeDir: string; - planDirectory: string; - fs: SuperintendentFileSystem; -}): Promise { - const docs = await listPlanDirectoryDocs( - options.fs, - options.planDirectory, - options.cwd, - options.homeDir - ); - - const matches: string[] = []; - - for (const docPath of docs) { - try { - const content = await options.fs.readFile(docPath, "utf8"); - const document = parseSuperintendentDoc(docPath, content); - if (document.frontmatter.kind === "superintendent") { - matches.push(docPath); - } - } catch { - // Ignore invalid docs during discovery. - } - } - - return matches; -} - -async function listPlanDirectoryDocs( - fs: SuperintendentFileSystem, - planDirectory: string, - cwd: string, - homeDir: string -): Promise { - const absoluteDir = resolveAbsolutePlanDirectory(planDirectory, cwd, homeDir); - let entries: string[]; - try { - entries = await fs.readdir(absoluteDir); - } catch (error) { - if (isMissingDirectory(error)) { - return []; - } - throw error; - } - - return entries - .filter((entry) => entry.toLowerCase().endsWith(".md")) - .map((entry) => path.join(absoluteDir, entry)) - .sort((left, right) => left.localeCompare(right)); -} - -function resolveAbsolutePlanDirectory(dir: string, cwd: string, homeDir: string): string { - if (dir.startsWith("~/")) { - return path.join(homeDir, dir.slice(2)); - } - return path.isAbsolute(dir) ? dir : path.resolve(cwd, dir); -} - function normalizeAgentSelection(value?: string | null): string | undefined { if (typeof value !== "string") { return undefined; @@ -949,14 +891,6 @@ function normalizeAgentSelection(value?: string | null): string | undefined { return trimmed.length > 0 ? trimmed : undefined; } -function isMissingDirectory(error: unknown): boolean { - if (!error || typeof error !== "object" || !("code" in error)) { - return false; - } - const code = (error as { code?: unknown }).code; - return code === "ENOENT" || code === "ENOTDIR"; -} - function createAgentRunner(options: { session: RunSession | undefined; executeAgent: RunCommandOptions["executeAgent"]; @@ -1327,18 +1261,6 @@ function stripStopReason(result: SuperintendentRunResult): LoopState { }; } -function displayPath(filePath: string, cwd: string, homeDir: string): string { - if (filePath.startsWith(`${cwd}${path.sep}`)) { - return path.relative(cwd, filePath); - } - - if (filePath.startsWith(`${homeDir}${path.sep}`)) { - return `~/${path.relative(homeDir, filePath)}`; - } - - return filePath; -} - function createDefaultFs(): SuperintendentFileSystem { const fs = { readFile: fsPromises.readFile as SuperintendentFileSystem["readFile"], From 11b9d0c9d8d2868653edaa983af14edeff11153b Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 05:59:13 -0500 Subject: [PATCH 098/111] chore: prefix active harness plans --- .poe-code/experiments/{dashboard-e2e.md => 01-dashboard-e2e.md} | 0 .poe-code/experiments/{speed-up-tests.md => 02-speed-up-tests.md} | 0 .../experiments/{tui-dashboard-e2e.md => 03-tui-dashboard-e2e.md} | 0 .poe-code/experiments/{tui-e2e-fresh.md => 04-tui-e2e-fresh.md} | 0 .../experiments/{tui-e2e-live-test.md => 05-tui-e2e-live-test.md} | 0 .poe-code/experiments/{tui-e2e-verify.md => 06-tui-e2e-verify.md} | 0 .poe-code/experiments/{tui-verify.md => 07-tui-verify.md} | 0 docs/plans/{agent-human-in-loop.md => 01-agent-human-in-loop.md} | 0 ...r-poe-integration.md => 02-ai-sdk-provider-poe-integration.md} | 0 ...nsolidate-planning-docs.md => 03-consolidate-planning-docs.md} | 0 ...roduction-readiness.md => 04-http-mcp-production-readiness.md} | 0 ...p-approval-windows.md => 05-human-in-loop-approval-windows.md} | 0 docs/plans/{js-subset-sandbox.md => 06-js-subset-sandbox.md} | 0 docs/plans/{mcp-typed-outputs.md => 07-mcp-typed-outputs.md} | 0 docs/plans/{memory.md => 08-memory.md} | 0 ...gent-integration.md => 09-pi-mono-coding-agent-integration.md} | 0 ...t-tier1-improvements.md => 10-poe-agent-tier1-improvements.md} | 0 ...hema-generation.md => 11-poe-code-config-schema-generation.md} | 0 .../plans/{provider-abstraction.md => 12-provider-abstraction.md} | 0 docs/plans/{spawn-hooks.md => 13-spawn-hooks.md} | 0 ...spawn-independent-skills.md => 14-spawn-independent-skills.md} | 0 docs/plans/{spawn-sdk-resume.md => 15-spawn-sdk-resume.md} | 0 ...endent-agentic-tools.md => 16-superintendent-agentic-tools.md} | 0 ...ntendent-plan-extends.md => 17-superintendent-plan-extends.md} | 0 ...ntendent-planner-role.md => 18-superintendent-planner-role.md} | 0 ...-brittleness-constants.md => 19-test-brittleness-constants.md} | 0 .../{toolcraft-release-notes.md => 20-toolcraft-release-notes.md} | 0 .../{toolcraft-yaml-output.md => 21-toolcraft-yaml-output.md} | 0 ...-plans-via-task-list.md => 22-zharness-plans-via-task-list.md} | 0 29 files changed, 0 insertions(+), 0 deletions(-) rename .poe-code/experiments/{dashboard-e2e.md => 01-dashboard-e2e.md} (100%) rename .poe-code/experiments/{speed-up-tests.md => 02-speed-up-tests.md} (100%) rename .poe-code/experiments/{tui-dashboard-e2e.md => 03-tui-dashboard-e2e.md} (100%) rename .poe-code/experiments/{tui-e2e-fresh.md => 04-tui-e2e-fresh.md} (100%) rename .poe-code/experiments/{tui-e2e-live-test.md => 05-tui-e2e-live-test.md} (100%) rename .poe-code/experiments/{tui-e2e-verify.md => 06-tui-e2e-verify.md} (100%) rename .poe-code/experiments/{tui-verify.md => 07-tui-verify.md} (100%) rename docs/plans/{agent-human-in-loop.md => 01-agent-human-in-loop.md} (100%) rename docs/plans/{ai-sdk-provider-poe-integration.md => 02-ai-sdk-provider-poe-integration.md} (100%) rename docs/plans/{consolidate-planning-docs.md => 03-consolidate-planning-docs.md} (100%) rename docs/plans/{http-mcp-production-readiness.md => 04-http-mcp-production-readiness.md} (100%) rename docs/plans/{human-in-loop-approval-windows.md => 05-human-in-loop-approval-windows.md} (100%) rename docs/plans/{js-subset-sandbox.md => 06-js-subset-sandbox.md} (100%) rename docs/plans/{mcp-typed-outputs.md => 07-mcp-typed-outputs.md} (100%) rename docs/plans/{memory.md => 08-memory.md} (100%) rename docs/plans/{pi-mono-coding-agent-integration.md => 09-pi-mono-coding-agent-integration.md} (100%) rename docs/plans/{poe-agent-tier1-improvements.md => 10-poe-agent-tier1-improvements.md} (100%) rename docs/plans/{poe-code-config-schema-generation.md => 11-poe-code-config-schema-generation.md} (100%) rename docs/plans/{provider-abstraction.md => 12-provider-abstraction.md} (100%) rename docs/plans/{spawn-hooks.md => 13-spawn-hooks.md} (100%) rename docs/plans/{spawn-independent-skills.md => 14-spawn-independent-skills.md} (100%) rename docs/plans/{spawn-sdk-resume.md => 15-spawn-sdk-resume.md} (100%) rename docs/plans/{superintendent-agentic-tools.md => 16-superintendent-agentic-tools.md} (100%) rename docs/plans/{superintendent-plan-extends.md => 17-superintendent-plan-extends.md} (100%) rename docs/plans/{superintendent-planner-role.md => 18-superintendent-planner-role.md} (100%) rename docs/plans/{test-brittleness-constants.md => 19-test-brittleness-constants.md} (100%) rename docs/plans/{toolcraft-release-notes.md => 20-toolcraft-release-notes.md} (100%) rename docs/plans/{toolcraft-yaml-output.md => 21-toolcraft-yaml-output.md} (100%) rename docs/plans/{zharness-plans-via-task-list.md => 22-zharness-plans-via-task-list.md} (100%) diff --git a/.poe-code/experiments/dashboard-e2e.md b/.poe-code/experiments/01-dashboard-e2e.md similarity index 100% rename from .poe-code/experiments/dashboard-e2e.md rename to .poe-code/experiments/01-dashboard-e2e.md diff --git a/.poe-code/experiments/speed-up-tests.md b/.poe-code/experiments/02-speed-up-tests.md similarity index 100% rename from .poe-code/experiments/speed-up-tests.md rename to .poe-code/experiments/02-speed-up-tests.md diff --git a/.poe-code/experiments/tui-dashboard-e2e.md b/.poe-code/experiments/03-tui-dashboard-e2e.md similarity index 100% rename from .poe-code/experiments/tui-dashboard-e2e.md rename to .poe-code/experiments/03-tui-dashboard-e2e.md diff --git a/.poe-code/experiments/tui-e2e-fresh.md b/.poe-code/experiments/04-tui-e2e-fresh.md similarity index 100% rename from .poe-code/experiments/tui-e2e-fresh.md rename to .poe-code/experiments/04-tui-e2e-fresh.md diff --git a/.poe-code/experiments/tui-e2e-live-test.md b/.poe-code/experiments/05-tui-e2e-live-test.md similarity index 100% rename from .poe-code/experiments/tui-e2e-live-test.md rename to .poe-code/experiments/05-tui-e2e-live-test.md diff --git a/.poe-code/experiments/tui-e2e-verify.md b/.poe-code/experiments/06-tui-e2e-verify.md similarity index 100% rename from .poe-code/experiments/tui-e2e-verify.md rename to .poe-code/experiments/06-tui-e2e-verify.md diff --git a/.poe-code/experiments/tui-verify.md b/.poe-code/experiments/07-tui-verify.md similarity index 100% rename from .poe-code/experiments/tui-verify.md rename to .poe-code/experiments/07-tui-verify.md diff --git a/docs/plans/agent-human-in-loop.md b/docs/plans/01-agent-human-in-loop.md similarity index 100% rename from docs/plans/agent-human-in-loop.md rename to docs/plans/01-agent-human-in-loop.md diff --git a/docs/plans/ai-sdk-provider-poe-integration.md b/docs/plans/02-ai-sdk-provider-poe-integration.md similarity index 100% rename from docs/plans/ai-sdk-provider-poe-integration.md rename to docs/plans/02-ai-sdk-provider-poe-integration.md diff --git a/docs/plans/consolidate-planning-docs.md b/docs/plans/03-consolidate-planning-docs.md similarity index 100% rename from docs/plans/consolidate-planning-docs.md rename to docs/plans/03-consolidate-planning-docs.md diff --git a/docs/plans/http-mcp-production-readiness.md b/docs/plans/04-http-mcp-production-readiness.md similarity index 100% rename from docs/plans/http-mcp-production-readiness.md rename to docs/plans/04-http-mcp-production-readiness.md diff --git a/docs/plans/human-in-loop-approval-windows.md b/docs/plans/05-human-in-loop-approval-windows.md similarity index 100% rename from docs/plans/human-in-loop-approval-windows.md rename to docs/plans/05-human-in-loop-approval-windows.md diff --git a/docs/plans/js-subset-sandbox.md b/docs/plans/06-js-subset-sandbox.md similarity index 100% rename from docs/plans/js-subset-sandbox.md rename to docs/plans/06-js-subset-sandbox.md diff --git a/docs/plans/mcp-typed-outputs.md b/docs/plans/07-mcp-typed-outputs.md similarity index 100% rename from docs/plans/mcp-typed-outputs.md rename to docs/plans/07-mcp-typed-outputs.md diff --git a/docs/plans/memory.md b/docs/plans/08-memory.md similarity index 100% rename from docs/plans/memory.md rename to docs/plans/08-memory.md diff --git a/docs/plans/pi-mono-coding-agent-integration.md b/docs/plans/09-pi-mono-coding-agent-integration.md similarity index 100% rename from docs/plans/pi-mono-coding-agent-integration.md rename to docs/plans/09-pi-mono-coding-agent-integration.md diff --git a/docs/plans/poe-agent-tier1-improvements.md b/docs/plans/10-poe-agent-tier1-improvements.md similarity index 100% rename from docs/plans/poe-agent-tier1-improvements.md rename to docs/plans/10-poe-agent-tier1-improvements.md diff --git a/docs/plans/poe-code-config-schema-generation.md b/docs/plans/11-poe-code-config-schema-generation.md similarity index 100% rename from docs/plans/poe-code-config-schema-generation.md rename to docs/plans/11-poe-code-config-schema-generation.md diff --git a/docs/plans/provider-abstraction.md b/docs/plans/12-provider-abstraction.md similarity index 100% rename from docs/plans/provider-abstraction.md rename to docs/plans/12-provider-abstraction.md diff --git a/docs/plans/spawn-hooks.md b/docs/plans/13-spawn-hooks.md similarity index 100% rename from docs/plans/spawn-hooks.md rename to docs/plans/13-spawn-hooks.md diff --git a/docs/plans/spawn-independent-skills.md b/docs/plans/14-spawn-independent-skills.md similarity index 100% rename from docs/plans/spawn-independent-skills.md rename to docs/plans/14-spawn-independent-skills.md diff --git a/docs/plans/spawn-sdk-resume.md b/docs/plans/15-spawn-sdk-resume.md similarity index 100% rename from docs/plans/spawn-sdk-resume.md rename to docs/plans/15-spawn-sdk-resume.md diff --git a/docs/plans/superintendent-agentic-tools.md b/docs/plans/16-superintendent-agentic-tools.md similarity index 100% rename from docs/plans/superintendent-agentic-tools.md rename to docs/plans/16-superintendent-agentic-tools.md diff --git a/docs/plans/superintendent-plan-extends.md b/docs/plans/17-superintendent-plan-extends.md similarity index 100% rename from docs/plans/superintendent-plan-extends.md rename to docs/plans/17-superintendent-plan-extends.md diff --git a/docs/plans/superintendent-planner-role.md b/docs/plans/18-superintendent-planner-role.md similarity index 100% rename from docs/plans/superintendent-planner-role.md rename to docs/plans/18-superintendent-planner-role.md diff --git a/docs/plans/test-brittleness-constants.md b/docs/plans/19-test-brittleness-constants.md similarity index 100% rename from docs/plans/test-brittleness-constants.md rename to docs/plans/19-test-brittleness-constants.md diff --git a/docs/plans/toolcraft-release-notes.md b/docs/plans/20-toolcraft-release-notes.md similarity index 100% rename from docs/plans/toolcraft-release-notes.md rename to docs/plans/20-toolcraft-release-notes.md diff --git a/docs/plans/toolcraft-yaml-output.md b/docs/plans/21-toolcraft-yaml-output.md similarity index 100% rename from docs/plans/toolcraft-yaml-output.md rename to docs/plans/21-toolcraft-yaml-output.md diff --git a/docs/plans/zharness-plans-via-task-list.md b/docs/plans/22-zharness-plans-via-task-list.md similarity index 100% rename from docs/plans/zharness-plans-via-task-list.md rename to docs/plans/22-zharness-plans-via-task-list.md From 68411bca8848288cd010c463090d21407ad0970f Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 06:41:25 -0500 Subject: [PATCH 099/111] docs: update zharness plan status --- docs/plans/22-zharness-plans-via-task-list.md | 2 +- docs/plans/22-zharness-plans-via-task-list.md.lock | 1 + docs/plans/zharness-plans-via-task-list.md.lock | 1 - 3 files changed, 2 insertions(+), 2 deletions(-) create mode 100644 docs/plans/22-zharness-plans-via-task-list.md.lock delete mode 100644 docs/plans/zharness-plans-via-task-list.md.lock diff --git a/docs/plans/22-zharness-plans-via-task-list.md b/docs/plans/22-zharness-plans-via-task-list.md index 6bd3443163..6b9559839c 100644 --- a/docs/plans/22-zharness-plans-via-task-list.md +++ b/docs/plans/22-zharness-plans-via-task-list.md @@ -619,7 +619,7 @@ tasks: - Do not touch the `archive/` directories. - Do not rename files in `qa/`, `research/`, or `poe-agent/`. status: - implement: open + implement: done commit: open - id: cleanup-and-verify diff --git a/docs/plans/22-zharness-plans-via-task-list.md.lock b/docs/plans/22-zharness-plans-via-task-list.md.lock new file mode 100644 index 0000000000..d9bc7fe09a --- /dev/null +++ b/docs/plans/22-zharness-plans-via-task-list.md.lock @@ -0,0 +1 @@ +{"pid":61704,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T11:40:57.337Z"} \ No newline at end of file diff --git a/docs/plans/zharness-plans-via-task-list.md.lock b/docs/plans/zharness-plans-via-task-list.md.lock deleted file mode 100644 index eb70ef0392..0000000000 --- a/docs/plans/zharness-plans-via-task-list.md.lock +++ /dev/null @@ -1 +0,0 @@ -{"pid":2553,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T10:57:03.929Z"} \ No newline at end of file From bac682111112687683f675b2d5a63ff48569e737 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 07:05:56 -0500 Subject: [PATCH 100/111] feat: add pipeline dry run support --- docs/plans/01-agent-human-in-loop.md | 191 +++++++++++++++++- docs/plans/22-zharness-plans-via-task-list.md | 6 +- .../22-zharness-plans-via-task-list.md.lock | 2 +- packages/agent-harness-tools/src/plans.ts | 4 +- .../src/agent-kit-integration.test.ts | 49 ----- .../src/discovery/discovery.ts | 30 --- packages/experiment-loop/src/index.ts | 1 - packages/pipeline/src/pipeline.test.ts | 49 +++++ packages/pipeline/src/run/pipeline.ts | 17 ++ packages/pipeline/src/types.ts | 3 +- packages/plan-browser/src/actions.test.ts | 4 +- packages/plan-browser/src/actions.ts | 2 +- packages/plan-browser/src/browser.ts | 4 +- packages/plan-browser/src/index.ts | 8 +- src/cli/commands/experiment.ts | 21 +- src/cli/commands/pipeline-command.test.ts | 34 ++++ src/cli/commands/pipeline.ts | 48 +++-- 17 files changed, 355 insertions(+), 118 deletions(-) delete mode 100644 packages/experiment-loop/src/discovery/discovery.ts diff --git a/docs/plans/01-agent-human-in-loop.md b/docs/plans/01-agent-human-in-loop.md index 3e23d340ca..bc9d597e36 100644 --- a/docs/plans/01-agent-human-in-loop.md +++ b/docs/plans/01-agent-human-in-loop.md @@ -1,10 +1,191 @@ --- -$schema: https://poe-platform.github.io/poe-code/schemas/plans/ralph.schema.json -kind: ralph +$schema: https://poe-platform.github.io/poe-code/schemas/plans/pipeline.schema.json +kind: pipeline version: 1 -status: - state: in_progress - iteration: 0 + +tasks: + - id: scaffold-package + title: Create package scaffold + prompt: | + Create the package skeleton for `packages/agent-human-in-loop/`. + Files to create: + - `packages/agent-human-in-loop/package.json`: name `@poe-code/agent-human-in-loop`, + type `module`, exports `./dist/index.js`, types `./dist/index.d.ts`, + no runtime dependencies, devDependencies mirror `agent-mcp-config`. + - `packages/agent-human-in-loop/tsconfig.json`: extends the workspace root + tsconfig, outputs to `dist/`. + - `packages/agent-human-in-loop/src/index.ts`: empty placeholder export + so the build succeeds. + Verify: `npm run build --workspace agent-human-in-loop` and + `npm run test --workspace agent-human-in-loop` both pass with no tests. + status: + implement: open + + - id: define-types + title: Define public types + prompt: | + In `packages/agent-human-in-loop/src/types.ts` define: + ```ts + export interface ApprovalRequest { + message: string; + declineInputPrompt?: string; + } + export type ApprovalResult = + | { outcome: "approved" } + | { outcome: "declined"; reason?: string }; + export interface HumanInLoopProvider { + readonly id: string; + requestApproval(request: ApprovalRequest): Promise; + } + ``` + No runtime code, no class, no zod. Pure TypeScript interfaces only. + If no existing workspace package exports a lightweight `UserError`, + also define one here: `export class UserError extends Error {}`. + status: + implement: open + + - id: mock-provider + title: Implement mock provider with tests + prompt: | + TDD: write tests first, then implement. + + Test file `packages/agent-human-in-loop/src/providers/mock.test.ts`: + - value form: `mockProvider({ outcome: 'approved' })` returns the same + result on every call. + - thunk form: thunk is called once per `requestApproval` call; a counter + closure can produce a sequence. + - thunk returning a Promise resolves correctly. + + Implementation `packages/agent-human-in-loop/src/providers/mock.ts`: + ```ts + export function mockProvider( + answer: ApprovalResult | (() => ApprovalResult | Promise) + ): HumanInLoopProvider; + ``` + The provider id is `"mock"`. Types come from `../types.js`. + status: + implement: open + test: open + + - id: request-approval-fn + title: Implement top-level requestApproval with tests + prompt: | + TDD: write tests first, then implement. + + Test file `packages/agent-human-in-loop/src/request-approval.test.ts` + using `mockProvider` from `./providers/mock.js`: + - delegates to provider.requestApproval and returns its result verbatim. + - strips `provider` from args before calling provider.requestApproval + (the provider's own method must not receive `provider` in its argument). + + Implementation `packages/agent-human-in-loop/src/request-approval.ts`: + ```ts + export function requestApproval( + args: ApprovalRequest & { provider: HumanInLoopProvider } + ): Promise { + const { provider, ...request } = args; + return provider.requestApproval(request); + } + ``` + No branching on provider.id. Types from `./types.js`. + status: + implement: open + test: open + + - id: osascript-script-helpers + title: Implement AppleScript helpers with tests + prompt: | + TDD: write tests first, then implement. + + Test file `packages/agent-human-in-loop/src/providers/osascript-script.test.ts`: + - `escapeAppleScriptString`: message with `"` and `\` round-trips correctly; + backslash escaped before quote. + - `buildScript` without declineInputPrompt: emits one-line form with + `{"Decline","Approve"}` buttons and escaped message+title. + - `buildScript` with declineInputPrompt: emits two-stage AppleScript with + `APPROVED`/`DECLINED:` outputs; prompt and message both escaped. + Use snapshots for both script shapes. + - `parseStdout`: + - `"Approve\n"` → `{ outcome: "approved" }` + - `"Decline\n"` → `{ outcome: "declined" }` + - `"APPROVED\n"` → `{ outcome: "approved" }` + - `"DECLINED:because\n"` → `{ outcome: "declined", reason: "because" }` + - `"DECLINED:\n"` → `{ outcome: "declined" }` (no reason field) + - unknown string → throws UserError + + Implementation `packages/agent-human-in-loop/src/providers/osascript-script.ts`: + - `escapeAppleScriptString(value: string): string` — replace `\` then `"`. + - `buildScript(request: ApprovalRequest, title: string): string` + - `parseStdout(out: string): ApprovalResult` + No shelling out anywhere in this file. + status: + implement: open + refactor: open + test: open + + - id: osascript-provider + title: Implement osascript provider with tests + prompt: | + TDD: write tests first, then implement. + + Test file `packages/agent-human-in-loop/src/providers/osascript.test.ts`. + Use an injected fake `binary` that records its argv and returns canned stdout. + No real osascript is invoked. + + Cases: + - without declineInputPrompt: stdout `"Approve\n"` → approved; `"Decline\n"` → declined. + - with declineInputPrompt: stdout `"APPROVED\n"` → approved; + `"DECLINED:because\n"` → declined with reason; `"DECLINED:\n"` → declined no reason. + - ENOENT from execFile → UserError("osascript not found …"). + - non-zero exit with unrecognized stdout → UserError with stderr content. + - empty declineInputPrompt (`""`) is treated as set; two-stage script rendered. + + Implementation `packages/agent-human-in-loop/src/providers/osascript.ts`: + ```ts + export interface OsascryptProviderOptions { + title?: string; // default "Approval needed" + binary?: string; // default "osascript" — test seam only + } + export function osascryptProvider(options?: OsascryptProviderOptions): HumanInLoopProvider; + ``` + Provider id is `"osascript"`. Uses `buildScript`/`parseStdout` from + `./osascript-script.js` and `node:child_process` execFile (promisified). + No `if (provider.id === …)` anywhere. + status: + implement: open + test: open + + - id: public-exports-and-docs + title: Wire public exports, README, QA doc, and example + prompt: | + Finalize `packages/agent-human-in-loop/src/index.ts`: + ```ts + export type { ApprovalRequest, ApprovalResult, HumanInLoopProvider } from "./types.js"; + export { requestApproval } from "./request-approval.js"; + export { osascryptProvider } from "./providers/osascript.js"; + export { mockProvider } from "./providers/mock.js"; + ``` + + Write `packages/agent-human-in-loop/README.md` with sections: + Overview, API (requestApproval, osascryptProvider, mockProvider), + Providers, Env vars (explicitly: none in v1), + AppleScript-escaping note (only `"` and `\` need escaping). + + Write `packages/agent-human-in-loop/QA.md` as a markdown checklist (not a script): + - approve path returns approved + - decline without prompt returns declined + - decline with prompt → reason populated; cancel on second dialog → declined no reason + - message containing quotes renders correctly + - two concurrent calls show two stacked dialogs (macOS native behavior) + + Write `packages/agent-human-in-loop/example.ts` with two calls: + one simple approval, one decline-with-reason. Not part of CI. + + Run `npm run test`, `npm run lint`, `npm run typecheck` from the repo root. + Verify `grep -r "provider.id ===" packages/agent-human-in-loop/src` is empty. + Verify `grep -r "execFileSync\|spawnSync" packages/agent-human-in-loop/src` is empty. + status: + implement: open --- # agent-human-in-loop diff --git a/docs/plans/22-zharness-plans-via-task-list.md b/docs/plans/22-zharness-plans-via-task-list.md index 6b9559839c..aff036ca08 100644 --- a/docs/plans/22-zharness-plans-via-task-list.md +++ b/docs/plans/22-zharness-plans-via-task-list.md @@ -620,7 +620,7 @@ tasks: - Do not rename files in `qa/`, `research/`, or `poe-agent/`. status: implement: done - commit: open + commit: done - id: cleanup-and-verify title: Final cleanup — delete dead code and run full test suite @@ -665,8 +665,8 @@ tasks: - No new dependencies. - No README additions beyond what was added in the export task. status: - implement: open - test: open + implement: done + test: done commit: open --- diff --git a/docs/plans/22-zharness-plans-via-task-list.md.lock b/docs/plans/22-zharness-plans-via-task-list.md.lock index d9bc7fe09a..af9ce1a8f7 100644 --- a/docs/plans/22-zharness-plans-via-task-list.md.lock +++ b/docs/plans/22-zharness-plans-via-task-list.md.lock @@ -1 +1 @@ -{"pid":61704,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T11:40:57.337Z"} \ No newline at end of file +{"pid":82812,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T12:05:22.100Z"} \ No newline at end of file diff --git a/packages/agent-harness-tools/src/plans.ts b/packages/agent-harness-tools/src/plans.ts index babf69913a..4b5a7385f6 100644 --- a/packages/agent-harness-tools/src/plans.ts +++ b/packages/agent-harness-tools/src/plans.ts @@ -210,12 +210,12 @@ export async function discoverPlans(options: DiscoverPlansOptions): Promise { +export const archivePlan = async (options: ArchivePlanOptions): Promise => { const planDirectory = resolveWorkflowPath(options.planDirectory, options.cwd, options.homeDir); const taskList = await openPlansTaskList(planDirectory, options.fs); await taskList.list("plans").fire(options.id, "archive"); -} +}; export function openPlanList(options: OpenPlanListOptions): Promise { return openPlansTaskList( diff --git a/packages/experiment-loop/src/agent-kit-integration.test.ts b/packages/experiment-loop/src/agent-kit-integration.test.ts index 9bbf9d7928..98b8543946 100644 --- a/packages/experiment-loop/src/agent-kit-integration.test.ts +++ b/packages/experiment-loop/src/agent-kit-integration.test.ts @@ -1,6 +1,5 @@ import { createFsFromVolume, Volume } from "memfs"; import { describe, expect, it, vi } from "vitest"; -import { discoverExperimentDocs } from "./discovery/discovery.js"; import { runExperimentLoop } from "./run/loop.js"; import type { ExecFn, ExperimentFileSystem, ExperimentGit } from "./types.js"; @@ -28,10 +27,6 @@ function createDoc(): string { ].join("\n"); } -function createExperimentPlanDoc(content: string): string { - return ["---", "kind: experiment", "---", "", content].join("\n"); -} - function createGit(): ExperimentGit { return { reset: vi.fn(async () => undefined), @@ -45,50 +40,6 @@ function createExec(): ExecFn { }) as ExecFn; } -describe("experiment-loop agent-kit discovery", () => { - it("discovers default experiment docs from the project directory", async () => { - const docs = await discoverExperimentDocs({ - cwd, - homeDir, - fs: createFs({ - "/repo/.poe-code/experiments/shared.md": createExperimentPlanDoc("# project"), - "/home/test/.poe-code/experiments/global.md": createExperimentPlanDoc("# global"), - "/home/test/.poe-code/experiments/shared.md": createExperimentPlanDoc("# home") - }) - }); - - expect(docs).toEqual([ - { - path: ".poe-code/experiments/shared.md", - displayPath: ".poe-code/experiments/shared.md" - } - ]); - }); - - it("discovers docs from a custom experiment directory", async () => { - const docs = await discoverExperimentDocs({ - cwd, - homeDir, - planDirectory: "docs/experiments", - fs: createFs({ - "/repo/docs/experiments/plan-b.md": createExperimentPlanDoc("# B"), - "/repo/docs/experiments/plan-a.md": createExperimentPlanDoc("# A") - }) - }); - - expect(docs).toEqual([ - { - path: "docs/experiments/plan-a.md", - displayPath: "docs/experiments/plan-a.md" - }, - { - path: "docs/experiments/plan-b.md", - displayPath: "docs/experiments/plan-b.md" - } - ]); - }); -}); - describe("experiment-loop agent-kit locking", () => { it("locks the doc before initializing the journal and releases the lock after the run", async () => { const docPath = "/repo/.poe-code/experiments/plan.md"; diff --git a/packages/experiment-loop/src/discovery/discovery.ts b/packages/experiment-loop/src/discovery/discovery.ts deleted file mode 100644 index ccffaa6442..0000000000 --- a/packages/experiment-loop/src/discovery/discovery.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { - discoverPlans, - type DiscoverPlansOptions -} from "@poe-code/agent-harness-tools"; - -export type ExperimentDiscoveryFs = NonNullable; - -export interface DiscoverExperimentDocsOptions { - cwd: string; - homeDir: string; - planDirectory?: string; - fs?: ExperimentDiscoveryFs; -} - -export async function discoverExperimentDocs( - options: DiscoverExperimentDocsOptions -): Promise> { - const docs = await discoverPlans({ - cwd: options.cwd, - homeDir: options.homeDir, - planDirectory: options.planDirectory?.trim() || ".poe-code/experiments", - kinds: ["experiment"], - fs: options.fs - }); - - return docs.map((doc) => ({ - path: doc.displayPath, - displayPath: doc.displayPath - })); -} diff --git a/packages/experiment-loop/src/index.ts b/packages/experiment-loop/src/index.ts index 5a86a3fd22..cdae3c480d 100644 --- a/packages/experiment-loop/src/index.ts +++ b/packages/experiment-loop/src/index.ts @@ -4,5 +4,4 @@ export * from "./journal/journal.js"; export * from "./evaluator/evaluator.js"; export * from "./git/git.js"; export * from "./config/loader.js"; -export * from "./discovery/discovery.js"; export * from "./run/loop.js"; diff --git a/packages/pipeline/src/pipeline.test.ts b/packages/pipeline/src/pipeline.test.ts index 3ecf7f0b84..f171b35905 100644 --- a/packages/pipeline/src/pipeline.test.ts +++ b/packages/pipeline/src/pipeline.test.ts @@ -1796,6 +1796,55 @@ describe("resolveFileIncludes", () => { }); describe("createPipelineSimulation", () => { + it("dry-runs by resolving the plan without acquiring the lock or running agents", async () => { + const fs = createFs({ + "/repo/docs/plans/plan.md": [ + "---", + `$schema: ${pipelineDocumentSchemaId}`, + "kind: pipeline", + "version: 1", + "tasks:", + " - id: quick-fix", + " title: Quick fix", + " prompt: Fix the timeout regression", + " status: open", + "---", + "" + ].join("\n") + }); + const runAgent = vi.fn(); + const onPlanResolved = vi.fn(); + const onLockStatusChange = vi.fn(); + + const result = await runPipeline({ + agent: "codex", + cwd: "/repo", + homeDir: "/home/test", + plan: "docs/plans/plan.md", + dryRun: true, + fs, + onPlanResolved, + onLockStatusChange, + runAgent + }); + + expect(result.stopReason).toBe("dry_run"); + expect(result.runsCompleted).toBe(0); + expect(result.lastTaskId).toBe("quick-fix"); + expect(runAgent).not.toHaveBeenCalled(); + expect(onLockStatusChange).not.toHaveBeenCalled(); + expect(onPlanResolved).toHaveBeenCalledWith({ + planPath: "docs/plans/plan.md", + done: 0, + failed: 0, + open: 1, + total: 1 + }); + await expect(fs.readFile("/repo/docs/plans/plan.md", "utf8")).resolves.toContain( + "status: open" + ); + }); + it("emits lock wait feedback after 2 seconds and resolves it once the lock is acquired", async () => { vi.useFakeTimers(); vi.spyOn(Math, "random").mockReturnValue(0); diff --git a/packages/pipeline/src/run/pipeline.ts b/packages/pipeline/src/run/pipeline.ts index ab5b98cffa..3f08c68189 100644 --- a/packages/pipeline/src/run/pipeline.ts +++ b/packages/pipeline/src/run/pipeline.ts @@ -341,6 +341,23 @@ export async function runPipeline(options: PipelineRunOptions): Promise Promise; @@ -173,7 +174,7 @@ export interface PipelineRunOptions { } export interface PipelineRunResult { - stopReason: "completed" | "failed" | "cancelled" | "max_runs" | "nothing_to_run"; + stopReason: "completed" | "failed" | "cancelled" | "max_runs" | "nothing_to_run" | "dry_run"; planPath: string; runsCompleted: number; totalDurationMs: number; diff --git a/packages/plan-browser/src/actions.test.ts b/packages/plan-browser/src/actions.test.ts index 5d1582d1ea..f4be54b2b4 100644 --- a/packages/plan-browser/src/actions.test.ts +++ b/packages/plan-browser/src/actions.test.ts @@ -1,6 +1,6 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; import { Volume, createFsFromVolume } from "memfs"; -import { archivePlan, deletePlan, editPlan, resolveEditor } from "./actions.js"; +import { archiveBrowserPlan, deletePlan, editPlan, resolveEditor } from "./actions.js"; import type { ActionFs } from "./types.js"; function createMemFs(files: Record = {}): ActionFs { @@ -18,7 +18,7 @@ describe("plan actions", () => { "/repo/.poe-code/ralph/plans/plan.md": "# Plan" }); - const archivedPath = await archivePlan( + const archivedPath = await archiveBrowserPlan( { absolutePath: "/repo/.poe-code/ralph/plans/plan.md" }, diff --git a/packages/plan-browser/src/actions.ts b/packages/plan-browser/src/actions.ts index 2361fa90d3..4aa4c0655a 100644 --- a/packages/plan-browser/src/actions.ts +++ b/packages/plan-browser/src/actions.ts @@ -21,7 +21,7 @@ export function editPlan( spawnSync(editor, [absolutePath], { stdio: "inherit" }); } -export async function archivePlan( +export async function archiveBrowserPlan( entry: Pick<{ absolutePath: string }, "absolutePath">, fs: ActionFs ): Promise { diff --git a/packages/plan-browser/src/browser.ts b/packages/plan-browser/src/browser.ts index 63081aab5c..922dea356b 100644 --- a/packages/plan-browser/src/browser.ts +++ b/packages/plan-browser/src/browser.ts @@ -8,7 +8,7 @@ import { text } from "@poe-code/design-system"; import { PromptCancelledError } from "@poe-code/design-system"; -import { archivePlan, deletePlan, editPlan } from "./actions.js"; +import { archiveBrowserPlan, deletePlan, editPlan } from "./actions.js"; import { discoverAllPlans } from "./discovery.js"; import { loadPlanPreviewMarkdown } from "./format.js"; import type { ActionFs, DiscoveryFs, PlanEntry, PlanKind } from "./types.js"; @@ -104,7 +104,7 @@ export async function runPlanBrowser(options: { initialValue: true }); if (confirmed) { - await archivePlan(selectedPlan, options.fs as ActionFs); + await archiveBrowserPlan(selectedPlan, options.fs as ActionFs); } } catch (error) { if (!(error instanceof PromptCancelledError)) { diff --git a/packages/plan-browser/src/index.ts b/packages/plan-browser/src/index.ts index ff41226d3a..c032d49d7b 100644 --- a/packages/plan-browser/src/index.ts +++ b/packages/plan-browser/src/index.ts @@ -1,5 +1,11 @@ export { discoverAllPlans } from "./discovery.js"; -export { archivePlan, deletePlan, editPlan, resolveEditor } from "./actions.js"; +export { + archiveBrowserPlan, + archiveBrowserPlan as archivePlan, + deletePlan, + editPlan, + resolveEditor +} from "./actions.js"; export { deriveMarkdownTitle, formatExperimentDetail, diff --git a/src/cli/commands/experiment.ts b/src/cli/commands/experiment.ts index d9b96f8078..f3ffb6de33 100644 --- a/src/cli/commands/experiment.ts +++ b/src/cli/commands/experiment.ts @@ -19,6 +19,7 @@ import { } from "@poe-code/agent-defs"; import { resolvePlanDirectory } from "@poe-code/pipeline"; import { + discoverPlans, resolveLoopAgent, resolveWorkflowPath, skillPlanConfigSection @@ -29,7 +30,7 @@ import { supportedAgents, type SkillScope } from "@poe-code/agent-skill-config"; -import { discoverExperimentDocs, parseExperimentFrontmatter } from "@poe-code/experiment-loop"; +import { parseExperimentFrontmatter } from "@poe-code/experiment-loop"; import type { ExperimentFrontmatter } from "@poe-code/experiment-loop"; import type { AcpMiddleware } from "@poe-code/agent-spawn"; import type { CliContainer } from "../container.js"; @@ -536,12 +537,18 @@ async function resolveDocPath(options: { return options.providedDoc.trim(); } - const docs = await discoverExperimentDocs({ - cwd: options.container.env.cwd, - homeDir: options.container.env.homeDir, - planDirectory: options.planDirectory, - fs: options.container.fs - }); + const docs = ( + await discoverPlans({ + cwd: options.container.env.cwd, + homeDir: options.container.env.homeDir, + planDirectory: options.planDirectory, + kinds: ["experiment"], + fs: options.container.fs + }) + ).map((doc) => ({ + path: doc.displayPath, + displayPath: doc.displayPath + })); if (docs.length === 0) { throw new ValidationError( `No markdown doc found under ${options.planDirectory}. Provide a doc path.` diff --git a/src/cli/commands/pipeline-command.test.ts b/src/cli/commands/pipeline-command.test.ts index 8edf76c095..c889434960 100644 --- a/src/cli/commands/pipeline-command.test.ts +++ b/src/cli/commands/pipeline-command.test.ts @@ -221,6 +221,40 @@ describe("pipeline run command", () => { ); }); + it("dry-runs an explicit plan without prompting for an agent", async () => { + const fs = createMemFs({ + "/repo/docs/plans/plan.md": PIPELINE_MD_EMPTY + }); + const container = createCliContainer({ + fs, + prompts: vi.fn().mockResolvedValue({}), + env: { cwd, homeDir }, + logger: () => {} + }); + const program = createBaseProgram(); + registerPipelineCommand(program, container); + + await program.parseAsync([ + "node", + "cli", + "--dry-run", + "pipeline", + "run", + "--plan", + "docs/plans/plan.md" + ]); + + expect(resolvePipelineLoopAgentMock).not.toHaveBeenCalled(); + expect(selectMock).not.toHaveBeenCalled(); + expect(vi.mocked(sdkRunPipeline)).toHaveBeenCalledWith( + expect.objectContaining({ + agent: "claude-code", + plan: "docs/plans/plan.md", + dryRun: true + }) + ); + }); + it("runs integration pipeline callbacks after CLI callbacks when enabled", async () => { const calls: string[] = []; vi.doMock("@poe-code/braintrust", () => ({ diff --git a/src/cli/commands/pipeline.ts b/src/cli/commands/pipeline.ts index 3d6ebd9c24..70aa0a9513 100644 --- a/src/cli/commands/pipeline.ts +++ b/src/cli/commands/pipeline.ts @@ -744,9 +744,9 @@ export function registerPipelineCommand(program: Command, container: CliContaine .option("--plan ", "Path to the pipeline plan file") .option("--plans ", "Paths to pipeline plan files to run sequentially") .option("--max-runs ", "Maximum number of agent executions to perform") + .option("--dry-run", "Resolve the selected plan without running agents or changing files") .action(async function (this: Command) { const flags = resolveCommandFlags(program); - const resources = createExecutionResources(container, flags, "pipeline:run"); const options = this.opts<{ agent?: string; model?: string; @@ -755,26 +755,41 @@ export function registerPipelineCommand(program: Command, container: CliContaine plan?: string; plans?: string[]; maxRuns?: string; + dryRun?: boolean; }>(); + const dryRun = flags.dryRun || Boolean(options.dryRun); + const resources = createExecutionResources( + container, + { ...flags, dryRun }, + "pipeline:run" + ); resources.logger.intro("pipeline run"); let integrations: Integrations | null = null; try { - const selectedAgent = await resolvePipelineLoopAgent({ - providedAgent: options.agent, - configuredDefaultAgent: await resolveDefaultAgent(container), - assumeYes: flags.assumeYes, - fallbackAgent: DEFAULT_PIPELINE_AGENT, - message: "Select agent to run pipeline steps with:", - select, - isCancel - }); - if ("cancelled" in selectedAgent) { - cancel("Pipeline run cancelled."); + const configuredDefaultAgent = await resolveDefaultAgent(container); + const agent = dryRun + ? resolvePipelineAgent(options.agent ?? configuredDefaultAgent ?? DEFAULT_PIPELINE_AGENT) + : await (async () => { + const selectedAgent = await resolvePipelineLoopAgent({ + providedAgent: options.agent, + configuredDefaultAgent, + assumeYes: flags.assumeYes, + fallbackAgent: DEFAULT_PIPELINE_AGENT, + message: "Select agent to run pipeline steps with:", + select, + isCancel + }); + if ("cancelled" in selectedAgent) { + cancel("Pipeline run cancelled."); + return null; + } + return resolvePipelineAgent(selectedAgent.agent); + })(); + if (agent === null) { return; } - const agent = resolvePipelineAgent(selectedAgent.agent); const commandConfig = await resolvePipelineCommandConfig(container); integrations = await loadIntegrations(commandConfig.configDoc); @@ -835,6 +850,7 @@ export function registerPipelineCommand(program: Command, container: CliContaine ...(options.task ? { task: options.task } : {}), plan: planPath, ...(maxRuns != null ? { maxRuns } : {}), + ...(dryRun ? { dryRun: true } : {}), assumeYes: flags.assumeYes }; if (integrations?.spawnMiddleware) { @@ -916,6 +932,12 @@ export function registerPipelineCommand(program: Command, container: CliContaine continue; } + if (result.stopReason === "dry_run") { + resources.logger.info("Dry run complete."); + resources.logger.resolved("Run summary", summary); + continue; + } + if (result.stopReason === "max_runs") { resources.logger.info(`Reached max runs (${result.runsCompleted}).`); resources.logger.resolved("Run summary", summary); From f31623c27f0c0406d7380f7a3faa692e94032c95 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 07:06:42 -0500 Subject: [PATCH 101/111] docs: archive zharness task-list plan --- docs/plans/22-zharness-plans-via-task-list.md.lock | 2 +- docs/plans/{ => archive}/22-zharness-plans-via-task-list.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename docs/plans/{ => archive}/22-zharness-plans-via-task-list.md (99%) diff --git a/docs/plans/22-zharness-plans-via-task-list.md.lock b/docs/plans/22-zharness-plans-via-task-list.md.lock index af9ce1a8f7..c7816da2ba 100644 --- a/docs/plans/22-zharness-plans-via-task-list.md.lock +++ b/docs/plans/22-zharness-plans-via-task-list.md.lock @@ -1 +1 @@ -{"pid":82812,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T12:05:22.100Z"} \ No newline at end of file +{"pid":82812,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T12:06:13.910Z"} \ No newline at end of file diff --git a/docs/plans/22-zharness-plans-via-task-list.md b/docs/plans/archive/22-zharness-plans-via-task-list.md similarity index 99% rename from docs/plans/22-zharness-plans-via-task-list.md rename to docs/plans/archive/22-zharness-plans-via-task-list.md index aff036ca08..dc80102a4b 100644 --- a/docs/plans/22-zharness-plans-via-task-list.md +++ b/docs/plans/archive/22-zharness-plans-via-task-list.md @@ -667,7 +667,7 @@ tasks: status: implement: done test: done - commit: open + commit: done --- # Context From 39636c19265f7dd1e28b647e76d88445599bd3e6 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 09:37:54 -0500 Subject: [PATCH 102/111] feat(task-list): add ignoreMalformed flag to markdown-dir Lets callers scan a directory containing free-form markdown alongside tasks without aborting on the first file that fails frontmatter validation. get() still surfaces MalformedTaskError so per-id reads remain strict. --- ...ist.md => zharness-plans-via-task-list.md} | 0 .../src/backends/markdown-dir.test.ts | 67 +++++++++++++++++++ .../task-list/src/backends/markdown-dir.ts | 58 ++++++++++------ packages/task-list/src/open-task-list.test.ts | 2 + packages/task-list/src/open.ts | 2 + packages/task-list/src/types.ts | 2 + 6 files changed, 110 insertions(+), 21 deletions(-) rename docs/plans/archive/{22-zharness-plans-via-task-list.md => zharness-plans-via-task-list.md} (100%) diff --git a/docs/plans/archive/22-zharness-plans-via-task-list.md b/docs/plans/archive/zharness-plans-via-task-list.md similarity index 100% rename from docs/plans/archive/22-zharness-plans-via-task-list.md rename to docs/plans/archive/zharness-plans-via-task-list.md diff --git a/packages/task-list/src/backends/markdown-dir.test.ts b/packages/task-list/src/backends/markdown-dir.test.ts index 3ee39bf8cd..86885cff86 100644 --- a/packages/task-list/src/backends/markdown-dir.test.ts +++ b/packages/task-list/src/backends/markdown-dir.test.ts @@ -194,6 +194,73 @@ Broken` await expect(taskList.list("planning").get("bad")).rejects.toBeInstanceOf(MalformedTaskError); }); + it("skips files without frontmatter in all() when ignoreMalformed is true", async () => { + const { fs } = createFs({ + "/repo/tasks/01-valid.md": `--- +kind: pipeline +state: draft +--- + +Body`, + "/repo/tasks/02-no-frontmatter.md": "# Just a heading\n\nFree-form planning doc.\n", + "/repo/tasks/03-also-valid.md": `--- +kind: pipeline +state: draft +--- + +Body` + }); + const taskList = await openTaskList({ + type: "markdown-dir", + path: "/repo/tasks", + singleList: "plans", + frontmatterMode: "passthrough", + ignoreMalformed: true, + fs + }); + + const tasks = await taskList.list("plans").all(); + + expect(tasks.map((task) => task.id)).toEqual(["valid", "also-valid"]); + }); + + it("propagates MalformedTaskError from all() when ignoreMalformed is false", async () => { + const { fs } = createFs({ + "/repo/tasks/01-valid.md": `--- +kind: pipeline +state: draft +--- + +Body`, + "/repo/tasks/02-no-frontmatter.md": "# Just a heading\n" + }); + const taskList = await openTaskList({ + type: "markdown-dir", + path: "/repo/tasks", + singleList: "plans", + frontmatterMode: "passthrough", + fs + }); + + await expect(taskList.list("plans").all()).rejects.toBeInstanceOf(MalformedTaskError); + }); + + it("still throws MalformedTaskError from get() when ignoreMalformed is true", async () => { + const { fs } = createFs({ + "/repo/tasks/01-broken.md": "# Just a heading\n" + }); + const taskList = await openTaskList({ + type: "markdown-dir", + path: "/repo/tasks", + singleList: "plans", + frontmatterMode: "passthrough", + ignoreMalformed: true, + fs + }); + + await expect(taskList.list("plans").get("broken")).rejects.toBeInstanceOf(MalformedTaskError); + }); + it("rejects non-task frontmatter in strict mode", async () => { const { fs } = createFs({ "/repo/tasks/planning/pipeline.md": `--- diff --git a/packages/task-list/src/backends/markdown-dir.ts b/packages/task-list/src/backends/markdown-dir.ts index 5e5d3ba919..2c1368a612 100644 --- a/packages/task-list/src/backends/markdown-dir.ts +++ b/packages/task-list/src/backends/markdown-dir.ts @@ -630,22 +630,31 @@ function createTasksView(deps: BackendDeps, layout: ListLayout, list: string): T }> { const entries = await readActiveEntries(); const tasks = new Map(); + const validEntries: ActiveEntry[] = []; for (const entry of entries) { const filePath = path.join(listDirectoryPath, entry.filename); - const file = await readTaskFile( - deps.fs, - list, - entry.id, - filePath, - validStates, - stateMachine.initial, - deps.frontmatterMode - ); - tasks.set(entry.id, { task: file.task, raw: file.frontmatter }); + try { + const file = await readTaskFile( + deps.fs, + list, + entry.id, + filePath, + validStates, + stateMachine.initial, + deps.frontmatterMode + ); + tasks.set(entry.id, { task: file.task, raw: file.frontmatter }); + validEntries.push(entry); + } catch (error) { + if (deps.ignoreMalformed && error instanceof MalformedTaskError) { + continue; + } + throw error; + } } - return { entries, tasks }; + return { entries: validEntries, tasks }; } async function readArchivedTasks(): Promise<{ task: Task; raw: TaskRecord }[]> { @@ -661,16 +670,23 @@ function createTasksView(deps: BackendDeps, layout: ListLayout, list: string): T if (!entryStat?.isFile()) continue; const id = entryName.slice(0, -MARKDOWN_EXTENSION.length); - const file = await readTaskFile( - deps.fs, - list, - id, - entryPath, - validStates, - stateMachine.initial, - deps.frontmatterMode - ); - result.push({ task: file.task, raw: file.frontmatter }); + try { + const file = await readTaskFile( + deps.fs, + list, + id, + entryPath, + validStates, + stateMachine.initial, + deps.frontmatterMode + ); + result.push({ task: file.task, raw: file.frontmatter }); + } catch (error) { + if (deps.ignoreMalformed && error instanceof MalformedTaskError) { + continue; + } + throw error; + } } return result.sort((left, right) => diff --git a/packages/task-list/src/open-task-list.test.ts b/packages/task-list/src/open-task-list.test.ts index 86905d2545..b7769f1378 100644 --- a/packages/task-list/src/open-task-list.test.ts +++ b/packages/task-list/src/open-task-list.test.ts @@ -71,6 +71,7 @@ describe("openTaskList", () => { path: "/repo/tasks", singleList: undefined, frontmatterMode: "strict", + ignoreMalformed: false, defaults: { metadata: {} }, @@ -97,6 +98,7 @@ describe("openTaskList", () => { path: "/repo/tasks.yaml", singleList: undefined, frontmatterMode: "strict", + ignoreMalformed: false, defaults: { metadata: {} }, diff --git a/packages/task-list/src/open.ts b/packages/task-list/src/open.ts index 564dc582fe..d07132fbf0 100644 --- a/packages/task-list/src/open.ts +++ b/packages/task-list/src/open.ts @@ -54,6 +54,8 @@ async function openFileBackend(options: FileBackendOptions): Promise { path: options.path, singleList: options.singleList, frontmatterMode: options.frontmatterMode ?? "strict", + ignoreMalformed: + options.type === "markdown-dir" ? options.ignoreMalformed ?? false : false, defaults: { metadata: { ...(options.defaults?.metadata ?? {}) } }, diff --git a/packages/task-list/src/types.ts b/packages/task-list/src/types.ts index 90ecced758..e84ef5d18b 100644 --- a/packages/task-list/src/types.ts +++ b/packages/task-list/src/types.ts @@ -105,6 +105,7 @@ export interface OpenMarkdownDirOptions { path: string; singleList?: string; frontmatterMode?: "strict" | "passthrough"; + ignoreMalformed?: boolean; defaults?: TaskDefaults; create?: boolean; lockStaleMs?: number; @@ -137,6 +138,7 @@ export interface BackendDeps { path: string; singleList?: string; frontmatterMode: "strict" | "passthrough"; + ignoreMalformed?: boolean; defaults: Required; lockStaleMs: number; lockRetries: number; From c4b60921f81e4f4a926b04c1623a5584d3908802 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 09:38:23 -0500 Subject: [PATCH 103/111] feat(agent-harness-tools): tolerate malformed plan files discoverPlans now opens the plan list with ignoreMalformed: true so free-form markdown sitting next to plan files no longer breaks discovery for the surrounding harnesses. --- .../agent-harness-tools/src/plans.test.ts | 20 +++++++++++++++++++ packages/agent-harness-tools/src/plans.ts | 1 + 2 files changed, 21 insertions(+) diff --git a/packages/agent-harness-tools/src/plans.test.ts b/packages/agent-harness-tools/src/plans.test.ts index 9ff17ccd1d..ed811c3b13 100644 --- a/packages/agent-harness-tools/src/plans.test.ts +++ b/packages/agent-harness-tools/src/plans.test.ts @@ -165,6 +165,26 @@ describe("plans", () => { ); }); + it("skips files without frontmatter when discovering plans", async () => { + const { fs } = createFs({ + "/repo/.poe-code/plans/01-pipeline.md": planDocument({ + kind: "pipeline" + }), + "/repo/.poe-code/plans/02-free-form.md": + "# Free-form planning doc\n\nNo frontmatter here.\n", + "/repo/.poe-code/plans/03-another-pipeline.md": planDocument({ + kind: "pipeline" + }) + }); + + const plans = await discoverPlans({ + ...discoverOptions(fs), + kinds: ["pipeline"] + }); + + expect(plans.map((plan) => plan.id)).toEqual(["pipeline", "another-pipeline"]); + }); + it("returns an empty list when the plan directory does not exist", async () => { const { fs } = createFs({}); diff --git a/packages/agent-harness-tools/src/plans.ts b/packages/agent-harness-tools/src/plans.ts index 4b5a7385f6..553b356266 100644 --- a/packages/agent-harness-tools/src/plans.ts +++ b/packages/agent-harness-tools/src/plans.ts @@ -149,6 +149,7 @@ function openPlansTaskList(planDirectory: string, fs: TaskListFs | undefined): P path: planDirectory, singleList: "plans", frontmatterMode: "passthrough", + ignoreMalformed: true, fs }); } From d7e21087714619eca61a4d00041b65d158ccae7f Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 09:38:37 -0500 Subject: [PATCH 104/111] chore(docs): drop stale lock for archived zharness plan --- docs/plans/22-zharness-plans-via-task-list.md.lock | 1 - 1 file changed, 1 deletion(-) delete mode 100644 docs/plans/22-zharness-plans-via-task-list.md.lock diff --git a/docs/plans/22-zharness-plans-via-task-list.md.lock b/docs/plans/22-zharness-plans-via-task-list.md.lock deleted file mode 100644 index c7816da2ba..0000000000 --- a/docs/plans/22-zharness-plans-via-task-list.md.lock +++ /dev/null @@ -1 +0,0 @@ -{"pid":82812,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T12:06:13.910Z"} \ No newline at end of file From da7bce39e19858c31bd8457c33b53cf0a1f120df Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 10:00:19 -0500 Subject: [PATCH 105/111] refactor(spawn): remove unconfigured-service confirmation prompt Drops the " is not configured via poe. Do you want to proceed?" prompt from spawn (interactive and non-interactive paths) along with the supporting helper, imports, and tests. --- src/cli/commands/spawn-command.test.ts | 166 ------------------------- src/cli/commands/spawn.ts | 61 +-------- 2 files changed, 2 insertions(+), 225 deletions(-) diff --git a/src/cli/commands/spawn-command.test.ts b/src/cli/commands/spawn-command.test.ts index 29eb3a7b5f..fe4dabd69f 100644 --- a/src/cli/commands/spawn-command.test.ts +++ b/src/cli/commands/spawn-command.test.ts @@ -15,15 +15,12 @@ import { createProgram } from "../program.js"; import { registerSpawnCommand } from "./spawn.js"; import { createCliContainer, type CliDependencies } from "../container.js"; import type { FileSystem } from "../utils/file-system.js"; -import { OperationCancelledError } from "../errors.js"; import type { CommandRunner, CommandRunnerOptions, CommandRunnerResult } from "../../utils/command-checks.js"; -const confirmMock = vi.hoisted(() => vi.fn()); -const isCancelMock = vi.hoisted(() => vi.fn().mockReturnValue(false)); const resolveWorkspaceMock = vi.hoisted(() => vi.fn()); vi.mock("../../sdk/spawn.js", () => ({ @@ -68,15 +65,6 @@ vi.mock("@poe-code/agent-spawn", async (importOriginal) => { }; }); -vi.mock("@poe-code/design-system", async (importOriginal) => { - const actual = await importOriginal(); - return { - ...actual, - confirm: confirmMock, - isCancel: isCancelMock - }; -}); - import { spawn as sdkSpawn } from "../../sdk/spawn.js"; import { getSpawnConfig, spawnInteractive, supportsMcpAtSpawn } from "@poe-code/agent-spawn"; import { resolveWorkspace } from "@poe-code/workspace-resolver"; @@ -173,9 +161,6 @@ describe("spawn command", () => { process.env = { ...originalEnv, FORCE_COLOR: "1" }; resetOutputFormatCache(); - confirmMock.mockResolvedValue(true); - isCancelMock.mockReturnValue(false); - vi.mocked(sdkSpawn).mockImplementation(() => ({ events: emptyAsyncIterable(), result: Promise.resolve({ stdout: "", stderr: "", exitCode: 0 }) @@ -2013,155 +1998,4 @@ describe("spawn command", () => { }); }); - describe("unconfigured service warning", () => { - const configPath = resolveConfigPath(homeDir); - - async function writeConfiguredServices( - fileSystem: FileSystem, - services: Record - ): Promise { - await fileSystem.writeFile(configPath, JSON.stringify({ configured_services: services }), { - encoding: "utf8" - }); - } - - it("skips prompt when service is configured", async () => { - await writeConfiguredServices(fs, { - "claude-code": { files: [] } - }); - - const { runner } = createCommandRunnerStub(); - const program = createProgram({ - fs, - prompts: vi.fn().mockResolvedValue({}), - env: { cwd, homeDir }, - commandRunner: runner, - logger: () => {} - }); - - await program.parseAsync(["node", "cli", "spawn", "claude-code", "hello"]); - - expect(confirmMock).not.toHaveBeenCalled(); - expect(sdkSpawn).toHaveBeenCalled(); - }); - - it("prompts and proceeds when user confirms", async () => { - confirmMock.mockResolvedValueOnce(true); - - const { runner } = createCommandRunnerStub(); - const program = createProgram({ - fs, - prompts: vi.fn().mockResolvedValue({}), - env: { cwd, homeDir }, - commandRunner: runner, - logger: () => {} - }); - - await program.parseAsync(["node", "cli", "spawn", "claude-code", "hello"]); - - expect(confirmMock).toHaveBeenCalled(); - expect(sdkSpawn).toHaveBeenCalled(); - }); - - it("cancels spawn when user declines", async () => { - confirmMock.mockResolvedValueOnce(false); - - const { runner } = createCommandRunnerStub(); - const program = createProgram({ - fs, - prompts: vi.fn().mockResolvedValue({}), - env: { cwd, homeDir }, - commandRunner: runner, - logger: () => {} - }); - - await program.parseAsync(["node", "cli", "spawn", "claude-code", "hello"]); - - expect(confirmMock).toHaveBeenCalled(); - expect(sdkSpawn).not.toHaveBeenCalled(); - }); - - it("aborts spawn when confirmation is cancelled", async () => { - confirmMock.mockResolvedValueOnce(Symbol("cancelled")); - isCancelMock.mockReturnValue(true); - - const { runner } = createCommandRunnerStub(); - const program = createProgram({ - fs, - prompts: vi.fn().mockResolvedValue({}), - env: { cwd, homeDir }, - commandRunner: runner, - logger: () => {} - }); - - await expect( - program.parseAsync(["node", "cli", "spawn", "claude-code", "hello"]) - ).rejects.toBeInstanceOf(OperationCancelledError); - - expect(confirmMock).toHaveBeenCalled(); - expect(sdkSpawn).not.toHaveBeenCalled(); - }); - - it("skips prompt with --yes when not configured", async () => { - const { runner } = createCommandRunnerStub(); - const program = createProgram({ - fs, - prompts: vi.fn().mockResolvedValue({}), - env: { cwd, homeDir }, - commandRunner: runner, - logger: () => {} - }); - - await program.parseAsync(["node", "cli", "--yes", "spawn", "claude-code", "hello"]); - - expect(confirmMock).not.toHaveBeenCalled(); - expect(sdkSpawn).toHaveBeenCalled(); - }); - - it("prompts in interactive mode when not configured", async () => { - confirmMock.mockResolvedValueOnce(true); - vi.mocked(spawnInteractive).mockResolvedValue({ - stdout: "", - stderr: "", - exitCode: 0 - }); - - const { runner } = createCommandRunnerStub(); - const program = createProgram({ - fs, - prompts: vi.fn().mockResolvedValue({}), - env: { cwd, homeDir }, - commandRunner: runner, - logger: () => {} - }); - - await program.parseAsync(["node", "cli", "spawn", "--interactive", "claude-code", "hello"]); - - expect(confirmMock).toHaveBeenCalled(); - expect(spawnInteractive).toHaveBeenCalled(); - }); - - it("cancels interactive spawn when user declines", async () => { - confirmMock.mockResolvedValueOnce(false); - vi.mocked(spawnInteractive).mockResolvedValue({ - stdout: "", - stderr: "", - exitCode: 0 - }); - - const { runner } = createCommandRunnerStub(); - const program = createProgram({ - fs, - prompts: vi.fn().mockResolvedValue({}), - env: { cwd, homeDir }, - commandRunner: runner, - logger: () => {} - }); - - await program.parseAsync(["node", "cli", "spawn", "--interactive", "claude-code", "hello"]); - - expect(confirmMock).toHaveBeenCalled(); - expect(spawnInteractive).not.toHaveBeenCalled(); - }); - }); }); diff --git a/src/cli/commands/spawn.ts b/src/cli/commands/spawn.ts index 915ff470d7..55f30b3731 100644 --- a/src/cli/commands/spawn.ts +++ b/src/cli/commands/spawn.ts @@ -12,14 +12,7 @@ import { type SpawnMode } from "@poe-code/agent-spawn"; import { resolveAgentId } from "@poe-code/agent-defs"; -import { - text, - confirm, - isCancel, - resolveOutputFormat, - renderMarkdown -} from "@poe-code/design-system"; -import { loadConfiguredServices } from "../../services/config.js"; +import { text, resolveOutputFormat, renderMarkdown } from "@poe-code/design-system"; import { createExecutionResources, resolveCommandFlags, @@ -36,7 +29,7 @@ import { resolveConfiguredModel, spawnCore } from "../../sdk/spawn-core.js"; import { spawn as spawnSdk } from "../../sdk/spawn.js"; import { spawnAutonomous } from "../../sdk/autonomous.js"; import type { FileSystem } from "../../utils/file-system.js"; -import { OperationCancelledError, ValidationError } from "../errors.js"; +import { ValidationError } from "../errors.js"; import { resolveSpawnWorkspace } from "../../workspace/resolve-spawn-workspace.js"; import { addRuntimeOptions, pickRuntimeOptions, type RuntimeCliOptions } from "./runtime-options.js"; @@ -168,15 +161,6 @@ export function registerSpawnCommand( const adapter = resolveServiceAdapter(container, service); const canonicalService = adapter.name; assertInteractiveSupport(adapter.label, canonicalService); - const proceed = await confirmUnconfiguredService( - container, - canonicalService, - adapter.label, - flags - ); - if (!proceed) { - return; - } const model = await resolveConfiguredModel( container, canonicalService, @@ -284,16 +268,6 @@ export function registerSpawnCommand( return; } - const proceed = await confirmUnconfiguredService( - container, - canonicalService, - adapter.label, - flags - ); - if (!proceed) { - return; - } - const final = await traceSpawnRun(integrations, canonicalService, () => spawnAutonomous(spawnSdk, { service: canonicalService, @@ -415,37 +389,6 @@ function listSpawnServiceNames( return names; } -async function confirmUnconfiguredService( - container: CliContainer, - service: string, - label: string, - flags: CommandFlags -): Promise { - const configuredServices = await loadConfiguredServices({ - fs: container.fs, - filePath: container.env.configPath, - projectFilePath: container.env.projectConfigPath - }); - - if (service in configuredServices) { - return true; - } - - if (flags.assumeYes) { - return true; - } - - const shouldProceed = await confirm({ - message: `${label} is not configured via poe. Do you want to proceed?` - }); - - if (isCancel(shouldProceed)) { - throw new OperationCancelledError(); - } - - return shouldProceed === true; -} - async function resolvePromptInput( input: string, fs: FileSystem, From c201022ca9c58987802d65bf3424a6c249a952e1 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 10:13:25 -0500 Subject: [PATCH 106/111] feat(spawn): show spinner during runtime boot/sync phases Adds a SpawnProgressEvent contract on OpenSpec so providers can emit structured lifecycle events. The e2b factory and opened-env fire events around template build, sandbox connect, workspace upload/download. The spawn CLI translates these into a design-system spinner so silent boot phases no longer look frozen. --- .../src/execution-env.test.ts | 2 +- .../agent-harness-tools/src/execution-env.ts | 14 +++ .../src/poe-command-execution.ts | 2 +- packages/agent-spawn/src/acp/spawn.ts | 1 + packages/agent-spawn/src/index.ts | 2 + packages/agent-spawn/src/spawn-interactive.ts | 1 + packages/agent-spawn/src/spawn.ts | 1 + packages/agent-spawn/src/types.ts | 7 +- packages/runner-e2b/src/factory.test.ts | 94 +++++++++++++++++++ packages/runner-e2b/src/factory.ts | 40 +++++--- packages/runner-e2b/src/opened-env.test.ts | 73 ++++++++++++++ packages/runner-e2b/src/opened-env.ts | 4 + src/cli/commands/spawn-command.test.ts | 56 +++++++---- src/cli/commands/spawn.ts | 63 ++++++++++++- src/sdk/spawn.ts | 5 +- src/sdk/types.ts | 7 +- 16 files changed, 334 insertions(+), 38 deletions(-) diff --git a/packages/agent-harness-tools/src/execution-env.test.ts b/packages/agent-harness-tools/src/execution-env.test.ts index c9f58c6da8..512174860f 100644 --- a/packages/agent-harness-tools/src/execution-env.test.ts +++ b/packages/agent-harness-tools/src/execution-env.test.ts @@ -78,7 +78,7 @@ describe("execution env registry", () => { expect(branchSites).toMatchInlineSnapshot(` [ - "execution-env.ts:97:return selectExecutionEnvFactory(runtime.type);", + "execution-env.ts:111:return selectExecutionEnvFactory(runtime.type);", ] `); }); diff --git a/packages/agent-harness-tools/src/execution-env.ts b/packages/agent-harness-tools/src/execution-env.ts index 99e06fb789..5889ebf123 100644 --- a/packages/agent-harness-tools/src/execution-env.ts +++ b/packages/agent-harness-tools/src/execution-env.ts @@ -15,6 +15,19 @@ export interface ExecutionEnvFactory { attach(envId: string, context?: AttachedJobContext): Promise; } +export type SpawnProgressEvent = + | { kind: "template-build:start"; backend: ExecutionEnvType } + | { kind: "template-build:cached"; backend: ExecutionEnvType; templateId: string } + | { kind: "template-build:end"; backend: ExecutionEnvType; templateId: string } + | { kind: "sandbox-connect:start"; backend: ExecutionEnvType } + | { kind: "sandbox-connect:end"; backend: ExecutionEnvType; envId: string } + | { kind: "workspace-upload:start"; backend: ExecutionEnvType } + | { kind: "workspace-upload:end"; backend: ExecutionEnvType } + | { kind: "workspace-download:start"; backend: ExecutionEnvType } + | { kind: "workspace-download:end"; backend: ExecutionEnvType }; + +export type SpawnProgressListener = (event: SpawnProgressEvent) => void; + export interface OpenSpec { cwd: string; runtimeCwd?: string; @@ -25,6 +38,7 @@ export interface OpenSpec { env: Record; uploadIgnoreFiles: string[]; jobLabel: { tool: string; argv: string[] }; + onProgress?: SpawnProgressListener; execution?: { wrapForLogTee?: boolean; stdin?: RunSpec["stdin"]; diff --git a/packages/agent-harness-tools/src/poe-command-execution.ts b/packages/agent-harness-tools/src/poe-command-execution.ts index 7aba3e3e3f..dfac127e4c 100644 --- a/packages/agent-harness-tools/src/poe-command-execution.ts +++ b/packages/agent-harness-tools/src/poe-command-execution.ts @@ -38,7 +38,7 @@ export function resolvePoeCommandExecution(input: { homeDir?: string; state?: StateManager; }; - openSpec?: Partial>; + openSpec?: Partial>; }): { factory: ReturnType; openSpec: OpenSpec; diff --git a/packages/agent-spawn/src/acp/spawn.ts b/packages/agent-spawn/src/acp/spawn.ts index 91ab0b09fd..ce842f3e7a 100644 --- a/packages/agent-spawn/src/acp/spawn.ts +++ b/packages/agent-spawn/src/acp/spawn.ts @@ -202,6 +202,7 @@ export function spawnStreaming(options: SpawnStreamingOptions): SpawnStreamingRe runnerSync: options.runnerSync }, openSpec: { + ...(options.onProgress ? { onProgress: options.onProgress } : {}), execution: { wrapForLogTee: false, stdin: "pipe", diff --git a/packages/agent-spawn/src/index.ts b/packages/agent-spawn/src/index.ts index b37fa77af1..8ee994900a 100644 --- a/packages/agent-spawn/src/index.ts +++ b/packages/agent-spawn/src/index.ts @@ -30,6 +30,8 @@ export type { StdinMode } from "./types.js"; +export type { SpawnProgressEvent, SpawnProgressListener } from "@poe-code/agent-harness-tools"; + export { allSpawnConfigs, getAcpSpawnConfig, diff --git a/packages/agent-spawn/src/spawn-interactive.ts b/packages/agent-spawn/src/spawn-interactive.ts index 35425ffd5b..7f17efa80b 100644 --- a/packages/agent-spawn/src/spawn-interactive.ts +++ b/packages/agent-spawn/src/spawn-interactive.ts @@ -83,6 +83,7 @@ export async function spawnInteractive( runnerSync: options.runnerSync }, openSpec: { + ...(options.onProgress ? { onProgress: options.onProgress } : {}), execution: { wrapForLogTee: false, stdin: "inherit", diff --git a/packages/agent-spawn/src/spawn.ts b/packages/agent-spawn/src/spawn.ts index ed84ab31cb..81a2d05375 100644 --- a/packages/agent-spawn/src/spawn.ts +++ b/packages/agent-spawn/src/spawn.ts @@ -188,6 +188,7 @@ export async function spawn( }, context, openSpec: { + ...(options.onProgress ? { onProgress: options.onProgress } : {}), execution: { wrapForLogTee: false, stdin: stdinMode ? "pipe" : "inherit", diff --git a/packages/agent-spawn/src/types.ts b/packages/agent-spawn/src/types.ts index 4970c8e0c6..25bd456173 100644 --- a/packages/agent-spawn/src/types.ts +++ b/packages/agent-spawn/src/types.ts @@ -1,5 +1,8 @@ import type { AdapterType } from "./adapters/index.js"; -import type { RuntimeOverrideOptions } from "@poe-code/agent-harness-tools"; +import type { + RuntimeOverrideOptions, + SpawnProgressListener +} from "@poe-code/agent-harness-tools"; import type { StateManager } from "@poe-code/poe-code-config"; export type SpawnMode = "yolo" | "edit" | "read"; @@ -79,6 +82,8 @@ export interface SpawnOptions { mountPoeCode?: boolean; /** Override runner workspace sync behavior. */ runnerSync?: RuntimeOverrideOptions["runnerSync"]; + /** Listener for runtime lifecycle progress events (template build, sandbox connect, workspace sync). */ + onProgress?: SpawnProgressListener; } export interface SpawnUsage { diff --git a/packages/runner-e2b/src/factory.test.ts b/packages/runner-e2b/src/factory.test.ts index 721bf53869..d7a9e8df2f 100644 --- a/packages/runner-e2b/src/factory.test.ts +++ b/packages/runner-e2b/src/factory.test.ts @@ -89,6 +89,100 @@ describe("e2bExecutionEnvFactory", () => { ); }); + it("emits sandbox-connect progress events when opening with a direct template id", async () => { + const events: unknown[] = []; + const { e2bExecutionEnvFactory } = await import("./factory.js"); + + await e2bExecutionEnvFactory.open({ + cwd: "/repo", + runtime: { + type: "e2b", + template_id: "tmpl_configured", + build_args: {}, + mounts: [] + }, + env: {}, + uploadIgnoreFiles: [], + jobLabel: { tool: "node", argv: ["node"] }, + onProgress(event) { + events.push(event); + } + }); + + expect(events).toEqual([ + { kind: "sandbox-connect:start", backend: "e2b" }, + { kind: "sandbox-connect:end", backend: "e2b", envId: "sb_open" } + ]); + }); + + it("emits template-build and sandbox-connect events when building a fresh template", async () => { + const events: unknown[] = []; + const state = { templates: { get: vi.fn(), put: vi.fn() }, jobs: {} }; + const { e2bExecutionEnvFactory } = await import("./factory.js"); + + await e2bExecutionEnvFactory.open({ + cwd: "/repo", + runtime: { + type: "e2b", + dockerfile: "Dockerfile", + build_context: ".", + build_args: {}, + mounts: [] + }, + state: state as Parameters[0]["state"], + env: {}, + uploadIgnoreFiles: [], + jobLabel: { tool: "node", argv: ["node"] }, + onProgress(event) { + events.push(event); + } + }); + + expect(events).toEqual([ + { kind: "template-build:start", backend: "e2b" }, + { kind: "template-build:end", backend: "e2b", templateId: "tmpl_built" }, + { kind: "sandbox-connect:start", backend: "e2b" }, + { kind: "sandbox-connect:end", backend: "e2b", envId: "sb_open" } + ]); + }); + + it("emits a template-build:cached event when buildE2bRuntimeTemplate hits the cache", async () => { + vi.mocked(buildE2bRuntimeTemplate).mockResolvedValueOnce({ + backend: "e2b", + hash: "h", + templateId: "tmpl_cached", + cached: true + }); + const events: unknown[] = []; + const state = { templates: { get: vi.fn(), put: vi.fn() }, jobs: {} }; + const { e2bExecutionEnvFactory } = await import("./factory.js"); + + await e2bExecutionEnvFactory.open({ + cwd: "/repo", + runtime: { + type: "e2b", + dockerfile: "Dockerfile", + build_context: ".", + build_args: {}, + mounts: [] + }, + state: state as Parameters[0]["state"], + env: {}, + uploadIgnoreFiles: [], + jobLabel: { tool: "node", argv: ["node"] }, + onProgress(event) { + events.push(event); + } + }); + + expect(events).toEqual([ + { kind: "template-build:start", backend: "e2b" }, + { kind: "template-build:cached", backend: "e2b", templateId: "tmpl_cached" }, + { kind: "sandbox-connect:start", backend: "e2b" }, + { kind: "sandbox-connect:end", backend: "e2b", envId: "sb_open" } + ]); + }); + it("attaches to an existing sandbox id", async () => { const { e2bExecutionEnvFactory } = await import("./factory.js"); diff --git a/packages/runner-e2b/src/factory.ts b/packages/runner-e2b/src/factory.ts index 7f738dc7dc..e92b897e01 100644 --- a/packages/runner-e2b/src/factory.ts +++ b/packages/runner-e2b/src/factory.ts @@ -13,26 +13,38 @@ export const e2bExecutionEnvFactory: ExecutionEnvFactory = { const runtime = parseE2bRuntime(spec.runtime); const runtimeCwd = spec.runtimeCwd ?? spec.cwd; const apiKey = await resolveE2bApiKey({ cwd: runtimeCwd }); - const templateId = - runtime.template_id ?? - ( - await buildE2bRuntimeTemplate({ - runtime, - dockerfilePath: path.resolve( - runtimeCwd, - runtime.dockerfile ?? path.join(".poe-code", "Dockerfile") - ), - buildContext: path.resolve(runtimeCwd, runtime.build_context ?? "."), - state: spec.state, - apiKey - }) - ).templateId; + let templateId = runtime.template_id; + if (templateId === undefined) { + spec.onProgress?.({ kind: "template-build:start", backend: "e2b" }); + const built = await buildE2bRuntimeTemplate({ + runtime, + dockerfilePath: path.resolve( + runtimeCwd, + runtime.dockerfile ?? path.join(".poe-code", "Dockerfile") + ), + buildContext: path.resolve(runtimeCwd, runtime.build_context ?? "."), + state: spec.state, + apiKey + }); + templateId = built.templateId; + spec.onProgress?.( + built.cached + ? { kind: "template-build:cached", backend: "e2b", templateId } + : { kind: "template-build:end", backend: "e2b", templateId } + ); + } + spec.onProgress?.({ kind: "sandbox-connect:start", backend: "e2b" }); const sandbox = await createSandbox({ apiKey, templateId, env: spec.env, timeoutMinutes: runtime.timeout_minutes }); + spec.onProgress?.({ + kind: "sandbox-connect:end", + backend: "e2b", + envId: sandbox.sandboxId + }); return createOpenedE2bEnv({ sandbox, spec, runtime }); }, diff --git a/packages/runner-e2b/src/opened-env.test.ts b/packages/runner-e2b/src/opened-env.test.ts index b725e3e91e..4090255dcb 100644 --- a/packages/runner-e2b/src/opened-env.test.ts +++ b/packages/runner-e2b/src/opened-env.test.ts @@ -271,6 +271,79 @@ describe("createOpenedE2bEnv", () => { ); }); + it("emits workspace-upload progress events around the upload", async () => { + const hostRunner = createHostRunnerMock(); + const sandbox = createSandboxMock(); + sandbox.commands.run.mockResolvedValue({ exitCode: 0 }); + const events: unknown[] = []; + const env = createOpenedE2bEnv({ + sandbox, + runtime: { ...createRuntime(), workspace_dir: "/sandbox/workspace" }, + spec: { + ...createSpec(), + hostRunner, + onProgress(event) { + events.push(event); + } + } + }); + + await env.uploadWorkspace(); + + expect(events).toEqual([ + { kind: "workspace-upload:start", backend: "e2b" }, + { kind: "workspace-upload:end", backend: "e2b" } + ]); + }); + + it("emits workspace-download progress events around the download", async () => { + const hostRunner = createHostRunnerMock(); + const sandbox = createSandboxMock(); + sandbox.commands.run.mockResolvedValue({ exitCode: 0 }); + sandbox.files.read.mockResolvedValue(new Uint8Array([0x74, 0x61, 0x72])); + const events: unknown[] = []; + const env = createOpenedE2bEnv({ + sandbox, + runtime: { ...createRuntime(), workspace_dir: "/sandbox/workspace" }, + spec: { + ...createSpec(), + hostRunner, + onProgress(event) { + events.push(event); + } + } + }); + + await env.downloadWorkspace({ conflictPolicy: "overwrite" }); + + expect(events).toEqual([ + { kind: "workspace-download:start", backend: "e2b" }, + { kind: "workspace-download:end", backend: "e2b" } + ]); + }); + + it("does not emit workspace-upload events when sync is none", async () => { + const hostRunner = createHostRunnerMock(); + const sandbox = createSandboxMock(); + const events: unknown[] = []; + const env = createOpenedE2bEnv({ + sandbox, + runtime: { ...createRuntime(), workspace_dir: "/sandbox/workspace" }, + spec: { + ...createSpec(), + hostRunner, + runner: { sync: "none", download_conflict: "refuse" }, + onProgress(event) { + events.push(event); + } + } + }); + + await env.uploadWorkspace(); + + expect(events).toEqual([]); + }); + it("skips workspace upload when runner sync is none", async () => { const hostRunner = createHostRunnerMock(); const sandbox = createSandboxMock(); diff --git a/packages/runner-e2b/src/opened-env.ts b/packages/runner-e2b/src/opened-env.ts index e1e3e927d3..640dfb4244 100644 --- a/packages/runner-e2b/src/opened-env.ts +++ b/packages/runner-e2b/src/opened-env.ts @@ -75,6 +75,7 @@ export function createOpenedE2bEnv(input: { if (input.spec.runner?.sync === "none") { return { files: 0, bytes: 0, skipped: [] }; } + input.spec.onProgress?.({ kind: "workspace-upload:start", backend: "e2b" }); const tempDir = mkdtempSync(path.join(tmpdir(), "poe-e2b-upload-")); const archivePath = path.join(tempDir, "workspace.tar"); try { @@ -99,6 +100,7 @@ export function createOpenedE2bEnv(input: { input.sandbox, createUploadWorkspaceCommand(sandboxWorkspaceDir) ); + input.spec.onProgress?.({ kind: "workspace-upload:end", backend: "e2b" }); return { files: 0, bytes: 0, skipped: [] }; } finally { rmSync(tempDir, { recursive: true, force: true }); @@ -108,6 +110,7 @@ export function createOpenedE2bEnv(input: { if (input.spec.runner?.sync === "upload" || input.spec.runner?.sync === "none") { return { files: 0, bytes: 0, conflicts: [] }; } + input.spec.onProgress?.({ kind: "workspace-download:start", backend: "e2b" }); const tempDir = mkdtempSync(path.join(tmpdir(), "poe-e2b-download-")); const archivePath = path.join(tempDir, "workspace.tar"); try { @@ -130,6 +133,7 @@ export function createOpenedE2bEnv(input: { stdout: "pipe", stderr: "pipe" }); + input.spec.onProgress?.({ kind: "workspace-download:end", backend: "e2b" }); return { files: 0, bytes: archive.byteLength, conflicts: [] }; } finally { rmSync(tempDir, { recursive: true, force: true }); diff --git a/src/cli/commands/spawn-command.test.ts b/src/cli/commands/spawn-command.test.ts index fe4dabd69f..8922dfa960 100644 --- a/src/cli/commands/spawn-command.test.ts +++ b/src/cli/commands/spawn-command.test.ts @@ -221,7 +221,8 @@ describe("spawn command", () => { mode: undefined, cwd: undefined, activityTimeoutMs: 600_000, - runtimeConfigCwd: cwd + runtimeConfigCwd: cwd, + onProgress: expect.any(Function) }); const plainChunks = chunks.map((chunk) => stripAnsi(chunk)); @@ -771,7 +772,8 @@ describe("spawn command", () => { mode: undefined, cwd: undefined, activityTimeoutMs: 600_000, - runtimeConfigCwd: cwd + runtimeConfigCwd: cwd, + onProgress: expect.any(Function) }); }); @@ -800,7 +802,8 @@ describe("spawn command", () => { mode: undefined, cwd: undefined, activityTimeoutMs: 600_000, - runtimeConfigCwd: cwd + runtimeConfigCwd: cwd, + onProgress: expect.any(Function) }); }); @@ -839,6 +842,7 @@ describe("spawn command", () => { cwd: undefined, activityTimeoutMs: 600_000, runtimeConfigCwd: cwd, + onProgress: expect.any(Function), mcpServers: { test: { command: "tiny-stdio-mcp-test-server", @@ -890,6 +894,7 @@ describe("spawn command", () => { cwd: undefined, activityTimeoutMs: 600_000, runtimeConfigCwd: cwd, + onProgress: expect.any(Function), mcpServers: { test: { command: "tiny-stdio-mcp-test-server", @@ -941,6 +946,7 @@ describe("spawn command", () => { cwd: undefined, activityTimeoutMs: 600_000, runtimeConfigCwd: cwd, + onProgress: expect.any(Function), mcpServers: { test: { command: "tiny-stdio-mcp-test-server", @@ -994,6 +1000,7 @@ describe("spawn command", () => { cwd: undefined, activityTimeoutMs: 600_000, runtimeConfigCwd: cwd, + onProgress: expect.any(Function), mcpServers: { test: { command: "tiny-stdio-mcp-test-server", @@ -1045,6 +1052,7 @@ describe("spawn command", () => { cwd: undefined, activityTimeoutMs: 600_000, runtimeConfigCwd: cwd, + onProgress: expect.any(Function), mcpServers: { test: { command: "tiny-stdio-mcp-test-server", @@ -1085,7 +1093,8 @@ describe("spawn command", () => { cwd: undefined, logDir: "/tmp/spawn-logs", activityTimeoutMs: 1500, - runtimeConfigCwd: cwd + runtimeConfigCwd: cwd, + onProgress: expect.any(Function) }); }); @@ -1199,7 +1208,8 @@ describe("spawn command", () => { mode: undefined, cwd: undefined, activityTimeoutMs: 600_000, - runtimeConfigCwd: cwd + runtimeConfigCwd: cwd, + onProgress: expect.any(Function) }); }); @@ -1225,7 +1235,8 @@ describe("spawn command", () => { mode: undefined, cwd: undefined, activityTimeoutMs: 600_000, - runtimeConfigCwd: cwd + runtimeConfigCwd: cwd, + onProgress: expect.any(Function) }); }); @@ -1293,7 +1304,8 @@ describe("spawn command", () => { mode: undefined, cwd: undefined, activityTimeoutMs: 600_000, - runtimeConfigCwd: cwd + runtimeConfigCwd: cwd, + onProgress: expect.any(Function) }); }); @@ -1356,7 +1368,8 @@ describe("spawn command", () => { mode: undefined, cwd: customCwd, activityTimeoutMs: 600_000, - runtimeConfigCwd: cwd + runtimeConfigCwd: cwd, + onProgress: expect.any(Function) }); }); @@ -1389,7 +1402,8 @@ describe("spawn command", () => { mode: undefined, cwd: resolved, activityTimeoutMs: 600_000, - runtimeConfigCwd: cwd + runtimeConfigCwd: cwd, + onProgress: expect.any(Function) }); }); @@ -1438,7 +1452,8 @@ describe("spawn command", () => { model: DEFAULT_CODEX_MODEL, cwd: "/tmp/workspaces/poe-code", mode: undefined, - runtimeConfigCwd: cwd + runtimeConfigCwd: cwd, + onProgress: expect.any(Function) }); expect(cleanup).toHaveBeenCalledTimes(1); }); @@ -1472,7 +1487,8 @@ describe("spawn command", () => { mode: undefined, cwd: undefined, activityTimeoutMs: 600_000, - runtimeConfigCwd: cwd + runtimeConfigCwd: cwd, + onProgress: expect.any(Function) }); }); @@ -1505,7 +1521,8 @@ describe("spawn command", () => { mode: undefined, cwd: undefined, activityTimeoutMs: 600_000, - runtimeConfigCwd: cwd + runtimeConfigCwd: cwd, + onProgress: expect.any(Function) }); }); @@ -1764,7 +1781,8 @@ describe("spawn command", () => { model: DEFAULT_CLAUDE_CODE_MODEL, cwd: undefined, mode: undefined, - runtimeConfigCwd: cwd + runtimeConfigCwd: cwd, + onProgress: expect.any(Function) }); expect(sdkSpawn).not.toHaveBeenCalled(); }); @@ -1859,7 +1877,8 @@ describe("spawn command", () => { model: DEFAULT_GOOSE_MODEL, cwd: undefined, mode: undefined, - runtimeConfigCwd: cwd + runtimeConfigCwd: cwd, + onProgress: expect.any(Function) }); }); @@ -1919,7 +1938,8 @@ describe("spawn command", () => { model: DEFAULT_CLAUDE_CODE_MODEL, cwd: undefined, mode: undefined, - runtimeConfigCwd: cwd + runtimeConfigCwd: cwd, + onProgress: expect.any(Function) }); expect(sdkSpawn).not.toHaveBeenCalled(); }); @@ -1954,7 +1974,8 @@ describe("spawn command", () => { model: "anthropic/claude-opus-4.7", cwd: undefined, mode: undefined, - runtimeConfigCwd: cwd + runtimeConfigCwd: cwd, + onProgress: expect.any(Function) }); }); @@ -1993,7 +2014,8 @@ describe("spawn command", () => { model: "gpt-4", cwd: "/projects/demo", mode: undefined, - runtimeConfigCwd: cwd + runtimeConfigCwd: cwd, + onProgress: expect.any(Function) }); }); }); diff --git a/src/cli/commands/spawn.ts b/src/cli/commands/spawn.ts index 55f30b3731..056ad743b2 100644 --- a/src/cli/commands/spawn.ts +++ b/src/cli/commands/spawn.ts @@ -9,10 +9,11 @@ import { listMcpSupportedAgents, supportsMcpAtSpawn, type McpSpawnConfig, - type SpawnMode + type SpawnMode, + type SpawnProgressListener } from "@poe-code/agent-spawn"; import { resolveAgentId } from "@poe-code/agent-defs"; -import { text, resolveOutputFormat, renderMarkdown } from "@poe-code/design-system"; +import { text, resolveOutputFormat, renderMarkdown, spinner } from "@poe-code/design-system"; import { createExecutionResources, resolveCommandFlags, @@ -155,6 +156,8 @@ export function registerSpawnCommand( }); const cwdOverride = workspace.cwd; + const onProgress = shouldEmitUiOutput ? createRuntimeProgressSpinner() : undefined; + try { integrations = await loadIntegrations(await resolveMergedDocument(container)); if (commandOptions.interactive) { @@ -174,6 +177,7 @@ export function registerSpawnCommand( runtimeConfigCwd: container.env.cwd, ...runtimeOptions, ...(mcpServers ? { mcpServers } : {}), + ...(onProgress ? { onProgress } : {}), cwd: cwdOverride }); process.exitCode = result.exitCode; @@ -282,6 +286,7 @@ export function registerSpawnCommand( ? { activityTimeoutMs: spawnOptions.activityTimeoutMs } : {}), ...(spawnOptions.middlewares ? { middlewares: spawnOptions.middlewares } : {}), + ...(onProgress ? { onProgress } : {}), runtimeConfigCwd: container.env.cwd, ...runtimeOptions }) @@ -590,3 +595,57 @@ function assertInteractiveSupport(label: string, service: string): void { function isObjectRecord(value: unknown): value is Record { return typeof value === "object" && value !== null && !Array.isArray(value); } + +function createRuntimeProgressSpinner(): SpawnProgressListener { + let active: ReturnType | null = null; + let activePhase: string | null = null; + + const start = (phase: string, message: string): void => { + if (active) { + active.stop(""); + } + activePhase = phase; + active = spinner(); + active.start(message); + }; + + const stop = (phase: string, message: string): void => { + if (active && activePhase === phase) { + active.stop(message); + active = null; + activePhase = null; + } + }; + + return (event) => { + switch (event.kind) { + case "template-build:start": + start("template-build", "Building runtime template…"); + return; + case "template-build:cached": + stop("template-build", "Runtime template cached."); + return; + case "template-build:end": + stop("template-build", "Runtime template built."); + return; + case "sandbox-connect:start": + start("sandbox-connect", "Connecting to sandbox…"); + return; + case "sandbox-connect:end": + stop("sandbox-connect", "Sandbox ready."); + return; + case "workspace-upload:start": + start("workspace-upload", "Uploading workspace…"); + return; + case "workspace-upload:end": + stop("workspace-upload", "Workspace uploaded."); + return; + case "workspace-download:start": + start("workspace-download", "Syncing workspace back…"); + return; + case "workspace-download:end": + stop("workspace-download", "Workspace synced."); + return; + } + }; +} diff --git a/src/sdk/spawn.ts b/src/sdk/spawn.ts index 4a243f7b49..8d7ddb056f 100644 --- a/src/sdk/spawn.ts +++ b/src/sdk/spawn.ts @@ -146,7 +146,8 @@ export function spawn( args: options.args, runtimeConfigCwd: options.runtimeConfigCwd, ...runtimeOverrides, - ...(resolvedMcpServers ? { mcpServers: resolvedMcpServers } : {}) + ...(resolvedMcpServers ? { mcpServers: resolvedMcpServers } : {}), + ...(options.onProgress ? { onProgress: options.onProgress } : {}) }); return { stdout: interactiveResult.stdout, @@ -231,6 +232,7 @@ export function spawn( ...(options.activityTimeoutMs !== undefined ? { activityTimeoutMs: options.activityTimeoutMs } : {}), + ...(options.onProgress ? { onProgress: options.onProgress } : {}), useStdin: options.useStdin ?? false }); @@ -292,6 +294,7 @@ export function spawn( : {}), ...(options.logDir ? { logDir: options.logDir } : {}), ...(options.logFileName ? { logFileName: options.logFileName } : {}), + ...(options.onProgress ? { onProgress: options.onProgress } : {}), useStdin: options.useStdin ?? false }); } diff --git a/src/sdk/types.ts b/src/sdk/types.ts index 1b4e4daf24..49ba43e223 100644 --- a/src/sdk/types.ts +++ b/src/sdk/types.ts @@ -1,4 +1,7 @@ -import type { RuntimeOverrideOptions } from "@poe-code/agent-harness-tools"; +import type { + RuntimeOverrideOptions, + SpawnProgressListener +} from "@poe-code/agent-harness-tools"; import type { AcpMiddleware, McpSpawnConfig, @@ -60,6 +63,8 @@ export interface SpawnOptions { mountPoeCode?: boolean; /** Runner workspace sync override: both, upload, or none */ runnerSync?: RuntimeOverrideOptions["runnerSync"]; + /** Listener for runtime lifecycle progress events (template build, sandbox connect, workspace sync). */ + onProgress?: SpawnProgressListener; } /** From abceaac39e527f20ac3283d46295792c9fd43222 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 11:33:08 -0500 Subject: [PATCH 107/111] feat: add spawn session support --- docs/big-picture.md | 43 -- ...md => 02-http-mcp-production-readiness.md} | 0 ...d => 03-human-in-loop-approval-windows.md} | 0 ...set-sandbox.md => 04-js-subset-sandbox.md} | 0 ...ped-outputs.md => 05-mcp-typed-outputs.md} | 0 docs/plans/{08-memory.md => 06-memory.md} | 0 ...=> 07-pi-mono-coding-agent-integration.md} | 0 ...traction.md => 08-provider-abstraction.md} | 0 ...ills.md => 09-spawn-independent-skills.md} | 0 ...ts.md => 10-test-brittleness-constants.md} | 0 ...-output.md => 11-toolcraft-yaml-output.md} | 0 .../12-plan-browser-default-and-reordering.md | 85 +++ docs/plans/13-agent-harness-daemon.md | 183 ++++++ docs/plans/24-harness-session-runtime.md.lock | 1 + docs/plans/archive/harness-session-runtime.md | 305 ++++++++++ packages/agent-harness-tools/src/index.ts | 24 +- .../src/run-poe-command.test.ts | 109 +++- .../src/run-poe-command.ts | 71 ++- packages/agent-spawn/src/agent-spawn.test.ts | 1 + packages/agent-spawn/src/index.ts | 12 +- .../agent-spawn/src/spawn-session.test.ts | 361 +++++++++++ packages/agent-spawn/src/spawn-session.ts | 566 ++++++++++++++++++ packages/experiment-loop/README.md | 6 + packages/pipeline/README.md | 4 + packages/ralph/README.md | 6 +- packages/ralph/src/ralph.test.ts | 67 +++ packages/ralph/src/run/ralph.ts | 25 + packages/ralph/src/types.ts | 1 + packages/superintendent/README.md | 4 + .../src/commands/builder-group.test.ts | 15 +- .../src/commands/builder-group.ts | 20 +- .../src/commands/inspector-group.test.ts | 12 +- .../src/commands/inspector-group.ts | 50 +- packages/superintendent/src/commands/run.ts | 238 +++++--- .../src/runtime/agent-runner-session.ts | 70 +++ .../src/runtime/agent-runner.test.ts | 69 +++ .../src/runtime/agent-runner.ts | 40 +- .../superintendent/src/runtime/loop.test.ts | 398 +++++++----- packages/superintendent/src/runtime/loop.ts | 46 +- .../superintendent/src/runtime/run-builder.ts | 19 +- .../src/runtime/run-inspector.ts | 16 +- .../src/runtime/run-owner-review.ts | 27 +- .../src/runtime/run-superintendent.ts | 23 +- src/cli/commands/experiment-ralph.test.ts | 363 ++++++++++- src/cli/commands/experiment.ts | 514 +++++++++------- src/cli/commands/pipeline-command.test.ts | 230 ++++++- src/cli/commands/pipeline.ts | 380 +++++++----- src/cli/commands/ralph.ts | 251 ++++++-- src/index.ts | 6 + src/sdk/experiment.ts | 101 +++- src/sdk/pipeline.test.ts | 136 ++++- src/sdk/pipeline.ts | 133 ++-- src/sdk/ralph.test.ts | 167 ++++-- src/sdk/ralph.ts | 157 +++-- src/sdk/sdk-core.test.ts | 110 +++- src/sdk/spawn-session.ts | 6 + 56 files changed, 4373 insertions(+), 1098 deletions(-) delete mode 100644 docs/big-picture.md rename docs/plans/{04-http-mcp-production-readiness.md => 02-http-mcp-production-readiness.md} (100%) rename docs/plans/{05-human-in-loop-approval-windows.md => 03-human-in-loop-approval-windows.md} (100%) rename docs/plans/{06-js-subset-sandbox.md => 04-js-subset-sandbox.md} (100%) rename docs/plans/{07-mcp-typed-outputs.md => 05-mcp-typed-outputs.md} (100%) rename docs/plans/{08-memory.md => 06-memory.md} (100%) rename docs/plans/{09-pi-mono-coding-agent-integration.md => 07-pi-mono-coding-agent-integration.md} (100%) rename docs/plans/{12-provider-abstraction.md => 08-provider-abstraction.md} (100%) rename docs/plans/{14-spawn-independent-skills.md => 09-spawn-independent-skills.md} (100%) rename docs/plans/{19-test-brittleness-constants.md => 10-test-brittleness-constants.md} (100%) rename docs/plans/{21-toolcraft-yaml-output.md => 11-toolcraft-yaml-output.md} (100%) create mode 100644 docs/plans/12-plan-browser-default-and-reordering.md create mode 100644 docs/plans/13-agent-harness-daemon.md create mode 100644 docs/plans/24-harness-session-runtime.md.lock create mode 100644 docs/plans/archive/harness-session-runtime.md create mode 100644 packages/agent-spawn/src/spawn-session.test.ts create mode 100644 packages/agent-spawn/src/spawn-session.ts create mode 100644 packages/superintendent/src/runtime/agent-runner-session.ts create mode 100644 packages/superintendent/src/runtime/agent-runner.test.ts create mode 100644 src/sdk/spawn-session.ts diff --git a/docs/big-picture.md b/docs/big-picture.md deleted file mode 100644 index 1d459a100f..0000000000 --- a/docs/big-picture.md +++ /dev/null @@ -1,43 +0,0 @@ -# High Level CLI - - is this context is an agent e.g. claude code, codex - -## Global - -poe-code --help -poe-code login - -## Query - -poe-code query [--text] -poe-code query --image -poe-code query --audio -poe-code query --video --params { resolution: "4k" } - -## Agent - default - -[agent] is the default and can be omitted - -poe-code agent -poe-code [agent] configure -poe-code [agent] unconfigure -poe-code [agent] spawn -poe-code [agent] wrap -poe-code [agent] install -poe-code [agent] test - -## Skill - -poe-code skill configure # prompt for provider -poe-code skill configure -poe-code skill unconfigure -poe-code skill --help # explain that it will install skill - -## MCP - -poe-code mcp # output the configuration json -poe-code mcp run # start the stdio MCP server -poe-code mcp configure # prompt for provider, --yes auto selects default -poe-code mcp configure -poe-code mcp unconfigure -poe-code mcp --help diff --git a/docs/plans/04-http-mcp-production-readiness.md b/docs/plans/02-http-mcp-production-readiness.md similarity index 100% rename from docs/plans/04-http-mcp-production-readiness.md rename to docs/plans/02-http-mcp-production-readiness.md diff --git a/docs/plans/05-human-in-loop-approval-windows.md b/docs/plans/03-human-in-loop-approval-windows.md similarity index 100% rename from docs/plans/05-human-in-loop-approval-windows.md rename to docs/plans/03-human-in-loop-approval-windows.md diff --git a/docs/plans/06-js-subset-sandbox.md b/docs/plans/04-js-subset-sandbox.md similarity index 100% rename from docs/plans/06-js-subset-sandbox.md rename to docs/plans/04-js-subset-sandbox.md diff --git a/docs/plans/07-mcp-typed-outputs.md b/docs/plans/05-mcp-typed-outputs.md similarity index 100% rename from docs/plans/07-mcp-typed-outputs.md rename to docs/plans/05-mcp-typed-outputs.md diff --git a/docs/plans/08-memory.md b/docs/plans/06-memory.md similarity index 100% rename from docs/plans/08-memory.md rename to docs/plans/06-memory.md diff --git a/docs/plans/09-pi-mono-coding-agent-integration.md b/docs/plans/07-pi-mono-coding-agent-integration.md similarity index 100% rename from docs/plans/09-pi-mono-coding-agent-integration.md rename to docs/plans/07-pi-mono-coding-agent-integration.md diff --git a/docs/plans/12-provider-abstraction.md b/docs/plans/08-provider-abstraction.md similarity index 100% rename from docs/plans/12-provider-abstraction.md rename to docs/plans/08-provider-abstraction.md diff --git a/docs/plans/14-spawn-independent-skills.md b/docs/plans/09-spawn-independent-skills.md similarity index 100% rename from docs/plans/14-spawn-independent-skills.md rename to docs/plans/09-spawn-independent-skills.md diff --git a/docs/plans/19-test-brittleness-constants.md b/docs/plans/10-test-brittleness-constants.md similarity index 100% rename from docs/plans/19-test-brittleness-constants.md rename to docs/plans/10-test-brittleness-constants.md diff --git a/docs/plans/21-toolcraft-yaml-output.md b/docs/plans/11-toolcraft-yaml-output.md similarity index 100% rename from docs/plans/21-toolcraft-yaml-output.md rename to docs/plans/11-toolcraft-yaml-output.md diff --git a/docs/plans/12-plan-browser-default-and-reordering.md b/docs/plans/12-plan-browser-default-and-reordering.md new file mode 100644 index 0000000000..99cfa76b04 --- /dev/null +++ b/docs/plans/12-plan-browser-default-and-reordering.md @@ -0,0 +1,85 @@ +--- +$schema: https://poe-platform.github.io/poe-code/schemas/plans/plan.schema.json +kind: plan +version: 1 +--- + +# Plan browser as default and priority reordering + +Make `poe-code` (no args) launch the plan browser, and let users reorder plans by priority with shift+arrow. + +## 1. What we're building + +- The root command should run the manager (the plan browser, `poe-code plan browse`). +- Add priority ordering with shift+arrow keys in the browser. + +## 2. User-facing shape + +### Root command + +`poe-code` with no arguments launches the plan browser. Equivalent to `poe-code plan browse`. + +```text +$ poe-code +┌ plan browser +│ +◆ Select a plan +│ ❯ 01-agent-human-in-loop Plan +│ 02-ai-sdk-provider-poe-integration Plan +│ 03-consolidate-planning-docs Plan +│ 04-http-mcp-production-readiness Plan +│ 05-human-in-loop-approval-windows Plan +│ ... +│ +│ ↑↓ navigate · ⇧↑ ⇧↓ reorder · enter open · q quit +└ +``` + +`poe-code --help` still prints help. On non-TTY stdin (`poe-code | cat`, CI without a tty), the browser cannot run and the command prints help instead. `--yes` has no effect on the browser — the browser is interactive only. + +### Plan list ordering + +The list shows plans in the order returned by the underlying task-list (priority order). For the markdown-dir backend that's the prefix order on disk (`01-…` first, `21-…` last). Replaces the current mtime-based sort. + +### Reorder with shift+arrow + +While a plan is highlighted in the list: + +- `Shift+↑` — move the highlighted plan up by one position. +- `Shift+↓` — move the highlighted plan down by one position. + +The move is committed immediately via the task-list's `move()` operation. For the markdown-dir backend that means the file is renamed (prefixes are repacked) before the list re-renders. The highlight follows the moved plan so the user can keep nudging. + +If a move would be a no-op (already at top / bottom), the keypress is ignored. + +### Browser actions remain + +After picking a plan with `Enter`, the existing flow is unchanged: render preview → choose Edit / Archive / Delete / Back ([packages/plan-browser/src/browser.ts:79-130](packages/plan-browser/src/browser.ts#L79-L130)). Archive continues to call the task-list's `archive` event, which already repacks remaining prefixes ([commit 5caa5f1d](docs/plans/archive/zharness-plans-via-task-list.md)). + +### README addition + +Add a short section under the top-level "Quick start" of the project README: + +```md +### Plan browser + +Run `poe-code` with no arguments to open the plan browser. From there you can: + +- Browse plans across kinds (plan, pipeline, experiment, ralph, superintendent). +- Reorder plans by priority with `Shift+↑` / `Shift+↓`. +- Edit, archive, or delete the selected plan. + +The browser is also available as `poe-code plan browse`. +``` + +## 3. Implementation details and technical decisions + +_TBD._ + +## 4. Interfaces and test plan + +_TBD._ + +## 5. Code plan + +_TBD._ diff --git a/docs/plans/13-agent-harness-daemon.md b/docs/plans/13-agent-harness-daemon.md new file mode 100644 index 0000000000..625e53ec83 --- /dev/null +++ b/docs/plans/13-agent-harness-daemon.md @@ -0,0 +1,183 @@ +--- +$schema: https://poe-platform.github.io/poe-code/schemas/plans/plan.schema.json +kind: plan +version: 1 +--- + +# Agent Harness Daemon + +A long-running daemon that polls task-list backends and dispatches each task through a harness workflow. + +## 1. What we're building + +A new `agent-harness-daemon` package: a long-running process that polls one or more task lists, picks up actionable tasks, and runs an agent-script harness flow per task. Task sources go through the existing `task-list` abstraction (extending it where needed, not duplicating). The daemon itself is generic — repo-specific behavior comes from the configured task sources and the harness docs they bind to. + +The two concrete use cases this repo will configure on top of the generic daemon: + +- **PRs by `kamilio`, status open** — for each open PR, check the CI build for the head commit; if failing, run a fix-it harness and push. +- **Main branch monitor** — watch latest commit on `main`; if its build is failing, run the same fix-it harness against `main`. + +State is persisted as `pr# → status` (and `main# → status` for the main monitor) so the daemon doesn't re-process a SHA it has already seen. + +The "tasks" surface for the daemon — what it reads to know what to do — is expressed via the task-list abstraction. The new piece is a backend that returns PRs (or branch heads) as tasks. The user noted "this probably should be in agent-script": treating that as an open thread for level 3 — whether the daemon's per-task work is described as an agent-script harness doc, or whether the daemon is a thinner runner that calls the harness directly. + +### In scope + +- New `agent-harness-daemon` package with a CLI entrypoint (daemon-style: long-running, polls on an interval, graceful shutdown). +- New `task-list` backend: **GitHub PRs by author/status/repo** (returns each matching PR as a task; metadata carries head SHA, branch, CI conclusion). +- State store: JSON file keyed by `# → status`, so re-polls don't re-run on the same SHA. +- Generic config that lets a deployer point the daemon at one or more task sources, each bound to a harness doc. +- Repo-local config for the two concrete cases above. + +### Out of scope (deferred) + +- Picking up GitHub issues as daemon tasks. +- Parallel execution of tasks — sequential only, one task at a time (matches the project's "sequential only" working assumption). +- Multi-machine coordination / leader election. + +## 2. User-facing shape + +### Package and CLI + +`@poe-code/agent-harness-daemon` ships a `poe-harness-daemon` binary. SDK exports `runDaemon(opts)` and `pollOnce(opts)` so the CLI is a thin wrapper. + +```text +poe-harness-daemon start --config # long-running, polls until SIGINT/SIGTERM +poe-harness-daemon once --config # single poll cycle, exits 0 if all sources clean +poe-harness-daemon list --config # print actionable tasks per source, no execution +poe-harness-daemon state --config # print state.json contents in a table +poe-harness-daemon state clear --config --source [--key ] + # drop one entry or a whole source +``` + +Common flags on every command: + +- `--config ` (required) — daemon config file; relative paths resolve against `cwd`. +- `--state ` — overrides `state` in config; default is `.state.json` next to the config file. +- `--once` (alias for the `once` subcommand on `start`, useful for cron). +- `--source ` — restrict to one source from the config (debugging). +- `--verbose` / `-v` — stream per-task harness logs to stdout in addition to the log file. +- `--yes` — accept defaults for any prompt; the daemon never prompts otherwise. + +### Daemon config file + +JSON, explicit. One file per deployment. `polling.intervalMs` is required (no implicit default — per "explicit over implicit"). `sources[]` binds a task-list backend to a harness doc. + +```json +{ + "$schema": "https://poe-platform.github.io/poe-code/schemas/agent-harness-daemon/config.schema.json", + "polling": { + "intervalMs": 300000, + "jitterMs": 15000 + }, + "state": "./harness-daemon.state.json", + "logDir": "./.harness-daemon-logs", + "sources": [ + { + "name": "kamilio-open-prs", + "taskList": { + "type": "gh-prs", + "repo": "poe-platform/poe-code", + "filter": { "state": "open", "author": "kamilio" } + }, + "harness": { + "doc": "./harnesses/fix-failing-pr.md", + "cwdStrategy": "worktree-from-head" + }, + "selectTask": { + "where": { "metadata.ciConclusion": "failure" } + } + }, + { + "name": "main-branch-monitor", + "taskList": { + "type": "gh-branch-head", + "repo": "poe-platform/poe-code", + "branch": "main" + }, + "harness": { + "doc": "./harnesses/fix-failing-main.md", + "cwdStrategy": "worktree-from-head" + }, + "selectTask": { + "where": { "metadata.ciConclusion": "failure" } + } + } + ] +} +``` + +Each source field, explicitly: + +- `taskList`: any valid `OpenTaskListOptions` from `task-list`. The two new backend types — `gh-prs` and `gh-branch-head` — return tasks shaped like the existing backends but with metadata fields specific to PRs/branches (see level 3). +- `harness.doc`: path to an agent-script harness markdown doc. The daemon runs `runDocumentWorkflow` against it, one invocation per actionable task. +- `harness.cwdStrategy`: `"worktree-from-head"` (default — daemon prepares a git worktree at the task's head SHA before invoking the harness) or `"as-is"` (run in the daemon's cwd; the harness is responsible for checkout). +- `selectTask.where`: simple metadata predicate. Tasks not matching are still recorded in state as "skipped" so they don't get reconsidered until their SHA changes. + +### State file + +JSON, written atomically after each task completes. Keys are `#`. + +```json +{ + "version": 1, + "entries": { + "kamilio-open-prs#a1b2c3d4": { + "status": "succeeded", + "taskQualifiedId": "gh-prs/1234", + "lastRunAt": "2026-05-04T14:21:09Z", + "lastDurationMs": 184221, + "harnessDoc": "./harnesses/fix-failing-pr.md" + }, + "main-branch-monitor#9f8e7d6c": { + "status": "skipped", + "reason": "ci-passing", + "lastSeenAt": "2026-05-04T14:25:01Z" + } + } +} +``` + +`status` values: `"succeeded" | "failed" | "skipped" | "in-progress"`. An entry with `"in-progress"` blocks re-entry on that key — if the daemon crashes mid-task, restart preserves the in-progress marker, and the operator clears it via `state clear`. + +### Example terminal session + +```text +$ poe-harness-daemon start --config ./harness-daemon.config.json +[14:21:00] daemon started · config=./harness-daemon.config.json · interval=5m +[14:21:00] poll cycle 1 begin +[14:21:01] kamilio-open-prs: 4 open PRs · 1 actionable (PR #1234, ci=failure, sha=a1b2c3d4) +[14:21:01] main-branch-monitor: HEAD=9f8e7d6c · ci=success · skip +[14:21:02] dispatch: kamilio-open-prs#a1b2c3d4 → ./harnesses/fix-failing-pr.md +[14:21:02] worktree: prepared at /tmp/harness-daemon/kamilio-open-prs/a1b2c3d4 +[14:21:02] harness: fix-failing-pr.md iteration 1 +… +[14:24:06] harness: completed · pushed 1 commit (b5c6d7e8) to feat/foo +[14:24:06] state: kamilio-open-prs#a1b2c3d4 → succeeded +[14:24:06] poll cycle 1 done · next in 5m + +^C +[14:24:18] SIGINT received · finishing current task before exit (none in flight) +[14:24:18] daemon stopped cleanly +``` + +```text +$ poe-harness-daemon list --config ./harness-daemon.config.json +source task ci action +kamilio-open-prs PR #1234 (a1b2…) failure run +kamilio-open-prs PR #1230 (d4e5…) success skip +kamilio-open-prs PR #1228 (f6a7…) pending skip +kamilio-open-prs PR #1219 (b8c9…) success skip +main-branch-monitor main HEAD (9f8e…) success skip +``` + +```text +$ poe-harness-daemon state --config ./harness-daemon.config.json +source sha status last run duration +kamilio-open-prs a1b2c3d4 succeeded 2026-05-04 14:24:06 3m4s +main-branch-monitor 9f8e7d6c skipped 2026-05-04 14:25:01 — +``` + +### Repo-local configuration (this repo) + +Lives under `tools/harness-daemon/` with two harness docs (`fix-failing-pr.md`, `fix-failing-main.md`) and a single config file. Run via `npm run harness-daemon` (script wraps `poe-harness-daemon start --config tools/harness-daemon/config.json`). Not started automatically — operator-launched per "overnight detach workflow" memory. diff --git a/docs/plans/24-harness-session-runtime.md.lock b/docs/plans/24-harness-session-runtime.md.lock new file mode 100644 index 0000000000..4e178b037e --- /dev/null +++ b/docs/plans/24-harness-session-runtime.md.lock @@ -0,0 +1 @@ +{"pid":50723,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T16:31:48.004Z"} \ No newline at end of file diff --git a/docs/plans/archive/harness-session-runtime.md b/docs/plans/archive/harness-session-runtime.md new file mode 100644 index 0000000000..36d91f77ac --- /dev/null +++ b/docs/plans/archive/harness-session-runtime.md @@ -0,0 +1,305 @@ +--- +$schema: https://poe-platform.github.io/poe-code/schemas/plans/pipeline.schema.json +kind: pipeline +version: 1 +tasks: + - id: session-skip-per-iteration-download + title: Make PoeCommandSession skip per-iteration workspace download + prompt: > + Today `createPoeCommandSession` + (packages/agent-harness-tools/src/run-poe-command.ts) + + keeps a single sandbox alive across `session.run(...)` calls and uploads + + the workspace once on the first run, but its `runSync` helper still calls + + `env.downloadWorkspace(...)` after every handle exits. Against e2b/docker + + that means each iteration round-trips the whole tar archive even though + + the sandbox itself is reused. The user goal is "kick off the harness, walk + + away" — between-iteration downloads are wasted bandwidth and add the only + + remaining silent pause in the loop. + + + Change `session.run(openSpec, signal?)` to accept a third arg + + `{ syncBack?: boolean }` (default `false`). When `syncBack` is `false`, + + pass a flag through to `runSync` that skips the post-exit + + `downloadWorkspace` call. The session must still surface the agent's + + stdout/stderr/exitCode the same way. + + + Add `session.syncBack(): Promise` so callers can pull the + + workspace back on demand (e.g. on Ctrl-C, before close, or between + + iterations that need host-side files). Keep `session.close()` doing a + + final `downloadWorkspace` followed by `env.close()`. If `syncBack()` + + already ran and nothing changed, `close()` should still be safe to call + + (idempotent — gate on whether a download already happened since the last + + run). + + + Update or extend `runPoeCommand` so the existing single-shot path keeps + + its current behavior (download every call, close every call). + + + The runner-e2b factory must keep emitting `workspace-download:start` / + + `workspace-download:end` events from the spinner work that just shipped. + + Don't fire spurious download events when `syncBack` is false. + status: + implement: done + test: done + - id: spawn-session-primitive + title: Add createSpawnSession primitive to agent-spawn + SDK + prompt: | + Add `createSpawnSession` to `packages/agent-spawn` (new file + `src/spawn-session.ts`, re-exported from the package index). Signature: + + createSpawnSession(options: { + service: string; + cwd?: string; + runtime?, runtimeImage?, runtimeTemplate?, runtimeConfigCwd?, + mountPoeCode?, runnerSync?, + mode?, mcpServers?, model?, signal?, onProgress?, ... + }): { + run(input: { prompt: string; agent?: string; model?: string; + cwd?: string; signal?: AbortSignal; + syncBack?: boolean }): Promise; + syncBack(): Promise; + close(): Promise; + } + + Internals: call `resolvePoeCommandExecution` once with the constructor + options to get a factory + base openSpec + state, then + `createPoeCommandSession({ factory, state })`. Each `run(...)` builds a + per-call openSpec by deep-merging the base openSpec with prompt/agent/ + model/cwd overrides (use `buildSpawnArgs` from agent-spawn to render the + argv for the chosen agent). Pass `onProgress` from the constructor + through every openSpec so the spinner driver in src/cli/commands/spawn.ts + keeps working unchanged. + + Detach is incoherent with sessions (one sandbox can't host N detached + jobs and stay attached). When constructor opts include `detach: true`, + throw at construction time with a message pointing the caller to plain + `spawn(...)`. + + Mirror the primitive at `src/sdk/spawn-session.ts` as a thin re-export + (matches the existing src/sdk/spawn.ts wrapping pattern). Keep src/sdk + logic-free per CLAUDE.md ("core should be lightweight and only wire + packages and expose public apis"). + + Reference and consolidate the existing `createReusableE2bRalphRunner` in + src/sdk/ralph.ts — that helper already opens once with + `createPoeCommandSession`, but only fires when no custom `runAgent` is + passed (which the CLI always does, so the helper is dead in practice). + The new primitive replaces it; delete the duplicate code path once + task `wire-ralph-cli-session` lands. + status: + implement: done + test: done + - id: wire-ralph-cli-session + title: Wire ralph CLI to one runtime session for the whole loop + prompt: | + `src/cli/commands/ralph.ts` builds a per-iteration `runAgent` that calls + `sdkSpawn.autonomous(...)` (around line 107). Each call goes through + `runPoeCommand` and spins up a fresh sandbox / re-uploads the workspace. + For e2b especially, this is the silent-pause pile-up the user is hitting. + + Replace the per-iteration spawn with one `createSpawnSession(...)` opened + before `runRalph(...)` is called and closed in a `finally` after it + returns. The session's runtime opts come from the CLI flags + (`runtimeOptions` plus `runtimeConfigCwd: container.env.cwd`). The + dashboard `runAgent` (around `createRalphDashboardRunAgent`) becomes a + thin shim that calls `session.run({ agent, prompt, model, cwd, signal })` + and translates the result for the dashboard. + + Honor `--detach`: if the user passed `--detach`, skip the session + entirely and use the existing one-shot autonomous spawn path. Sessions + and detach are mutually exclusive (the SDK primitive throws on this + combo). + + Default `syncBack` to `false` for normal iterations. After the last + iteration completes (or on cancellation / fatal error), call + `session.syncBack()` once before `session.close()` so the user's local + tree reflects the final sandbox state. The host-side frontmatter writes + ralph already does (status: completed/open/failed) keep working — they + run AFTER the session.close(), so they see the synced files. + + Delete the now-dead `createReusableE2bRalphRunner` path in + `src/sdk/ralph.ts` and route the SDK `runRalph` through the new session + primitive too. + status: + implement: done + test: done + - id: wire-superintendent-session + title: Wire superintendent to one runtime session per run + prompt: | + `packages/superintendent/src/runtime/agent-runner.ts` calls + `runPoeCommand` (line 122) on every agent invocation. Across a multi-role + superintendent run that's N fresh sandbox boots and N workspace + uploads/downloads — same problem as ralph. + + Convert `agent-runner.ts` to take a session via input rather than + constructing its own factory + openSpec. Define a small + `AgentRunnerSession` interface in agent-harness-tools (re-export from + package index) that exposes `run(openSpec)` and `close()` — superintendent + depends on agent-harness-tools already, so no new dep. The session is + created in `packages/superintendent/src/runtime/run-superintendent.ts` + (or wherever the role loop is orchestrated) and passed down through the + role/iteration plumbing. + + The session itself comes from the SDK primitive in the CLI layer + (`src/sdk/superintendent.ts` or `src/cli/commands/...` — wherever + superintendent is invoked). Run-superintendent stays inside + `packages/superintendent` and accepts an injected session, keeping the + package free of SDK imports. + + Default `syncBack: false` between role invocations. Force a final + `syncBack()` then `close()` at the end of the run (and on cancel, in + `finally`). Each role still gets its own openSpec (different agent, + prompt, log path); only the runtime sandbox is shared. + + `runPoeCommand` stays untouched — superintendent's old code path is just + no longer used. + status: + implement: done + test: done + - id: wire-experiment-session + title: Wire experiment-loop to one runtime session with per-iteration sync + prompt: | + `src/cli/commands/experiment.ts` (`createExperimentDashboardRunAgent` / + `createExperimentCliRunAgent`, around lines 255 / 298 / 762) and + `src/sdk/experiment.ts` line 73 each iteration calls + `sdkSpawn.autonomous(...)` directly — fresh sandbox every time. + + Replace with a single `createSpawnSession(...)` opened before the loop + and closed in a `finally`. Both the dashboard and the CLI run-agent + shapes funnel through `session.run(...)`. + + IMPORTANT: experiment-loop runs git operations on the host cwd between + iterations (see `packages/experiment-loop/src/run/loop.ts` lines around + 390–500: `git.currentHash`, `git.reset`, journal commits keyed on + `entry.commit`). With a long-lived sandbox, the agent's edits live + inside the sandbox and the host tree is empty until something pulls it + back. The host-side git steps would see stale state. + + Pass `syncBack: true` on every `session.run(...)` call from + experiment-loop. The sandbox stays alive (saves boot cost — the only + thing the user actually cares about here), but files round-trip on each + iteration so the host git steps keep working unchanged. Document this + in the experiment-loop README so future authors know not to remove it. + + No change needed to `packages/experiment-loop/src/run/loop.ts` itself — + it accepts an injected `runAgent`, so swapping the CLI's runAgent + implementation is enough. + status: + implement: done + test: done + - id: wire-pipeline-session + title: Wire pipeline to one runtime session for the whole run + prompt: | + `src/cli/commands/pipeline.ts` has two runAgent factories + (`createPipelineDashboardRunAgent` around line 366, + `createPipelineCliRunAgent` around line 447) — both call `sdkSpawn(...)` + or `sdkSpawn.autonomous(...)` per task. `src/sdk/pipeline.ts` has + mirrored runAgent fallbacks (lines 111, 158). All of them spin up a + fresh sandbox per task. + + Replace with a `createSpawnSession(...)` opened before the pipeline run + starts (in `runPipelineWithDashboard` / `runPipeline` equivalents) and + closed in a `finally`. Both runAgent shapes funnel through + `session.run(...)`. Streaming events the dashboard relies on must keep + flowing — `session.run` should expose stdout/stderr the same way the + current spawn does (a streaming variant of `session.run` that returns + `{ events, result }` like `spawn(...)` does today; reuse the underlying + handle/streams). + + Default `syncBack: false` between tasks. Final + `syncBack()` + `close()` after the last task. Pipeline doesn't run + host-side git between tasks (commits happen via the agent's commit step + inside the sandbox), so deferred sync is correct here. + + Mirror the change in `src/sdk/pipeline.ts` so SDK callers get the same + behavior. Keep the existing `runAgent` override hook so users can plug + a custom runner if they want to (it bypasses the session). + status: + implement: done + test: done + - id: document-session-semantics + title: Document the session lifecycle in harness READMEs + prompt: | + Update the package READMEs to describe the new "one sandbox per harness + run" lifecycle. Don't add unrelated content; one tight section per + README. Touch: + + - packages/ralph/README.md — under a "Runtime sessions" or similar + section: explain that a single sandbox is opened at the start of + `ralph run` and reused across all iterations; workspace is uploaded + once and synced back at the end (or on abort). Note `--detach` is + incompatible with sessions and falls back to the one-shot path. + - packages/superintendent/README.md — same shape: one sandbox per + superintendent run, all roles share it. + - packages/experiment-loop/README.md — one sandbox per experiment run, + but workspace round-trips on every iteration because experiment-loop + runs git on the host between iterations. Be explicit that this is + intentional. + - packages/pipeline/README.md — one sandbox per pipeline run, sync at + end. + + Per CLAUDE.md "Keep the readme up to date but you are not allowed to + add anything to readme without user's permission" — these additions + ARE authorized by this plan; do not expand scope to unrelated sections. + status: + implement: done +state: archived +--- + +# Long-lived runtime session for harnesses + +## Why + +Today every iteration of every harness (ralph, superintendent, experiment, pipeline) calls `spawnAutonomous`, which goes through `runPoeCommand` and per-call does: + +1. `factory.open(...)` — fresh sandbox boot +2. `env.uploadWorkspace()` — full tar of cwd +3. agent runs +4. `env.downloadWorkspace(...)` — full tar back +5. `env.close()` — sandbox killed + +Against e2b, every iteration eats the cold-boot pause plus an upload and a download. The user's stated goal is to kick off a long harness run, close the laptop, and come back to a finished result — the per-iteration boot is the entire blocker. + +## Current audit + +- **ralph**: [src/cli/commands/ralph.ts:107](../../src/cli/commands/ralph.ts#L107) wires a custom `runAgent` to `sdkSpawn.autonomous(...)` per iteration — fresh sandbox every time. There is a partial `createReusableE2bRalphRunner` in [src/sdk/ralph.ts:58](../../src/sdk/ralph.ts#L58) that uses `createPoeCommandSession`, but the CLI always passes its own `runAgent` so the reusable path is dead. +- **superintendent**: [packages/superintendent/src/runtime/agent-runner.ts:122](../../packages/superintendent/src/runtime/agent-runner.ts#L122) calls `runPoeCommand` directly per agent invocation — fresh sandbox per role. +- **experiment**: [src/cli/commands/experiment.ts:267, :300, :762](../../src/cli/commands/experiment.ts) and [src/sdk/experiment.ts:73](../../src/sdk/experiment.ts#L73) call `sdkSpawn.autonomous(...)` per iteration. Constraint: experiment-loop runs git ops on the host cwd between iterations, so files must be on disk between iterations. +- **pipeline**: [src/cli/commands/pipeline.ts:380, :449](../../src/cli/commands/pipeline.ts) and [src/sdk/pipeline.ts:111, :158](../../src/sdk/pipeline.ts) call `sdkSpawn(...)` / `sdkSpawn.autonomous(...)` per task — fresh sandbox per task. + +## Foundation that already exists + +- `createPoeCommandSession` in [packages/agent-harness-tools/src/run-poe-command.ts:138](../../packages/agent-harness-tools/src/run-poe-command.ts#L138) — opens factory once, uploads once, exposes `run(spec)` for repeated calls. Sandbox stays alive; `close()` kills it. +- BUT `runSync` (line 357) still calls `downloadWorkspace` after every handle exits. So the session pattern as it stands saves the boot but not the per-iteration sync. Fixed by task `session-skip-per-iteration-download`. +- The progress-spinner work (commit `c201022c`) emits events for sandbox connect / template build / workspace upload / workspace download. Sessions must keep those events flowing for the existing spinner driver in [src/cli/commands/spawn.ts](../../src/cli/commands/spawn.ts). + +## Decisions + +- Session = one sandbox per harness run. All iterations / roles / tasks share it. +- Default sync semantics: upload once on first run, defer download to `session.close()`. Harnesses that need host-side files between iterations (only experiment-loop today, because of host git) opt into per-iteration sync via `syncBack: true`. +- `--detach` is incompatible with sessions. The SDK primitive throws on the combo; CLI flags fall back to the existing one-shot detach path. +- `createSpawnSession` lives in `packages/agent-spawn` (real logic) with a thin re-export at `src/sdk/spawn-session.ts` (CLAUDE.md: src/sdk is a wrapper, not a logic layer). +- Existing `createReusableE2bRalphRunner` in src/sdk/ralph.ts is deleted once ralph is wired to the new primitive — single shared path, no per-harness duplication (project memory: "Extend shared libs, don't duplicate"). +- TDD per CLAUDE.md. Each task ships with unit tests. Existing fast-mock patterns in `packages/runner-e2b/src/factory.test.ts` and `packages/agent-spawn/src/agent-spawn.test.ts` are the model. diff --git a/packages/agent-harness-tools/src/index.ts b/packages/agent-harness-tools/src/index.ts index 2e96938610..1f63e4fea6 100644 --- a/packages/agent-harness-tools/src/index.ts +++ b/packages/agent-harness-tools/src/index.ts @@ -1,13 +1,5 @@ -export { - discoverWorkflowDocs, - resolveWorkflowPath, - type DiscoverDocsOptions -} from "./paths.js"; -export { - discoverPlans, - archivePlan, - openPlanList -} from "./plans.js"; +export { discoverWorkflowDocs, resolveWorkflowPath, type DiscoverDocsOptions } from "./paths.js"; +export { discoverPlans, archivePlan, openPlanList } from "./plans.js"; export type { PlanRef, DiscoverPlansOptions, @@ -28,11 +20,7 @@ export { type WorkflowHook, type WorkflowMode } from "./hooks.js"; -export { - runWorkflowStage, - type StageContext, - type WorkflowStage -} from "./stage.js"; +export { runWorkflowStage, type StageContext, type WorkflowStage } from "./stage.js"; export { lockWorkflow, type LockOptions } from "./lock.js"; export { runDocumentWorkflow, @@ -41,10 +29,7 @@ export { type WorkflowFileStat, type WorkflowFileSystem } from "./runner.js"; -export { - runDocumentWorkflowSequence, - type DocumentWorkflowSequenceOptions -} from "./sequence.js"; +export { runDocumentWorkflowSequence, type DocumentWorkflowSequenceOptions } from "./sequence.js"; export { makeRunLogFileName, resolveRunLogDir, @@ -61,6 +46,7 @@ export { export { createPoeCommandSession, runPoeCommand, + type AgentRunnerSession, type PoeCommandSession } from "./run-poe-command.js"; export { diff --git a/packages/agent-harness-tools/src/run-poe-command.test.ts b/packages/agent-harness-tools/src/run-poe-command.test.ts index 6a769caff5..31ea76a0c1 100644 --- a/packages/agent-harness-tools/src/run-poe-command.test.ts +++ b/packages/agent-harness-tools/src/run-poe-command.test.ts @@ -317,7 +317,7 @@ describe("runPoeCommand", () => { expect(execStarted).toBe(true); }); - it("reuses an opened environment across session commands and downloads after each command", async () => { + it("reuses an opened environment across session commands without syncing by default", async () => { const { state } = createRecordingState(); const env = createMockEnv(); let opens = 0; @@ -348,14 +348,15 @@ describe("runPoeCommand", () => { expect(second).toMatchObject({ kind: "sync", exitCode: 0 }); expect(opens).toBe(1); expect(env.uploads).toBe(1); - expect(env.downloads).toEqual([{ conflictPolicy: "refuse" }, { conflictPolicy: "refuse" }]); + expect(env.downloads).toEqual([]); expect(env.closed).toBe(false); await session.close(); + expect(env.downloads).toEqual([{ conflictPolicy: "refuse" }]); expect(env.closed).toBe(true); }); - it("syncs a reused session workspace back after each command while keeping remote state for the next command", async () => { + it("syncs a reused session workspace back on demand while keeping remote state for the next command", async () => { const { state } = createRecordingState(); const env = createMockEnv(); let localIterations = ""; @@ -373,9 +374,8 @@ describe("runPoeCommand", () => { }; env.exec = (spec): RunHandle => { env.execSpecs.push(spec); - const nextIteration = remoteIterations.trim().length === 0 - ? 1 - : remoteIterations.trim().split("\n").length + 1; + const nextIteration = + remoteIterations.trim().length === 0 ? 1 : remoteIterations.trim().split("\n").length + 1; remoteIterations += `${nextIteration}\n`; return { pid: 123, @@ -399,9 +399,15 @@ describe("runPoeCommand", () => { }); await session.run(openSpec); + expect(localIterations).toBe(""); + + await session.syncBack(); expect(localIterations).toBe("1\n"); await session.run(openSpec); + expect(localIterations).toBe("1\n"); + + await session.syncBack(); expect(localIterations).toBe("1\n2\n"); expect(remoteIterations).toBe("1\n2\n"); expect(env.uploads).toBe(1); @@ -412,6 +418,97 @@ describe("runPoeCommand", () => { expect(env.execSpecs).toHaveLength(2); await session.close(); + expect(env.downloads).toHaveLength(2); + }); + + it("supports opt-in per-run sync back for reused sessions", async () => { + const { state } = createRecordingState(); + const env = createMockEnv(); + const session = createPoeCommandSession({ factory: createE2bFactory(env), state }); + + const result = await session.run(createOpenSpec(), undefined, { syncBack: true }); + + expect(result).toEqual({ + kind: "sync", + exitCode: 0, + download: { files: 0, bytes: 0, conflicts: [] } + }); + expect(env.downloads).toEqual([{ conflictPolicy: "refuse" }]); + + await session.close(); + expect(env.downloads).toHaveLength(1); + expect(env.closed).toBe(true); + }); + + it("captures session stdout and stderr without syncing back by default", async () => { + const { state } = createRecordingState(); + const env = createMockEnv(); + const stdout = new PassThrough(); + const stderr = new PassThrough(); + const runResult = deferred(); + env.exec = (spec): RunHandle => { + env.execSpecs.push(spec); + setImmediate(() => { + stdout.write("hello\n"); + stderr.write("warn\n"); + stdout.end(); + stderr.end(); + runResult.resolve({ exitCode: 7 }); + }); + return { + pid: 123, + stdout, + stderr, + stdin: null, + result: runResult.promise, + kill() {} + }; + }; + const session = createPoeCommandSession({ factory: createE2bFactory(env), state }); + + const result = await session.run( + createOpenSpec({ + execution: { captureOutput: true, wrapForLogTee: false } + }) + ); + + expect(result).toEqual({ + kind: "sync", + exitCode: 7, + stdout: "hello\n", + stderr: "warn\n" + }); + expect(env.downloads).toEqual([]); + + await session.close(); + expect(env.downloads).toEqual([{ conflictPolicy: "refuse" }]); + }); + + it("does not download on close when syncBack already ran after the last session command", async () => { + const { state } = createRecordingState(); + const env = createMockEnv(); + const session = createPoeCommandSession({ factory: createE2bFactory(env), state }); + + await session.run(createOpenSpec()); + await session.syncBack(); + await session.close(); + + expect(env.downloads).toEqual([{ conflictPolicy: "refuse" }]); + expect(env.closed).toBe(true); + }); + + it("allows no-op session sync and close before the first command", async () => { + const { state } = createRecordingState(); + const env = createMockEnv(); + const session = createPoeCommandSession({ factory: createE2bFactory(env), state }); + + await expect(session.syncBack()).resolves.toEqual({ files: 0, bytes: 0, conflicts: [] }); + await session.close(); + await session.close(); + + expect(env.uploads).toBe(0); + expect(env.downloads).toEqual([]); + expect(env.closed).toBe(false); }); it("configures the spawned E2B agent after upload and before the agent command", async () => { diff --git a/packages/agent-harness-tools/src/run-poe-command.ts b/packages/agent-harness-tools/src/run-poe-command.ts index 2762cfcb1a..01a50756d1 100644 --- a/packages/agent-harness-tools/src/run-poe-command.ts +++ b/packages/agent-harness-tools/src/run-poe-command.ts @@ -96,8 +96,12 @@ export async function runPoeCommand(opts: { jobId, openSpec: opts.openSpec, signal: opts.signal, - wrapCommand + wrapCommand, + syncBack: true }); + if (result.download === undefined) { + throw new Error("Expected workspace download result from single-shot Poe command run."); + } await runningJob; shouldClose = false; @@ -121,26 +125,32 @@ export async function runPoeCommand(opts: { } } -export interface PoeCommandSession { +export interface AgentRunnerSession { run( openSpec: OpenSpec, - signal?: AbortSignal + signal?: AbortSignal, + options?: { syncBack?: boolean } ): Promise<{ kind: "sync"; exitCode: number; - download: DownloadResult; + download?: DownloadResult; stdout?: string; stderr?: string; }>; + syncBack(): Promise; close(): Promise; } +export type PoeCommandSession = AgentRunnerSession; + export function createPoeCommandSession(opts: { factory: ExecutionEnvFactory; state: StateManager; }): PoeCommandSession { let env: OpenedEnv | null = null; let closed = false; + let lastOpenSpec: OpenSpec | null = null; + let needsDownload = false; async function getEnv(openSpec: OpenSpec): Promise { if (closed) { @@ -154,11 +164,24 @@ export function createPoeCommandSession(opts: { const opened = opts.factory.open(openSpec); env = isPromiseLike(opened) ? await opened : opened; await env.uploadWorkspace(); + lastOpenSpec = openSpec; return env; } + async function downloadCurrentWorkspace(): Promise { + if (env === null || lastOpenSpec === null) { + return { files: 0, bytes: 0, conflicts: [] }; + } + + const download = await env.downloadWorkspace({ + conflictPolicy: lastOpenSpec.runner?.download_conflict ?? "refuse" + }); + needsDownload = false; + return download; + } + return { - async run(openSpec, signal) { + async run(openSpec, signal, options) { const jobId = createUlid(); const pendingJob = opts.state.jobs.put({ id: jobId, @@ -171,6 +194,7 @@ export function createPoeCommandSession(opts: { status: "pending" }); const currentEnv = await getEnv(openSpec); + lastOpenSpec = openSpec; await pendingJob; await configureE2bSpawnAgentIfAvailable({ env: currentEnv, @@ -198,6 +222,7 @@ export function createPoeCommandSession(opts: { handle.stdin?.setDefaultEncoding("utf8"); handle.stdin?.end(openSpec.execution.input); } + needsDownload = true; await opts.state.jobs.update(jobId, { status: "running", @@ -212,8 +237,12 @@ export function createPoeCommandSession(opts: { openSpec, signal, wrapCommand, - closeAfterDownload: false + closeAfterDownload: false, + syncBack: options?.syncBack === true }); + if (result.download !== undefined) { + needsDownload = false; + } await opts.state.jobs.update(jobId, { status: "exited", @@ -224,17 +253,29 @@ export function createPoeCommandSession(opts: { return { kind: "sync", exitCode: result.exitCode, - download: result.download, + ...(result.download !== undefined ? { download: result.download } : {}), ...(result.stdout !== undefined ? { stdout: result.stdout } : {}), ...(result.stderr !== undefined ? { stderr: result.stderr } : {}) }; }, + async syncBack() { + if (closed) { + throw new Error("Cannot sync Poe command session after it is closed."); + } + return downloadCurrentWorkspace(); + }, async close() { if (closed) { return; } closed = true; - await env?.close(); + try { + if (needsDownload) { + await downloadCurrentWorkspace(); + } + } finally { + await env?.close(); + } } }; } @@ -362,7 +403,8 @@ async function runSync(opts: { signal?: AbortSignal; wrapCommand: boolean; closeAfterDownload?: boolean; -}): Promise<{ exitCode: number; download: DownloadResult; stdout?: string; stderr?: string }> { + syncBack?: boolean; +}): Promise<{ exitCode: number; download?: DownloadResult; stdout?: string; stderr?: string }> { const execution = opts.openSpec.execution; const capture = execution?.captureOutput === true; const abort = createAbortSync(opts.signal, opts.handle, execution?.activityTimeoutMs); @@ -375,15 +417,18 @@ async function runSync(opts: { const { exitCode } = opts.wrapCommand ? await abort.waitForExit(opts.env, opts.jobId) : await abort.waitForHandle(); - const download = await opts.env.downloadWorkspace({ - conflictPolicy: opts.openSpec.runner?.download_conflict ?? "refuse" - }); + const download = + opts.syncBack === false + ? undefined + : await opts.env.downloadWorkspace({ + conflictPolicy: opts.openSpec.runner?.download_conflict ?? "refuse" + }); if (opts.closeAfterDownload !== false) { await opts.env.close(); } return { exitCode, - download, + ...(download !== undefined ? { download } : {}), ...(capture ? { stdout: streamState.stdout(), stderr: streamState.stderr() } : {}) }; } finally { diff --git a/packages/agent-spawn/src/agent-spawn.test.ts b/packages/agent-spawn/src/agent-spawn.test.ts index a253bcb03c..5f3b0b48a0 100644 --- a/packages/agent-spawn/src/agent-spawn.test.ts +++ b/packages/agent-spawn/src/agent-spawn.test.ts @@ -88,6 +88,7 @@ describe("@poe-code/agent-spawn", () => { it("exports streaming + adapters API", () => { expect(typeof agentSpawnApi.spawn).toBe("function"); + expect(typeof agentSpawnApi.createSpawnSession).toBe("function"); expect(typeof agentSpawnApi.spawnAcp).toBe("function"); expect(typeof agentSpawnApi.spawnInteractive).toBe("function"); expect(typeof agentSpawnApi.spawnStreaming).toBe("function"); diff --git a/packages/agent-spawn/src/index.ts b/packages/agent-spawn/src/index.ts index 8ee994900a..a2077a603f 100644 --- a/packages/agent-spawn/src/index.ts +++ b/packages/agent-spawn/src/index.ts @@ -30,7 +30,11 @@ export type { StdinMode } from "./types.js"; -export type { SpawnProgressEvent, SpawnProgressListener } from "@poe-code/agent-harness-tools"; +export type { + DownloadResult, + SpawnProgressEvent, + SpawnProgressListener +} from "@poe-code/agent-harness-tools"; export { allSpawnConfigs, @@ -47,6 +51,12 @@ export { type BuildSpawnArgsResult } from "./spawn.js"; export { spawn } from "./spawn.js"; +export { + createSpawnSession, + type CreateSpawnSessionOptions, + type SpawnSession, + type SpawnSessionRunInput +} from "./spawn-session.js"; export { spawnInteractive } from "./spawn-interactive.js"; export { spawnAutonomous } from "./autonomous.js"; export type { AutonomousOptions, StreamingSpawnFn, StreamingSpawnReturn } from "./autonomous.js"; diff --git a/packages/agent-spawn/src/spawn-session.test.ts b/packages/agent-spawn/src/spawn-session.test.ts new file mode 100644 index 0000000000..5d4e284571 --- /dev/null +++ b/packages/agent-spawn/src/spawn-session.test.ts @@ -0,0 +1,361 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { createSpawnSession } from "./spawn-session.js"; +import type { OpenSpec } from "@poe-code/agent-harness-tools"; +import type { AcpMiddleware } from "./acp/middleware.js"; + +const createPoeCommandSessionMock = vi.hoisted(() => vi.fn()); +const resolvePoeCommandExecutionMock = vi.hoisted(() => vi.fn()); + +vi.mock("@poe-code/agent-harness-tools", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + createPoeCommandSession: createPoeCommandSessionMock, + resolvePoeCommandExecution: resolvePoeCommandExecutionMock + }; +}); + +describe("createSpawnSession", () => { + beforeEach(() => { + createPoeCommandSessionMock.mockReset(); + resolvePoeCommandExecutionMock.mockReset(); + }); + + it("rejects detached sessions at construction time", () => { + expect(() => + createSpawnSession({ + service: "claude-code", + detach: true + }) + ).toThrow(/detach.*spawn\(\.\.\.\)/i); + + expect(resolvePoeCommandExecutionMock).not.toHaveBeenCalled(); + expect(createPoeCommandSessionMock).not.toHaveBeenCalled(); + }); + + it("resolves the runtime once and reuses the command session for runs", async () => { + const run = vi.fn().mockResolvedValue({ + kind: "sync", + exitCode: 0, + stdout: "done", + stderr: "", + download: { files: 1, bytes: 2, conflicts: [] } + }); + const syncBack = vi.fn().mockResolvedValue({ files: 2, bytes: 4, conflicts: [] }); + const close = vi.fn().mockResolvedValue(undefined); + const factory = { type: "e2b" }; + const state = { jobs: {} }; + const onProgress = vi.fn(); + const baseOpenSpec = createBaseOpenSpec(onProgress); + + resolvePoeCommandExecutionMock.mockReturnValue({ + factory, + state, + detach: false, + openSpec: baseOpenSpec + }); + createPoeCommandSessionMock.mockReturnValue({ run, syncBack, close }); + + const session = createSpawnSession({ + service: "claude-code", + cwd: "/repo", + runtime: "e2b", + runtimeTemplate: "tmpl_base", + runtimeConfigCwd: "/config", + model: "base-model", + mode: "read", + downloadConflict: "overwrite", + onProgress + }); + + await expect( + session.run({ + prompt: "fix bug", + agent: "codex", + model: "gpt-5", + cwd: "/repo/pkg", + syncBack: true + }) + ).resolves.toEqual({ + stdout: "done", + stderr: "", + exitCode: 0 + }); + await expect(session.syncBack()).resolves.toEqual({ files: 2, bytes: 4, conflicts: [] }); + await session.close(); + + expect(resolvePoeCommandExecutionMock).toHaveBeenCalledTimes(1); + expect(resolvePoeCommandExecutionMock).toHaveBeenCalledWith( + expect.objectContaining({ + cwd: "/repo", + runtimeConfigCwd: "/config", + tool: "claude-code", + runtime: expect.objectContaining({ + runtime: "e2b", + runtimeTemplate: "tmpl_base" + }), + openSpec: expect.objectContaining({ + onProgress + }) + }) + ); + expect(createPoeCommandSessionMock).toHaveBeenCalledTimes(1); + expect(createPoeCommandSessionMock).toHaveBeenCalledWith({ factory, state }); + expect(run).toHaveBeenCalledTimes(1); + expect(run).toHaveBeenCalledWith( + expect.objectContaining({ + ...baseOpenSpec, + cwd: "/repo/pkg", + onProgress, + env: expect.objectContaining(process.env), + runner: expect.objectContaining({ + download_conflict: "overwrite", + workspace: { exclude: ["node_modules"] } + }), + jobLabel: { + tool: "codex", + argv: expect.arrayContaining(["codex", "exec", "fix bug"]) + }, + execution: expect.objectContaining({ + wrapForLogTee: false, + stdout: "pipe", + stderr: "pipe", + captureOutput: true, + env: expect.objectContaining(process.env) + }) + }), + undefined, + { syncBack: true } + ); + expect(syncBack).toHaveBeenCalledTimes(1); + expect(close).toHaveBeenCalledTimes(1); + }); + + it("uses the constructor signal when a run does not provide one", async () => { + const signal = new AbortController().signal; + const run = vi.fn().mockResolvedValue({ kind: "sync", exitCode: 0 }); + resolvePoeCommandExecutionMock.mockReturnValue({ + factory: { type: "host" }, + state: { jobs: {} }, + detach: false, + openSpec: createBaseOpenSpec() + }); + createPoeCommandSessionMock.mockReturnValue({ + run, + syncBack: vi.fn(), + close: vi.fn() + }); + + const session = createSpawnSession({ service: "claude-code", signal }); + await session.run({ prompt: "hello" }); + + expect(run.mock.calls[0]?.[1]).toBe(signal); + }); + + it("uses a per-run signal over the constructor signal", async () => { + const constructorSignal = new AbortController().signal; + const runSignal = new AbortController().signal; + const run = vi.fn().mockResolvedValue({ kind: "sync", exitCode: 0 }); + resolvePoeCommandExecutionMock.mockReturnValue({ + factory: { type: "host" }, + state: { jobs: {} }, + detach: false, + openSpec: createBaseOpenSpec() + }); + createPoeCommandSessionMock.mockReturnValue({ + run, + syncBack: vi.fn(), + close: vi.fn() + }); + + const session = createSpawnSession({ service: "claude-code", signal: constructorSignal }); + await session.run({ prompt: "hello", signal: runSignal }); + + expect(run.mock.calls[0]?.[1]).toBe(runSignal); + }); + + it("passes stdin-mode prompts through execution input instead of argv", async () => { + const run = vi.fn().mockResolvedValue({ + kind: "sync", + exitCode: 0, + stdout: "ok", + stderr: "" + }); + resolvePoeCommandExecutionMock.mockReturnValue({ + factory: { type: "host" }, + state: { jobs: {} }, + detach: false, + openSpec: createBaseOpenSpec() + }); + createPoeCommandSessionMock.mockReturnValue({ + run, + syncBack: vi.fn(), + close: vi.fn() + }); + + const session = createSpawnSession({ service: "codex", useStdin: true }); + await session.run({ prompt: "stdin prompt" }); + + const openSpec = run.mock.calls[0]?.[0] as OpenSpec; + expect(openSpec.jobLabel.argv).toContain("-"); + expect(openSpec.jobLabel.argv).not.toContain("stdin prompt"); + expect(openSpec.execution).toEqual( + expect.objectContaining({ + stdin: "pipe", + input: "stdin prompt" + }) + ); + }); + + it("runs configured middlewares around each command with the populated spawn context", async () => { + const run = vi.fn().mockResolvedValue({ + kind: "sync", + exitCode: 0, + stdout: "agent output", + stderr: "tool warning" + }); + resolvePoeCommandExecutionMock.mockReturnValue({ + factory: { type: "host" }, + state: { jobs: {} }, + detach: false, + openSpec: createBaseOpenSpec() + }); + createPoeCommandSessionMock.mockReturnValue({ + run, + syncBack: vi.fn(), + close: vi.fn() + }); + + const calls: string[] = []; + const middleware: AcpMiddleware = vi.fn(async (ctx, next) => { + calls.push(`before:${ctx.agent}:${ctx.model}:${ctx.prompt}`); + await next(); + calls.push(`after:${ctx.sessionResult?.output}:${ctx.events.length}`); + }); + const session = createSpawnSession({ + service: "claude-code", + model: "base-model", + middlewares: [middleware] + }); + + await session.run({ + agent: "codex", + prompt: "fix bug", + model: "gpt-5" + }); + + expect(middleware).toHaveBeenCalledTimes(1); + expect(calls).toEqual(["before:codex:gpt-5:fix bug", "after:agent output:2"]); + expect(middleware).toHaveBeenCalledWith( + expect.objectContaining({ + sessionId: "spawn-session", + agent: "codex", + prompt: "fix bug", + model: "gpt-5", + cwd: expect.any(String), + sessionResult: { + output: "agent output", + messages: ["agent output"], + toolCalls: [] + }, + events: [ + { event: "agent_message", text: "agent output" }, + { event: "error", message: "tool warning" } + ] + }), + expect.any(Function) + ); + }); + + it("can run a command in streaming mode while reusing the command session", async () => { + const run = vi.fn(async (openSpec: OpenSpec) => { + openSpec.execution?.onStdout?.( + `${JSON.stringify({ + type: "item.completed", + item: { type: "agent_message", text: "streamed output" } + })}\n` + ); + openSpec.execution?.onStderr?.("warning\n"); + return { + kind: "sync", + exitCode: 0, + stdout: "captured stdout", + stderr: "warning\n" + }; + }); + resolvePoeCommandExecutionMock.mockReturnValue({ + factory: { type: "host" }, + state: { jobs: {} }, + detach: false, + openSpec: createBaseOpenSpec() + }); + createPoeCommandSessionMock.mockReturnValue({ + run, + syncBack: vi.fn(), + close: vi.fn() + }); + + const stderrChunks: string[] = []; + const session = createSpawnSession({ + service: "codex", + tee: { + stderr: { + write(chunk: string) { + stderrChunks.push(chunk); + } + } + } + }); + + const { events, result } = session.run( + { + prompt: "fix bug", + syncBack: false + }, + { streaming: true } + ); + + await expect(Promise.all([collect(events), result])).resolves.toEqual([ + [{ event: "agent_message", text: "streamed output" }], + expect.objectContaining({ stdout: "captured stdout", stderr: "warning\n", exitCode: 0 }) + ]); + expect(run).toHaveBeenCalledWith(expect.any(Object), undefined, { syncBack: false }); + expect(stderrChunks).toEqual(["warning\n"]); + }); +}); + +async function collect(events: AsyncIterable): Promise { + const collected: T[] = []; + for await (const event of events) { + collected.push(event); + } + return collected; +} + +function createBaseOpenSpec(onProgress?: OpenSpec["onProgress"]): OpenSpec { + return { + cwd: "/repo", + runtimeCwd: "/config", + runtime: { type: "host", mounts: [] }, + runner: { + detach: false, + sync: "both", + workspace: { exclude: ["node_modules"] }, + upload_max_file_mb: 100, + download_conflict: "refuse" + }, + state: undefined, + env: { BASE: "1" }, + uploadIgnoreFiles: [], + jobLabel: { + tool: "claude-code", + argv: ["claude", "-p", ""] + }, + ...(onProgress ? { onProgress } : {}), + execution: { + stdout: "pipe", + stderr: "pipe", + captureOutput: true + } + }; +} diff --git a/packages/agent-spawn/src/spawn-session.ts b/packages/agent-spawn/src/spawn-session.ts new file mode 100644 index 0000000000..079f3b6d21 --- /dev/null +++ b/packages/agent-spawn/src/spawn-session.ts @@ -0,0 +1,566 @@ +import "./register-factories.js"; +import { + createPoeCommandSession, + resolvePoeCommandExecution, + type DownloadResult, + type OpenSpec +} from "@poe-code/agent-harness-tools"; +import type { StateManager } from "@poe-code/poe-code-config"; +import type { AcpMiddleware, SpawnContext } from "./acp/middleware.js"; +import { applyMiddlewares } from "./acp/middleware.js"; +import { sessionCapture } from "./acp/middlewares/session-capture.js"; +import { spawnLog } from "./acp/middlewares/spawn-log.js"; +import { usageCapture } from "./acp/middlewares/usage-capture.js"; +import type { AcpEvent } from "./acp/types.js"; +import { getAdapter } from "./adapters/index.js"; +import { resolveConfig } from "./configs/resolve-config.js"; +import { buildSpawnArgs } from "./spawn.js"; +import type { McpSpawnConfig, SpawnMode, SpawnOptions, SpawnResult } from "./types.js"; + +export interface CreateSpawnSessionOptions { + service: string; + cwd?: string; + model?: string; + mode?: SpawnMode; + args?: string[]; + mcpServers?: McpSpawnConfig; + useStdin?: boolean; + signal?: AbortSignal; + tee?: SpawnOptions["tee"]; + activityTimeoutMs?: number; + runtime?: SpawnOptions["runtime"]; + runtimeImage?: string; + runtimeTemplate?: string; + runtimeConfigCwd?: string; + detach?: boolean; + mountPoeCode?: boolean; + runnerSync?: SpawnOptions["runnerSync"]; + downloadConflict?: NonNullable["download_conflict"]; + onProgress?: SpawnOptions["onProgress"]; + middlewares?: AcpMiddleware[]; + context?: { + homeDir?: string; + state?: StateManager; + }; +} + +export interface SpawnSessionRunInput { + prompt: string; + agent?: string; + model?: string; + mode?: SpawnMode; + cwd?: string; + logDir?: string; + logFileName?: string; + mcpServers?: McpSpawnConfig; + signal?: AbortSignal; + syncBack?: boolean; +} + +export interface SpawnSessionRunStreamingResult { + events: AsyncIterable; + result: Promise; +} + +export interface SpawnSession { + run(input: SpawnSessionRunInput, options: { streaming: true }): SpawnSessionRunStreamingResult; + run(input: SpawnSessionRunInput): Promise; + syncBack(): Promise; + close(): Promise; +} + +export function createSpawnSession(options: CreateSpawnSessionOptions): SpawnSession { + if (options.detach === true) { + throw new Error( + "createSpawnSession does not support detach: true. Use plain spawn(...) instead." + ); + } + + const baseCwd = options.cwd ?? process.cwd(); + const baseSpawnArgs = buildSpawnArgs(options.service, { + prompt: "", + model: options.model, + mode: options.mode, + args: options.args, + mcpServers: options.mcpServers, + useStdin: options.useStdin + }); + const baseProcessEnv = resolveProcessEnv(baseSpawnArgs.env); + const execution = resolvePoeCommandExecution({ + cwd: baseCwd, + runtimeConfigCwd: options.runtimeConfigCwd, + env: baseProcessEnv, + argv: [baseSpawnArgs.binaryName, ...baseSpawnArgs.args], + tool: options.service, + runtime: { + runtime: options.runtime, + runtimeImage: options.runtimeImage, + runtimeTemplate: options.runtimeTemplate, + detach: false, + mountPoeCode: options.mountPoeCode, + runnerSync: options.runnerSync + }, + context: options.context, + openSpec: { + ...(options.onProgress ? { onProgress: options.onProgress } : {}), + execution: buildExecutionSpec({ + prompt: "", + processEnv: baseProcessEnv, + useStdin: options.useStdin, + tee: options.tee, + activityTimeoutMs: options.activityTimeoutMs + }) + } + }); + const session = createPoeCommandSession({ + factory: execution.factory, + state: execution.state + }); + + const run: SpawnSession["run"] = ((input, runOptions?: { streaming?: boolean }) => { + if (runOptions?.streaming) { + return runStreaming(input); + } + + return runCompleted(input); + }) as SpawnSession["run"]; + + return { + run, + async syncBack() { + return await session.syncBack(); + }, + async close() { + await session.close(); + } + }; + + function runStreaming(input: SpawnSessionRunInput): SpawnSessionRunStreamingResult { + const streaming = createStreamingRunState({ + agent: input.agent ?? options.service, + input, + baseCwd, + defaultModel: options.model, + defaultMode: options.mode, + middlewares: options.middlewares + }); + + return { + events: streaming.events, + result: runCompleted(input, streaming) + }; + } + + async function runCompleted( + input: SpawnSessionRunInput, + streaming?: StreamingRunState + ): Promise { + const agent = input.agent ?? options.service; + const prompt = input.prompt; + const spawnArgs = buildSpawnArgs(agent, { + prompt, + model: input.model ?? options.model, + mode: input.mode ?? options.mode, + args: options.args, + mcpServers: input.mcpServers ?? options.mcpServers, + useStdin: options.useStdin + }); + const processEnv = resolveProcessEnv(spawnArgs.env); + const openSpec = mergeOpenSpec(execution.openSpec, { + cwd: input.cwd ?? baseCwd, + env: processEnv, + jobLabel: { + tool: agent, + argv: [spawnArgs.binaryName, ...spawnArgs.args] + }, + ...(options.onProgress ? { onProgress: options.onProgress } : {}), + ...(options.downloadConflict + ? { runner: { download_conflict: options.downloadConflict } } + : {}), + execution: buildExecutionSpec({ + prompt, + processEnv, + useStdin: options.useStdin, + tee: options.tee, + activityTimeoutMs: options.activityTimeoutMs, + ...(streaming ? { streaming } : {}) + }) + }); + const runCommand = async () => + await session.run(openSpec, input.signal ?? options.signal, { + syncBack: input.syncBack + }); + const result = await (async () => { + try { + return streaming + ? await runCommand() + : options.middlewares && options.middlewares.length > 0 + ? await runWithMiddlewares(options.middlewares, { + agent, + prompt, + model: input.model ?? options.model, + mode: input.mode ?? options.mode, + cwd: input.cwd ?? baseCwd, + logDir: input.logDir, + logFileName: input.logFileName, + run: runCommand + }) + : await runCommand(); + } finally { + streaming?.close(); + } + })(); + + const usage = getCapturedUsage(streaming?.context.usage); + return { + stdout: result.stdout ?? "", + stderr: result.stderr ?? "", + exitCode: result.exitCode, + ...(streaming?.context.threadId ? { threadId: streaming.context.threadId } : {}), + ...(usage ? { usage } : {}), + ...(streaming?.context.logFile ? { logFile: streaming.context.logFile } : {}) + }; + } +} + +type StreamingRunState = { + events: AsyncIterable; + context: SpawnContext; + onStdout(chunk: string): void; + close(): void; + suppressStdoutTee: boolean; +}; + +function createStreamingRunState(input: { + agent: string; + input: SpawnSessionRunInput; + baseCwd: string; + defaultModel?: string; + defaultMode?: SpawnMode; + middlewares?: AcpMiddleware[]; +}): StreamingRunState { + const queue = createLineQueue(); + const adapter = resolveStreamingAdapter(input.agent); + const rawEvents = adapter + ? filterAcpEvents(adapter(queue.lines())) + : (async function* (): AsyncIterable {})(); + const context: SpawnContext = { + sessionId: "spawn-session", + agent: input.agent, + events: [], + usage: { + inputTokens: 0, + outputTokens: 0 + }, + eventStream: rawEvents, + prompt: input.input.prompt, + cwd: input.input.cwd ?? input.baseCwd, + ...((input.input.model ?? input.defaultModel) + ? { model: input.input.model ?? input.defaultModel } + : {}), + ...((input.input.mode ?? input.defaultMode) + ? { mode: input.input.mode ?? input.defaultMode } + : {}), + ...(input.input.logDir ? { logDir: input.input.logDir } : {}), + ...(input.input.logFileName ? { logFileName: input.input.logFileName } : {}), + startedAt: new Date() + }; + const eventsPromise = (async (): Promise> => { + await applyMiddlewares( + [sessionCapture, usageCapture, spawnLog, ...(input.middlewares ?? [])], + context + ); + return context.eventStream ?? (async function* (): AsyncIterable {})(); + })(); + + return { + context, + suppressStdoutTee: adapter !== undefined, + onStdout(chunk) { + queue.push(chunk); + }, + close() { + queue.close(); + }, + events: (async function* () { + for await (const event of await eventsPromise) { + yield event; + } + })() + }; +} + +function resolveStreamingAdapter( + agent: string +): ((lines: AsyncIterable) => AsyncIterable) | undefined { + const { spawnConfig } = resolveConfig(agent); + if ( + !spawnConfig || + spawnConfig.kind !== "cli" || + typeof (spawnConfig as { adapter?: unknown }).adapter !== "string" + ) { + return undefined; + } + + return (lines) => + filterAcpEvents( + getAdapter((spawnConfig as { adapter: Parameters[0] }).adapter)(lines) + ); +} + +function isAcpEvent(value: unknown): value is AcpEvent { + return !!value && typeof value === "object" && "event" in value; +} + +async function* filterAcpEvents(source: AsyncIterable): AsyncIterable { + for await (const event of source) { + if (isAcpEvent(event)) { + yield event; + } + } +} + +async function runWithMiddlewares( + middlewares: AcpMiddleware[], + input: { + agent: string; + prompt: string; + model?: string; + mode?: SpawnMode; + cwd: string; + logDir?: string; + logFileName?: string; + run(): Promise<{ + kind: "sync"; + exitCode: number; + download?: DownloadResult; + stdout?: string; + stderr?: string; + }>; + } +): Promise<{ + kind: "sync"; + exitCode: number; + download?: DownloadResult; + stdout?: string; + stderr?: string; +}> { + let result: + | { + kind: "sync"; + exitCode: number; + download?: DownloadResult; + stdout?: string; + stderr?: string; + } + | undefined; + const ctx: SpawnContext = { + sessionId: "spawn-session", + agent: input.agent, + events: [], + usage: { + inputTokens: 0, + outputTokens: 0 + }, + prompt: input.prompt, + cwd: input.cwd, + ...(input.logDir ? { logDir: input.logDir } : {}), + ...(input.logFileName ? { logFileName: input.logFileName } : {}), + ...(input.model ? { model: input.model } : {}), + ...(input.mode ? { mode: input.mode } : {}), + startedAt: new Date() + }; + + await runAcpMiddlewares(middlewares, ctx, async () => { + result = await input.run(); + const stdout = result.stdout ?? ""; + const stderr = result.stderr ?? ""; + + if (stdout.length > 0) { + ctx.events.push({ event: "agent_message", text: stdout }); + } + if (stderr.length > 0) { + ctx.events.push({ event: "error", message: stderr }); + } + + ctx.sessionResult = { + output: stdout, + messages: stdout.length > 0 ? [stdout] : [], + toolCalls: [] + }; + }); + + if (!result) { + throw new Error("Spawn session middleware did not run the command."); + } + + return result; +} + +async function runAcpMiddlewares( + middlewares: AcpMiddleware[], + ctx: SpawnContext, + runCommand: () => Promise +): Promise { + let index = -1; + + async function dispatch(position: number): Promise { + if (position <= index) { + throw new Error("next() called multiple times"); + } + + index = position; + if (position === middlewares.length) { + await runCommand(); + return; + } + + const middleware = middlewares[position]; + if (typeof middleware !== "function") { + throw new Error(`Invalid ACP middleware at index ${position}`); + } + + await middleware(ctx, () => dispatch(position + 1)); + } + + await dispatch(0); +} + +function resolveProcessEnv(env: Record | undefined): Record { + const baseEnv = process.env as Record; + return env ? { ...baseEnv, ...env } : baseEnv; +} + +function buildExecutionSpec(input: { + prompt: string; + processEnv: Record; + useStdin?: boolean; + tee?: SpawnOptions["tee"]; + activityTimeoutMs?: number; + streaming?: StreamingRunState; +}): NonNullable { + return { + wrapForLogTee: false, + stdin: input.useStdin ? "pipe" : "inherit", + stdout: "pipe", + stderr: "pipe", + env: input.processEnv, + input: input.useStdin ? input.prompt : undefined, + captureOutput: true, + activityTimeoutMs: input.activityTimeoutMs, + onStdout(chunk: string) { + input.streaming?.onStdout(chunk); + if (!input.streaming?.suppressStdoutTee) { + input.tee?.stdout?.write(chunk); + } + }, + onStderr(chunk: string) { + input.tee?.stderr?.write(chunk); + } + }; +} + +function getCapturedUsage( + usage: SpawnResult["usage"] | undefined +): SpawnResult["usage"] | undefined { + if (!usage) { + return undefined; + } + + if (usage.inputTokens > 0 || usage.outputTokens > 0) { + return usage; + } + + if (usage.cachedTokens !== undefined || usage.costUsd !== undefined) { + return usage; + } + + return undefined; +} + +function createLineQueue(): { + push(chunk: string): void; + close(): void; + lines(): AsyncIterable; +} { + const lines: string[] = []; + const waiters: Array<{ resolve(value: IteratorResult): void }> = []; + let pending = ""; + let closed = false; + + const emit = (line: string): void => { + const waiter = waiters.shift(); + if (waiter) { + waiter.resolve({ done: false, value: line }); + return; + } + lines.push(line); + }; + + return { + push(chunk) { + if (closed) return; + pending += chunk; + let newlineIndex = pending.indexOf("\n"); + while (newlineIndex !== -1) { + const raw = pending.slice(0, newlineIndex); + emit(raw.endsWith("\r") ? raw.slice(0, -1) : raw); + pending = pending.slice(newlineIndex + 1); + newlineIndex = pending.indexOf("\n"); + } + }, + close() { + if (closed) return; + if (pending.length > 0) { + emit(pending.endsWith("\r") ? pending.slice(0, -1) : pending); + pending = ""; + } + closed = true; + while (waiters.length > 0) { + waiters.shift()!.resolve({ done: true, value: undefined }); + } + }, + lines() { + return { + [Symbol.asyncIterator](): AsyncIterator { + return { + next(): Promise> { + if (lines.length > 0) { + return Promise.resolve({ done: false, value: lines.shift()! }); + } + if (closed) { + return Promise.resolve({ done: true, value: undefined }); + } + return new Promise((resolve) => { + waiters.push({ resolve }); + }); + } + }; + } + }; + } + }; +} + +function mergeOpenSpec(base: OpenSpec, override: Record): OpenSpec { + return deepMerge(base, override) as OpenSpec; +} + +function deepMerge(base: unknown, override: unknown): unknown { + if (override === undefined) { + return base; + } + if (!isPlainObject(base) || !isPlainObject(override)) { + return override; + } + + const merged: Record = { ...base }; + for (const [key, value] of Object.entries(override)) { + merged[key] = deepMerge(merged[key], value); + } + return merged; +} + +function isPlainObject(value: unknown): value is Record { + return Boolean(value && typeof value === "object" && !Array.isArray(value)); +} diff --git a/packages/experiment-loop/README.md b/packages/experiment-loop/README.md index c912c2eae8..2ee0767fe8 100644 --- a/packages/experiment-loop/README.md +++ b/packages/experiment-loop/README.md @@ -102,6 +102,12 @@ measure baseline -> loop: The agent learns from past attempts through the journal — it sees what worked and what didn't. +### Runtime Sessions + +`experiment run` opens one sandbox session at the start of the experiment run and reuses it across experiments. Unlike other long-lived runtime sessions, experiment-loop intentionally round-trips the workspace on every iteration. + +The loop runs git operations on the host workspace between iterations: it reads the current hash, resets discarded experiments, and records journal entries keyed by commits. Each iteration syncs agent changes back before those host git steps run, then uploads the host workspace state before the next agent turn so the sandbox stays aligned with kept or discarded changes. + ## Custom Experiment Directory By default experiment docs are discovered from `.poe-code/experiments/`. To use a different directory: diff --git a/packages/pipeline/README.md b/packages/pipeline/README.md index 0c5ea4815d..ca87f1d95c 100644 --- a/packages/pipeline/README.md +++ b/packages/pipeline/README.md @@ -141,6 +141,10 @@ Stop conditions: all work complete, a task/step fails, cancellation, or `maxRuns A failed task or step blocks all later tasks. +### Runtime Sessions + +`pipeline run` opens one sandbox session at the start of the run and reuses it for every setup hook, task step, and teardown hook. The workspace is uploaded once before the first execution, then synced back to the host when the run finishes or aborts. + ### Cancellation No intermediate status is written before spawn. If an execution is aborted, the task stays at its prior status and the lock is released. diff --git a/packages/ralph/README.md b/packages/ralph/README.md index 8834a03b04..fcbb296efd 100644 --- a/packages/ralph/README.md +++ b/packages/ralph/README.md @@ -94,9 +94,11 @@ POE_RALPH_PLAN_DIRECTORY=docs/plans poe-code ralph run poe-code ralph run docs/plans/refactor-auth.md ``` -## Runtime Workspaces +## Runtime Sessions -When validating Ralph against a remote runtime such as E2B, create a fresh temporary workspace with `mkdtemp`, put only the Ralph plan and intended test files in that directory, pass the plan path directly, and run with `--cwd `. Do not aim Ralph runtime tests at the poe-code checkout or a parent repository; Ralph agents are expected to edit their working directory across iterations, and remote runtime downloads overwrite the tmpdir copy after each iteration so the next iteration sees the prior edits. +`ralph run` opens one sandbox session at the start of the run and reuses it for every iteration. The workspace is uploaded once before the first iteration, then synced back to the host when the run finishes or aborts. + +`--detach` is incompatible with runtime sessions. Detached runs fall back to the one-shot spawn path instead of opening a shared session. ## Dashboard Configuration diff --git a/packages/ralph/src/ralph.test.ts b/packages/ralph/src/ralph.test.ts index 200eb145a7..753c2ee963 100644 --- a/packages/ralph/src/ralph.test.ts +++ b/packages/ralph/src/ralph.test.ts @@ -796,6 +796,73 @@ describe("createRalphSimulation", () => { expect(body).toBe("# Archive me"); }); + it("prepares the final workspace before completed status and archive writes", async () => { + const { fs, rawFs } = createRunFs({ + "/repo/.poe-code/ralph/plans/plan.md": "# Original" + }); + const prepareFinalWorkspace = vi.fn(async () => { + await fs.writeFile("/repo/.poe-code/ralph/plans/plan.md", "# Synced body"); + }); + + await runRalph({ + cwd: "/repo", + homeDir: "/home/test", + docPath: ".poe-code/ralph/plans/plan.md", + maxIterations: 1, + fs, + prepareFinalWorkspace, + runAgent: async () => ({ + stdout: "", + stderr: "", + exitCode: 0 + }) + }); + + expect(prepareFinalWorkspace).toHaveBeenCalledTimes(1); + const archived = await rawFs.readFile( + "/repo/.poe-code/ralph/plans/archive/plan.md", + "utf8" + ); + const { data, body } = parseFrontmatter(archived as string); + expect(data.status).toEqual({ + state: "completed", + iteration: 1 + }); + expect(body).toBe("# Synced body"); + }); + + it("prepares the final workspace before fatal-error open status writes", async () => { + const { fs, rawFs } = createRunFs({ + "/repo/.poe-code/ralph/plans/plan.md": "# Original" + }); + const prepareFinalWorkspace = vi.fn(async () => { + await fs.writeFile("/repo/.poe-code/ralph/plans/plan.md", "# Synced body"); + }); + + await expect( + runRalph({ + cwd: "/repo", + homeDir: "/home/test", + docPath: ".poe-code/ralph/plans/plan.md", + maxIterations: 1, + fs, + prepareFinalWorkspace, + runAgent: async () => { + throw new Error("boom"); + } + }) + ).rejects.toThrow("boom"); + + expect(prepareFinalWorkspace).toHaveBeenCalledTimes(1); + const content = await rawFs.readFile("/repo/.poe-code/ralph/plans/plan.md", "utf8"); + const { data, body } = parseFrontmatter(content as string); + expect(data.status).toEqual({ + state: "open", + iteration: 0 + }); + expect(body).toBe("# Synced body"); + }); + it("writes open status on abort signal", async () => { const controller = new AbortController(); const sim = createRalphSimulation({ diff --git a/packages/ralph/src/run/ralph.ts b/packages/ralph/src/run/ralph.ts index 7d35e8c44f..5864b7075e 100644 --- a/packages/ralph/src/run/ralph.ts +++ b/packages/ralph/src/run/ralph.ts @@ -53,8 +53,10 @@ export async function runRalph(options: RalphRunOptions): Promise 0) { + await prepareFinalWorkspace(); await updateFrontmatter(fs, absoluteDocPath, "completed", iterationsCompleted); await archivePlanShared({ cwd: options.cwd, @@ -216,6 +225,7 @@ export async function runRalph(options: RalphRunOptions): Promise[0]["fs"]> }); } else if (stopReason === "cancelled" && !archived) { + await prepareFinalWorkspace(); await updateFrontmatter(fs, absoluteDocPath, "open", iterationsCompleted); } @@ -236,6 +246,21 @@ function createRunResult( }; } +function createPrepareFinalWorkspaceOnce( + prepareFinalWorkspace: RalphRunOptions["prepareFinalWorkspace"] +): () => Promise { + let prepared = false; + + return async () => { + if (prepared || prepareFinalWorkspace === undefined) { + return; + } + + prepared = true; + await prepareFinalWorkspace(); + }; +} + async function resolveDocumentConfigFromContent( options: RalphRunOptions, fs: RalphFileSystem, diff --git a/packages/ralph/src/types.ts b/packages/ralph/src/types.ts index e25d6d56e8..0412c23998 100644 --- a/packages/ralph/src/types.ts +++ b/packages/ralph/src/types.ts @@ -61,6 +61,7 @@ export interface RalphRunOptions { runnerSync?: "both" | "upload" | "none"; fs?: RalphFileSystem; runAgent?: (input: AgentRunInput) => Promise; + prepareFinalWorkspace?: () => Promise; onIterationStart?: (iteration: number, maxIterations: number, agent: string) => void; onIterationComplete?: (iteration: number, durationMs: number, success: boolean) => void; signal?: AbortSignal; diff --git a/packages/superintendent/README.md b/packages/superintendent/README.md index 6dd045e97e..1e1b722c0a 100644 --- a/packages/superintendent/README.md +++ b/packages/superintendent/README.md @@ -47,6 +47,10 @@ Behavior notes: - `builder run` executes only the builder role. - `inspector run` executes one named inspector, or all configured inspectors when `name` is omitted. +## Runtime Sessions + +`superintendent run` opens one sandbox session at the start of the run and reuses it for the whole workflow. Builder, inspector, superintendent, and owner roles all share that same sandbox. The workspace is uploaded once before the first role execution, then synced back to the host when the run finishes or aborts. + ## MCP tool names MCP server entrypoint: diff --git a/packages/superintendent/src/commands/builder-group.test.ts b/packages/superintendent/src/commands/builder-group.test.ts index b22a0e2358..d2a3c86f8e 100644 --- a/packages/superintendent/src/commands/builder-group.test.ts +++ b/packages/superintendent/src/commands/builder-group.test.ts @@ -74,7 +74,10 @@ describe("superintendent builder run", () => { filePath: path.resolve(targetPath) }), {}, - { defaultCwd: process.cwd() } + expect.objectContaining({ + defaultCwd: process.cwd(), + agentSession: expect.any(Object) + }) ); expect(result).toEqual({ summary: "Implemented builder run", @@ -110,10 +113,12 @@ describe("superintendent builder run", () => { it("renders markdown output with summary and log sections", async () => { const { builderRunCommand } = await import("./builder-group.js"); - expect(builderRunCommand.render.markdown?.({ - summary: "Implemented builder run", - log: "Implemented builder run\nUpdated tests" - })).toBe( + expect( + builderRunCommand.render.markdown?.({ + summary: "Implemented builder run", + log: "Implemented builder run\nUpdated tests" + }) + ).toBe( [ "## Builder result", "", diff --git a/packages/superintendent/src/commands/builder-group.ts b/packages/superintendent/src/commands/builder-group.ts index 0679830cbd..305df392e9 100644 --- a/packages/superintendent/src/commands/builder-group.ts +++ b/packages/superintendent/src/commands/builder-group.ts @@ -1,6 +1,10 @@ import { S, UserError, defineCommand, defineGroup } from "toolcraft"; import { text } from "@poe-code/design-system"; import { parseSuperintendentDoc } from "../document/parse.js"; +import { + createSuperintendentAgentSession, + finalizeAgentRunnerSession +} from "../runtime/agent-runner-session.js"; import { runBuilder, type BuilderResult } from "../runtime/run-builder.js"; export type BuilderGroupRunners = { @@ -23,8 +27,22 @@ export function createBuilderRunCommand(runners?: BuilderGroupRunners) { handler: async ({ params, fs }) => { const content = await readDocument(params.path, fs); const document = parseSuperintendentDoc(params.path, content); + const session = createSuperintendentAgentSession({ + homeDir: process.env.HOME ?? process.env.USERPROFILE ?? process.cwd() + }); - return runBuilderImpl(document, {}, { defaultCwd: process.cwd() }); + try { + return await runBuilderImpl( + document, + {}, + { + defaultCwd: process.cwd(), + agentSession: session + } + ); + } finally { + await finalizeAgentRunnerSession(session); + } }, render: { rich: (result, { logger }) => { diff --git a/packages/superintendent/src/commands/inspector-group.test.ts b/packages/superintendent/src/commands/inspector-group.test.ts index 20b008d701..62dc4f979a 100644 --- a/packages/superintendent/src/commands/inspector-group.test.ts +++ b/packages/superintendent/src/commands/inspector-group.test.ts @@ -109,7 +109,10 @@ describe("superintendent inspector commands", () => { expect(runAllInspectorsMock).toHaveBeenCalledWith( expect.objectContaining({ filePath: path.resolve(targetPath) }), {}, - { defaultCwd: process.cwd() } + expect.objectContaining({ + defaultCwd: process.cwd(), + agentSession: expect.any(Object) + }) ); expect(result).toEqual([ { name: "code-quality", summary: "quality-ok" }, @@ -149,7 +152,10 @@ describe("superintendent inspector commands", () => { }), expect.objectContaining({ filePath: path.resolve(targetPath) }), {}, - { defaultCwd: process.cwd() } + expect.objectContaining({ + defaultCwd: process.cwd(), + agentSession: expect.any(Object) + }) ); expect(result).toEqual([{ name: "manual-qa", summary: "qa-ok" }]); }); @@ -172,7 +178,7 @@ describe("superintendent inspector commands", () => { }, progress: vi.fn() }) - ).rejects.toThrow('Inspector not found: missing'); + ).rejects.toThrow("Inspector not found: missing"); }); it("renders a friendly rich empty state when listing no inspectors", async () => { diff --git a/packages/superintendent/src/commands/inspector-group.ts b/packages/superintendent/src/commands/inspector-group.ts index 4cfa257f42..03644b2033 100644 --- a/packages/superintendent/src/commands/inspector-group.ts +++ b/packages/superintendent/src/commands/inspector-group.ts @@ -1,10 +1,10 @@ import { S, UserError, defineCommand, defineGroup } from "toolcraft"; import { parseSuperintendentDoc } from "../document/parse.js"; import { - runAllInspectors, - runInspector, - type InspectorResult -} from "../runtime/run-inspector.js"; + createSuperintendentAgentSession, + finalizeAgentRunnerSession +} from "../runtime/agent-runner-session.js"; +import { runAllInspectors, runInspector, type InspectorResult } from "../runtime/run-inspector.js"; export type InspectorListItem = { name: string; @@ -85,18 +85,36 @@ export function createInspectorRunCommand(runners?: InspectorGroupRunners) { const document = parseSuperintendentDoc(params.path, content); const defaultCwd = process.cwd(); + const session = createSuperintendentAgentSession({ + homeDir: process.env.HOME ?? process.env.USERPROFILE ?? defaultCwd + }); - if (params.name === undefined) { - return runAllInspectorsImpl(document, {}, { defaultCwd }); - } + try { + if (params.name === undefined) { + return await runAllInspectorsImpl(document, {}, { defaultCwd, agentSession: session }); + } - const config = document.frontmatter.inspectors?.[params.name]; + const config = document.frontmatter.inspectors?.[params.name]; - if (config === undefined) { - throw new UserError(`Inspector not found: ${params.name}`); - } + if (config === undefined) { + throw new UserError(`Inspector not found: ${params.name}`); + } - return [await runInspectorImpl(params.name, config, document, {}, { defaultCwd })]; + return [ + await runInspectorImpl( + params.name, + config, + document, + {}, + { + defaultCwd, + agentSession: session + } + ) + ]; + } finally { + await finalizeAgentRunnerSession(session); + } }, render: { rich: (result, { logger }) => { @@ -105,7 +123,9 @@ export function createInspectorRunCommand(runners?: InspectorGroupRunners) { return; } - logger.success(`Completed ${result.length} inspector run${result.length === 1 ? "" : "s"}.`); + logger.success( + `Completed ${result.length} inspector run${result.length === 1 ? "" : "s"}.` + ); for (const inspector of result) { logger.message(`${inspector.name}: ${inspector.summary || "(no output)"}`); @@ -154,7 +174,9 @@ function renderInspectorListMarkdown(result: InspectorListItem[]): string { } for (const inspector of result) { - lines.push(`- ${inspector.name} (${inspector.agent}${inspector.mode ? `, ${inspector.mode}` : ""})`); + lines.push( + `- ${inspector.name} (${inspector.agent}${inspector.mode ? `, ${inspector.mode}` : ""})` + ); } return lines.join("\n"); diff --git a/packages/superintendent/src/commands/run.ts b/packages/superintendent/src/commands/run.ts index d11e8236ca..171192ef2f 100644 --- a/packages/superintendent/src/commands/run.ts +++ b/packages/superintendent/src/commands/run.ts @@ -6,6 +6,7 @@ import { resolveLoopAgent, resolveRunLogDir, resolveWorkflowPath, + type AgentRunnerSession, type RuntimeOverrideOptions } from "@poe-code/agent-harness-tools"; import { @@ -46,6 +47,7 @@ import { } from "@poe-code/poe-code-config"; import { superintendentConfigScope } from "../config-scope.js"; import { parseSuperintendentDoc, readExplicitBuilderAgent } from "../document/parse.js"; +import { createSuperintendentAgentSession } from "../runtime/agent-runner-session.js"; import { runLoop, type AgentRunInput, @@ -103,6 +105,7 @@ export type RunCommandOptions = { stderr?: NodeJS.WritableStream; exit?: (code: number) => never; integrations?: Integrations | null; + agentSession?: AgentRunnerSession; }; type OutputKind = "info" | "success" | "error" | "tool" | "status"; @@ -133,23 +136,33 @@ const coreDefaultAgentConfigSchema = { const runParams = S.Object({ doc: S.Optional(S.String({ description: "Path to the superintendent markdown document" })), - agent: S.Optional(S.String({ - description: - "Override the builder agent for this run. Precedence: --agent > plan frontmatter builder.agent." - })), - runtime: S.Optional(S.Enum(["host", "docker", "e2b"] as const, { - description: "Override runtime backend: host, docker, or e2b" - })), + agent: S.Optional( + S.String({ + description: + "Override the builder agent for this run. Precedence: --agent > plan frontmatter builder.agent." + }) + ), + runtime: S.Optional( + S.Enum(["host", "docker", "e2b"] as const, { + description: "Override runtime backend: host, docker, or e2b" + }) + ), runtimeImage: S.Optional(S.String({ description: "Override Docker runtime image" })), runtimeTemplate: S.Optional(S.String({ description: "Override E2B runtime template id" })), detach: S.Optional(S.Boolean({ description: "Run as a detached runtime job" })), - mountPoeCode: S.Optional(S.Boolean({ - description: "Mount the local poe-code checkout into the runtime" - })), - runnerSync: S.Optional(S.Enum(["both", "upload", "none"] as const, { - description: "Override runner workspace sync: both, upload, or none" - })), - tui: S.Optional(S.Boolean({ description: "Show a live dashboard while Superintendent is running" })) + mountPoeCode: S.Optional( + S.Boolean({ + description: "Mount the local poe-code checkout into the runtime" + }) + ), + runnerSync: S.Optional( + S.Enum(["both", "upload", "none"] as const, { + description: "Override runner workspace sync: both, upload, or none" + }) + ), + tui: S.Optional( + S.Boolean({ description: "Show a live dashboard while Superintendent is running" }) + ) }); export const runCommand = defineCommand({ @@ -180,7 +193,8 @@ export const runCommand = defineCommand({ configuredDefaultAgent: commandConfig.configuredDefaultAgent, assumeYes: process.argv.includes("--yes"), interactive: Boolean(process.stdin.isTTY), - useDashboard: shouldUseInteractiveDashboard(tuiEnabled) && resolveOutputFormat() === "terminal", + useDashboard: + shouldUseInteractiveDashboard(tuiEnabled) && resolveOutputFormat() === "terminal", env: process.env, integrations, ...(commandConfig.planDirectory ? { planDirectory: commandConfig.planDirectory } : {}) @@ -295,7 +309,11 @@ async function resolveSuperintendentCommandConfig( configPath, projectConfigPath ); - const planDirectory = resolveScope(planConfigScope.schema, document.plan, env).plan_directory?.trim(); + const planDirectory = resolveScope( + planConfigScope.schema, + document.plan, + env + ).plan_directory?.trim(); const superintendentResolved = resolveScope( superintendentConfigScope.schema, document[superintendentConfigScope.scope], @@ -387,6 +405,7 @@ export async function runSuperintendentCommand( const stderr = options.stderr ?? process.stderr; const exitProcess = options.exit ?? ((code: number) => process.exit(code)); const integrations = options.integrations ?? null; + const useInjectedAgentRunner = Boolean(options.executeAgent || options.detach || options.runLoop); const shutdownAndExit = (code: number): void => { if (!integrations) { exitProcess(code); @@ -451,55 +470,76 @@ export async function runSuperintendentCommand( ...(options.fs ? { fs } : {}), signal: headlessAbort.signal, logDir: runLogDir, - callbacks: mergeLoopCallbacks({ - onBuilderStart: () => { - activeStage = "builder"; - }, - onBuilderComplete: () => { - activeStage = undefined; - }, - onBuilderFailed: () => { - activeStage = undefined; - }, - onInspectorStart: (name) => { - activeStage = { inspector: name }; - }, - onInspectorComplete: () => { - activeStage = undefined; - }, - onInspectorFailed: () => { - activeStage = undefined; - }, - onSuperintendentStart: () => { - activeStage = "superintendent"; - }, - onSuperintendentComplete: () => { - activeStage = undefined; + callbacks: mergeLoopCallbacks( + { + onBuilderStart: () => { + activeStage = "builder"; + }, + onBuilderComplete: () => { + activeStage = undefined; + }, + onBuilderFailed: () => { + activeStage = undefined; + }, + onInspectorStart: (name) => { + activeStage = { inspector: name }; + }, + onInspectorComplete: () => { + activeStage = undefined; + }, + onInspectorFailed: () => { + activeStage = undefined; + }, + onSuperintendentStart: () => { + activeStage = "superintendent"; + }, + onSuperintendentComplete: () => { + activeStage = undefined; + }, + onOwnerStart: () => { + activeStage = "owner"; + }, + onOwnerComplete: () => { + activeStage = undefined; + } }, - onOwnerStart: () => { - activeStage = "owner"; - }, - onOwnerComplete: () => { - activeStage = undefined; - } - }, integrations?.superintendentCallbacks), - runAgent: createAgentRunner({ - session: undefined, - executeAgent: options.executeAgent, - selectedBuilderAgent, - integrations, - runtime: { - runtime: options.runtime, - runtimeImage: options.runtimeImage, - runtimeTemplate: options.runtimeTemplate, - detach: options.detach, - mountPoeCode: options.mountPoeCode, - runnerSync: options.runnerSync - }, - activeStage: () => activeStage, - now, - stderr - }) + integrations?.superintendentCallbacks + ), + ...(useInjectedAgentRunner + ? { + runAgent: createAgentRunner({ + session: undefined, + executeAgent: options.executeAgent, + selectedBuilderAgent, + integrations, + runtime: { + runtime: options.runtime, + runtimeImage: options.runtimeImage, + runtimeTemplate: options.runtimeTemplate, + detach: options.detach, + mountPoeCode: options.mountPoeCode, + runnerSync: options.runnerSync + }, + activeStage: () => activeStage, + now, + stderr + }) + } + : { + agentSession: + options.agentSession ?? + createSuperintendentAgentSession({ + homeDir: options.homeDir, + runtime: { + runtime: options.runtime, + runtimeImage: options.runtimeImage, + runtimeTemplate: options.runtimeTemplate, + detach: false, + mountPoeCode: options.mountPoeCode, + runnerSync: options.runnerSync + } + }) + }) }); return { @@ -754,23 +794,41 @@ export async function runSuperintendentCommand( callbacks: mergeLoopCallbacks(callbacks, integrations?.superintendentCallbacks), signal: abortController.signal, logDir: runLogDir, - runAgent: createAgentRunner({ - session, - executeAgent: options.executeAgent, - selectedBuilderAgent, - integrations, - runtime: { - runtime: options.runtime, - runtimeImage: options.runtimeImage, - runtimeTemplate: options.runtimeTemplate, - detach: options.detach, - mountPoeCode: options.mountPoeCode, - runnerSync: options.runnerSync - }, - activeStage: () => session.activeStage, - now, - stderr - }) + ...(useInjectedAgentRunner + ? { + runAgent: createAgentRunner({ + session, + executeAgent: options.executeAgent, + selectedBuilderAgent, + integrations, + runtime: { + runtime: options.runtime, + runtimeImage: options.runtimeImage, + runtimeTemplate: options.runtimeTemplate, + detach: options.detach, + mountPoeCode: options.mountPoeCode, + runnerSync: options.runnerSync + }, + activeStage: () => session.activeStage, + now, + stderr + }) + } + : { + agentSession: + options.agentSession ?? + createSuperintendentAgentSession({ + homeDir: options.homeDir, + runtime: { + runtime: options.runtime, + runtimeImage: options.runtimeImage, + runtimeTemplate: options.runtimeTemplate, + detach: false, + mountPoeCode: options.mountPoeCode, + runnerSync: options.runnerSync + } + }) + }) }); session.state = stripStopReason(result); @@ -907,7 +965,8 @@ function createAgentRunner(options: { return async (input) => { const activeStage = options.activeStage(); const agent = activeStage === "builder" ? options.selectedBuilderAgent : input.agent; - const executeAgent = options.executeAgent ?? + const executeAgent = + options.executeAgent ?? ((nextAgent: string, nextInput: AgentRunInput) => executeSpawnAgent(nextAgent, nextInput, options.integrations)); const stageLabel = formatStageLabel(activeStage); @@ -1100,7 +1159,9 @@ async function executeSpawnAgentStreaming( middlewareContext ); - await acp.withAcpWriter(writer, () => renderAcpStream(middlewareContext.eventStream ?? rawEvents)); + await acp.withAcpWriter(writer, () => + renderAcpStream(middlewareContext.eventStream ?? rawEvents) + ); const final = await done; const logFile = middlewareContext.logFile ?? final.logFile; @@ -1111,7 +1172,9 @@ async function executeSpawnAgentStreaming( exitCode: final.exitCode, ...(logFile ? { logFile } : {}), ...(sessionResult?.output ? { summary: sessionResult.output } : {}), - ...(middlewareContext.usage.inputTokens > 0 || middlewareContext.usage.outputTokens > 0 || middlewareContext.usage.cachedTokens !== undefined + ...(middlewareContext.usage.inputTokens > 0 || + middlewareContext.usage.outputTokens > 0 || + middlewareContext.usage.cachedTokens !== undefined ? { usage: { inputTokens: middlewareContext.usage.inputTokens, @@ -1126,7 +1189,12 @@ async function executeSpawnAgentStreaming( ? { toolCalls: sessionResult.toolCalls.flatMap((toolCall) => typeof toolCall.title === "string" - ? [{ title: toolCall.title, ...(toolCall.input !== undefined ? { input: toolCall.input } : {}) }] + ? [ + { + title: toolCall.title, + ...(toolCall.input !== undefined ? { input: toolCall.input } : {}) + } + ] : [] ) } diff --git a/packages/superintendent/src/runtime/agent-runner-session.ts b/packages/superintendent/src/runtime/agent-runner-session.ts new file mode 100644 index 0000000000..db3d1d4524 --- /dev/null +++ b/packages/superintendent/src/runtime/agent-runner-session.ts @@ -0,0 +1,70 @@ +import { + createPoeCommandSession, + resolvePoeCommandExecution, + type AgentRunnerSession, + type DownloadResult, + type OpenSpec, + type RuntimeOverrideOptions +} from "@poe-code/agent-harness-tools"; + +export function createSuperintendentAgentSession(options: { + homeDir: string; + runtime?: RuntimeOverrideOptions; +}): AgentRunnerSession { + let session: AgentRunnerSession | undefined; + + const getSession = (openSpec: OpenSpec): AgentRunnerSession => { + if (session) { + return session; + } + + const execution = resolvePoeCommandExecution({ + cwd: openSpec.cwd, + env: resolveOpenSpecEnv(openSpec), + argv: openSpec.jobLabel.argv, + tool: openSpec.jobLabel.tool, + runtime: options.runtime, + context: { + homeDir: options.homeDir + }, + openSpec + }); + + session = createPoeCommandSession({ + factory: execution.factory, + state: execution.state + }); + return session; + }; + + return { + async run(openSpec, signal, runOptions) { + return await getSession(openSpec).run(openSpec, signal, runOptions); + }, + async syncBack(): Promise { + return session ? await session.syncBack() : { files: 0, bytes: 0, conflicts: [] }; + }, + async close(): Promise { + await session?.close(); + } + }; +} + +export async function finalizeAgentRunnerSession( + session: AgentRunnerSession | undefined +): Promise { + if (!session) { + return; + } + + try { + await session.syncBack(); + } finally { + await session.close(); + } +} + +function resolveOpenSpecEnv(openSpec: OpenSpec): Record { + const env = openSpec.execution?.env ?? openSpec.env; + return (env ?? process.env) as Record; +} diff --git a/packages/superintendent/src/runtime/agent-runner.test.ts b/packages/superintendent/src/runtime/agent-runner.test.ts new file mode 100644 index 0000000000..7ea0637692 --- /dev/null +++ b/packages/superintendent/src/runtime/agent-runner.test.ts @@ -0,0 +1,69 @@ +import { describe, expect, it, vi } from "vitest"; +import type { AgentRunnerSession } from "@poe-code/agent-harness-tools"; + +describe("runAutonomousAgent", () => { + it("runs the role open spec through the injected session without syncing back", async () => { + const session: AgentRunnerSession = { + run: vi.fn(async () => ({ + kind: "sync" as const, + exitCode: 0, + stdout: "done", + stderr: "" + })), + syncBack: vi.fn(async () => ({ files: 0, bytes: 0, conflicts: [] })), + close: vi.fn(async () => {}) + }; + + const { runAutonomousAgent } = await import("./agent-runner.js"); + const result = await runAutonomousAgent({ + agent: "claude-code", + prompt: "Build the feature", + cwd: "/repo", + logPath: "/tmp/superintendent/builder.log", + session + }); + + expect(result).toEqual({ + stdout: "done", + logFile: "/tmp/superintendent/builder.log" + }); + expect(session.run).toHaveBeenCalledWith( + expect.objectContaining({ + cwd: "/repo", + jobLabel: expect.objectContaining({ + tool: "claude-code" + }) + }), + undefined, + { syncBack: false } + ); + }); + + it("throws when the injected session run exits non-zero", async () => { + const session: AgentRunnerSession = { + run: vi.fn(async () => ({ + kind: "sync" as const, + exitCode: 2, + stdout: "stdout details", + stderr: "stderr details" + })), + syncBack: vi.fn(async () => ({ files: 0, bytes: 0, conflicts: [] })), + close: vi.fn(async () => {}) + }; + + const { runAutonomousAgent } = await import("./agent-runner.js"); + + await expect( + runAutonomousAgent({ + agent: "claude-code", + prompt: "Build the feature", + cwd: "/repo", + session + }) + ).rejects.toThrow("stderr details"); + + expect(session.run).toHaveBeenCalledWith(expect.any(Object), undefined, { + syncBack: false + }); + }); +}); diff --git a/packages/superintendent/src/runtime/agent-runner.ts b/packages/superintendent/src/runtime/agent-runner.ts index 137551f865..c202d79020 100644 --- a/packages/superintendent/src/runtime/agent-runner.ts +++ b/packages/superintendent/src/runtime/agent-runner.ts @@ -2,15 +2,11 @@ import "@poe-code/agent-spawn/register-factories"; import { mkdirSync, openSync, writeSync, closeSync } from "node:fs"; import path from "node:path"; import { + type AgentRunnerSession, type RuntimeOverrideOptions, - resolvePoeCommandExecution, - runPoeCommand + resolvePoeCommandExecution } from "@poe-code/agent-harness-tools"; -import { - buildSpawnArgs, - type McpSpawnConfig, - type SpawnMode -} from "@poe-code/agent-spawn"; +import { buildSpawnArgs, type McpSpawnConfig, type SpawnMode } from "@poe-code/agent-spawn"; export type { McpSpawnConfig, SpawnMode }; @@ -27,6 +23,8 @@ export type AutonomousInput = { detach?: boolean; mountPoeCode?: boolean; runnerSync?: RuntimeOverrideOptions["runnerSync"]; + session?: AgentRunnerSession; + signal?: AbortSignal; }; export type AutonomousOutput = @@ -79,6 +77,14 @@ export async function runAutonomousAgent(input: AutonomousInput): Promise): TestFs { return { rawFs, - fs: ({ + fs: { readFile: (filePath: string, encoding: BufferEncoding) => rawFs.readFile(filePath, encoding) as Promise, writeFile: async (filePath: string, content: string) => { @@ -62,7 +63,7 @@ function createFs(files: Record): TestFs { await rawFs.mkdir(path.dirname(newPath), { recursive: true }); await rawFs.rename(oldPath, newPath); } - }) as SuperintendentFileSystem + } as SuperintendentFileSystem }; } @@ -82,10 +83,10 @@ function createDocument( const inspectorSpecs: InspectorSpec[] | undefined = options.withInspectors === false ? undefined - : options.inspectors ?? [ + : (options.inspectors ?? [ { name: "code-quality", prompt: "Inspect {{builder.summary}}" }, { name: "manual-qa", prompt: "Validate {{inspectors.code-quality}}" } - ]; + ]); const inspectors = inspectorSpecs ? [ @@ -189,7 +190,6 @@ describe("runLoop", () => { } }); - await expect( runLoop({ docPath, @@ -215,169 +215,261 @@ describe("runLoop", () => { ); }); - it( - "runs the full lifecycle, writes status updates, and preserves agent body edits", - async () => { - const docPath = "/repo/docs/plans/feature.md"; - const { fs, rawFs } = createFs({ [docPath]: createDocument() }); - const events: string[] = []; - const stateChanges: Array> = []; - - runBuilderMock.mockImplementation(async (doc) => { - expect(doc.frontmatter.status).toEqual({ - state: "in_progress", - round: 1, - review_turn: 0 - }); - const updated = (await rawFs.readFile(docPath, "utf8")) - .toString() - .replace("- [ ] Task 1", "- [x] Task 1"); - await rawFs.writeFile(docPath, updated, { encoding: "utf8" }); - events.push("builder"); - return { - summary: "Builder finished round 1", - log: "Marked Task 1 done" - }; - }); + it("passes an injected agent session to each role and finalizes it after the loop", async () => { + const docPath = "/repo/docs/plans/feature.md"; + const { fs } = createFs({ [docPath]: createDocument({ withInspectors: false }) }); + const session: AgentRunnerSession = { + run: vi.fn(async () => ({ + kind: "sync" as const, + exitCode: 0, + stdout: "", + stderr: "" + })), + syncBack: vi.fn(async () => ({ files: 1, bytes: 10, conflicts: [] })), + close: vi.fn(async () => {}) + }; + const events: string[] = []; + + runBuilderMock.mockImplementation(async (_doc, _context, options) => { + expect(options.agentSession).toBe(session); + events.push("builder"); + return { + summary: "Builder completed", + log: "Builder completed" + }; + }); + runSuperintendentMock.mockImplementation(async (_doc, _context, options) => { + expect(options.agentSession).toBe(session); + events.push("superintendent"); + return { + summary: "Ready", + transition: { + action: "request_review", + summary: "Ready" + } + }; + }); + runOwnerReviewMock.mockImplementation(async (_doc, _context, options) => { + expect(options.agentSession).toBe(session); + events.push("owner"); + return { + transition: { + action: "approve_completion" + } + }; + }); - runInspectorMock - .mockImplementationOnce(async (name, _config, doc, context) => { - expect(name).toBe("code-quality"); - expect(doc.frontmatter.status.round).toBe(1); - expect(context.builder).toEqual({ - summary: "Builder finished round 1", - log: "Marked Task 1 done" - }); - expect(context.inspectors).toEqual({}); - events.push("inspector:code-quality"); - return { - name, - summary: "Looks good" - }; - }) - .mockImplementationOnce(async (name, _config, _doc, context) => { - expect(name).toBe("manual-qa"); - expect(context.inspectors).toEqual({ - "code-quality": "Looks good" - }); - events.push("inspector:manual-qa"); - return { - name, - summary: "QA passed" - }; - }); + await expect( + runLoop({ + docPath, + cwd: "/repo", + homeDir: "/home/test", + fs, + agentSession: session, + runners + }) + ).resolves.toMatchObject({ + state: "completed", + stopReason: "completed" + }); - runSuperintendentMock.mockImplementation(async (doc, context) => { - expect(doc.frontmatter.status).toEqual({ - state: "in_progress", - round: 1, - review_turn: 0 - }); + expect(events).toEqual(["builder", "superintendent", "owner"]); + expect(session.syncBack).toHaveBeenCalledOnce(); + expect(session.close).toHaveBeenCalledOnce(); + expect(session.syncBack).toHaveBeenCalledBefore(session.close); + }); + + it("finalizes an injected agent session when a role fails", async () => { + const docPath = "/repo/docs/plans/feature.md"; + const { fs } = createFs({ [docPath]: createDocument({ withInspectors: false }) }); + const session: AgentRunnerSession = { + run: vi.fn(async () => ({ + kind: "sync" as const, + exitCode: 0, + stdout: "", + stderr: "" + })), + syncBack: vi.fn(async () => ({ files: 1, bytes: 10, conflicts: [] })), + close: vi.fn(async () => {}) + }; + + runBuilderMock.mockRejectedValue(new Error("builder failed")); + + await expect( + runLoop({ + docPath, + cwd: "/repo", + homeDir: "/home/test", + fs, + agentSession: session, + runners + }) + ).rejects.toThrow("builder failed"); + + expect(session.syncBack).toHaveBeenCalledOnce(); + expect(session.close).toHaveBeenCalledOnce(); + expect(session.syncBack).toHaveBeenCalledBefore(session.close); + }); + + it("runs the full lifecycle, writes status updates, and preserves agent body edits", async () => { + const docPath = "/repo/docs/plans/feature.md"; + const { fs, rawFs } = createFs({ [docPath]: createDocument() }); + const events: string[] = []; + const stateChanges: Array> = []; + + runBuilderMock.mockImplementation(async (doc) => { + expect(doc.frontmatter.status).toEqual({ + state: "in_progress", + round: 1, + review_turn: 0 + }); + const updated = (await rawFs.readFile(docPath, "utf8")) + .toString() + .replace("- [ ] Task 1", "- [x] Task 1"); + await rawFs.writeFile(docPath, updated, { encoding: "utf8" }); + events.push("builder"); + return { + summary: "Builder finished round 1", + log: "Marked Task 1 done" + }; + }); + + runInspectorMock + .mockImplementationOnce(async (name, _config, doc, context) => { + expect(name).toBe("code-quality"); + expect(doc.frontmatter.status.round).toBe(1); expect(context.builder).toEqual({ summary: "Builder finished round 1", log: "Marked Task 1 done" }); - expect(context.inspectors).toEqual({ - "code-quality": "Looks good", - "manual-qa": "QA passed" - }); - events.push("superintendent"); + expect(context.inspectors).toEqual({}); + events.push("inspector:code-quality"); return { - summary: "Ready for owner review", - transition: { - action: "request_review", - summary: "Ready for owner review" - } + name, + summary: "Looks good" }; - }); - - runOwnerReviewMock.mockImplementation(async (doc, context) => { - expect(doc.frontmatter.status).toEqual({ - state: "review", - round: 1, - review_turn: 0 - }); - expect(context.superintendent).toEqual({ - summary: "Ready for owner review" + }) + .mockImplementationOnce(async (name, _config, _doc, context) => { + expect(name).toBe("manual-qa"); + expect(context.inspectors).toEqual({ + "code-quality": "Looks good" }); - events.push("owner"); + events.push("inspector:manual-qa"); return { - transition: { - action: "approve_completion" - } + name, + summary: "QA passed" }; }); - const result = await runLoop({ - docPath, - cwd: "/repo", - homeDir: "/home/test", - fs, - runners, - callbacks: { - onBuilderStart: () => events.push("builder:start"), - onBuilderComplete: () => events.push("builder:complete"), - onInspectorStart: (name) => events.push(`inspector:start:${name}`), - onInspectorComplete: (result) => events.push(`inspector:complete:${result.name}`), - onSuperintendentStart: () => events.push("superintendent:start"), - onSuperintendentComplete: () => events.push("superintendent:complete"), - onOwnerStart: () => events.push("owner:start"), - onOwnerComplete: () => events.push("owner:complete"), - onRoundComplete: (round) => events.push(`round:${round}`), - onLoopComplete: () => events.push("loop:complete"), - onStateChange: (state) => { - stateChanges.push({ - state: state.state, - round: state.round, - reviewTurn: state.reviewTurn - }); - } - } - }); - - expect(result).toEqual({ - state: "completed", + runSuperintendentMock.mockImplementation(async (doc, context) => { + expect(doc.frontmatter.status).toEqual({ + state: "in_progress", round: 1, - reviewTurn: 0, - maxRounds: 10, - maxReviewTurns: 5, - stopReason: "completed" + review_turn: 0 + }); + expect(context.builder).toEqual({ + summary: "Builder finished round 1", + log: "Marked Task 1 done" }); - expect(events).toEqual([ - "builder:start", - "builder", - "builder:complete", - "inspector:start:code-quality", - "inspector:code-quality", - "inspector:complete:code-quality", - "inspector:start:manual-qa", - "inspector:manual-qa", - "inspector:complete:manual-qa", - "superintendent:start", - "superintendent", - "superintendent:complete", - "owner:start", - "owner", - "owner:complete", - "round:1", - "loop:complete" - ]); - expect(stateChanges).toEqual([ - { state: "in_progress", round: 1, reviewTurn: 0 }, - { state: "review", round: 1, reviewTurn: 0 }, - { state: "completed", round: 1, reviewTurn: 0 } - ]); - - const finalDoc = await readDoc(rawFs, docPath); - expect(finalDoc.body).toContain("- [x] Task 1"); - expect(finalDoc.frontmatter.status).toEqual({ - state: "completed", + expect(context.inspectors).toEqual({ + "code-quality": "Looks good", + "manual-qa": "QA passed" + }); + events.push("superintendent"); + return { + summary: "Ready for owner review", + transition: { + action: "request_review", + summary: "Ready for owner review" + } + }; + }); + + runOwnerReviewMock.mockImplementation(async (doc, context) => { + expect(doc.frontmatter.status).toEqual({ + state: "review", round: 1, review_turn: 0 }); - }, - 15_000 - ); + expect(context.superintendent).toEqual({ + summary: "Ready for owner review" + }); + events.push("owner"); + return { + transition: { + action: "approve_completion" + } + }; + }); + + const result = await runLoop({ + docPath, + cwd: "/repo", + homeDir: "/home/test", + fs, + runners, + callbacks: { + onBuilderStart: () => events.push("builder:start"), + onBuilderComplete: () => events.push("builder:complete"), + onInspectorStart: (name) => events.push(`inspector:start:${name}`), + onInspectorComplete: (result) => events.push(`inspector:complete:${result.name}`), + onSuperintendentStart: () => events.push("superintendent:start"), + onSuperintendentComplete: () => events.push("superintendent:complete"), + onOwnerStart: () => events.push("owner:start"), + onOwnerComplete: () => events.push("owner:complete"), + onRoundComplete: (round) => events.push(`round:${round}`), + onLoopComplete: () => events.push("loop:complete"), + onStateChange: (state) => { + stateChanges.push({ + state: state.state, + round: state.round, + reviewTurn: state.reviewTurn + }); + } + } + }); + + expect(result).toEqual({ + state: "completed", + round: 1, + reviewTurn: 0, + maxRounds: 10, + maxReviewTurns: 5, + stopReason: "completed" + }); + expect(events).toEqual([ + "builder:start", + "builder", + "builder:complete", + "inspector:start:code-quality", + "inspector:code-quality", + "inspector:complete:code-quality", + "inspector:start:manual-qa", + "inspector:manual-qa", + "inspector:complete:manual-qa", + "superintendent:start", + "superintendent", + "superintendent:complete", + "owner:start", + "owner", + "owner:complete", + "round:1", + "loop:complete" + ]); + expect(stateChanges).toEqual([ + { state: "in_progress", round: 1, reviewTurn: 0 }, + { state: "review", round: 1, reviewTurn: 0 }, + { state: "completed", round: 1, reviewTurn: 0 } + ]); + + const finalDoc = await readDoc(rawFs, docPath); + expect(finalDoc.body).toContain("- [x] Task 1"); + expect(finalDoc.frontmatter.status).toEqual({ + state: "completed", + round: 1, + review_turn: 0 + }); + }, 15_000); it("stores owner feedback and passes it to the next builder round", async () => { const docPath = "/repo/docs/plans/feature.md"; @@ -473,7 +565,6 @@ describe("runLoop", () => { throw new Error("builder failed"); }); - await expect( runLoop({ docPath, @@ -519,7 +610,6 @@ describe("runLoop", () => { throw new Error(`inspector failed: ${name}`); }); - await expect( runLoop({ docPath, @@ -815,9 +905,7 @@ describe("runLoop", () => { const docPath = "/repo/docs/plans/feature.md"; const { fs } = createFs({ [docPath]: createDocument({ - inspectors: [ - { name: "code-quality", prompt: "Check {{builder.summary}}" } - ], + inspectors: [{ name: "code-quality", prompt: "Check {{builder.summary}}" }], superintendentPrompt: "Review {{builder.summary}}" }) }); diff --git a/packages/superintendent/src/runtime/loop.ts b/packages/superintendent/src/runtime/loop.ts index 7f1243a233..6da93a83d0 100644 --- a/packages/superintendent/src/runtime/loop.ts +++ b/packages/superintendent/src/runtime/loop.ts @@ -1,11 +1,17 @@ import path from "node:path"; import * as fsPromises from "node:fs/promises"; -import { lockWorkflow, makeRunLogFileName, resolveWorkflowPath } from "@poe-code/agent-harness-tools"; +import { + lockWorkflow, + makeRunLogFileName, + resolveWorkflowPath, + type AgentRunnerSession +} from "@poe-code/agent-harness-tools"; import { parseSuperintendentDoc, type SuperintendentDoc } from "../document/parse.js"; import { parseTaskBoard } from "../document/tasks.js"; import { updateStatus } from "../document/write.js"; import { createLoopState, type LoopState } from "../state/machine.js"; import { withAutonomousAgentRunner, type McpSpawnConfig } from "./agent-runner.js"; +import { finalizeAgentRunnerSession } from "./agent-runner-session.js"; import { runBuilder, type BuilderResult } from "./run-builder.js"; import { runInspector, type InspectorResult } from "./run-inspector.js"; import { runOwnerReview, type OwnerResult } from "./run-owner-review.js"; @@ -31,11 +37,7 @@ export interface SuperintendentFileStat { export interface SuperintendentFileSystem { readFile(path: string, encoding: BufferEncoding): Promise; - writeFile( - path: string, - data: string, - options?: { encoding?: BufferEncoding } - ): Promise; + writeFile(path: string, data: string, options?: { encoding?: BufferEncoding }): Promise; readdir(path: string): Promise; stat(path: string): Promise; mkdir(path: string, options?: { recursive?: boolean }): Promise; @@ -107,6 +109,7 @@ export type RunLoopOptions = { fs?: SuperintendentFileSystem; callbacks?: LoopCallbacks; runAgent?: (input: AgentRunInput) => Promise; + agentSession?: AgentRunnerSession; runners?: LoopRunners; signal?: AbortSignal; logDir?: string; @@ -126,6 +129,7 @@ type LoopRuntime = { fs: SuperintendentFileSystem; callbacks: LoopCallbacks; runAgent?: (input: AgentRunInput) => Promise; + agentSession?: AgentRunnerSession; runners: ResolvedRunners; signal?: AbortSignal; logDir?: string; @@ -142,7 +146,10 @@ type TemplateLoopContext = { }; type LockCapableSuperintendentFs = { - open(path: string, flags: string): Promise<{ + open( + path: string, + flags: string + ): Promise<{ close(): Promise; writeFile( data: string, @@ -323,7 +330,9 @@ export async function runLoop( const superintendentResult = await executeSuperintendent(options, context); if (superintendentResult.transition?.action !== "request_review") { - throw new Error("Superintendent must call request_review to continue a review exchange"); + throw new Error( + "Superintendent must call request_review to continue a review exchange" + ); } context = { @@ -400,7 +409,11 @@ export async function runLoop( } }); } finally { - await releaseLock(); + try { + await finalizeAgentRunnerSession(options.agentSession); + } finally { + await releaseLock(); + } } } @@ -414,6 +427,7 @@ function normalizeOptions(input: string | RunLoopOptions, callbacks?: LoopCallba callbacks: input.callbacks ?? {}, runners: resolveRunners(input.runners), ...(input.runAgent ? { runAgent: input.runAgent } : {}), + ...(input.agentSession ? { agentSession: input.agentSession } : {}), ...(input.signal ? { signal: input.signal } : {}), ...(input.logDir ? { logDir: input.logDir } : {}) }; @@ -480,10 +494,7 @@ async function readDocument( return parseSuperintendentDoc(docPath, content); } -async function readDocumentContent( - fs: SuperintendentFileSystem, - docPath: string -): Promise { +async function readDocumentContent(fs: SuperintendentFileSystem, docPath: string): Promise { return fs.readFile(docPath, "utf8"); } @@ -599,10 +610,11 @@ async function executeSuperintendent( function buildRoleOptions( options: LoopRuntime, role: string -): { defaultCwd: string; logPath?: string } { +): { defaultCwd: string; logPath?: string; agentSession?: AgentRunnerSession } { return { defaultCwd: options.cwd, - ...(options.logDir ? { logPath: path.join(options.logDir, makeRunLogFileName(role)) } : {}) + ...(options.logDir ? { logPath: path.join(options.logDir, makeRunLogFileName(role)) } : {}), + ...(options.agentSession ? { agentSession: options.agentSession } : {}) }; } @@ -720,7 +732,9 @@ async function withInjectedAgentRunner( if (result.exitCode !== 0) { throw new Error( - result.stderr || result.stdout || `Agent \`${agent}\` failed with exit code ${result.exitCode}` + result.stderr || + result.stdout || + `Agent \`${agent}\` failed with exit code ${result.exitCode}` ); } diff --git a/packages/superintendent/src/runtime/run-builder.ts b/packages/superintendent/src/runtime/run-builder.ts index 3812fa9d26..767430953d 100644 --- a/packages/superintendent/src/runtime/run-builder.ts +++ b/packages/superintendent/src/runtime/run-builder.ts @@ -1,10 +1,7 @@ import "@poe-code/agent-spawn/register-factories"; +import type { AgentRunnerSession } from "@poe-code/agent-harness-tools"; import type { SuperintendentDoc } from "../document/parse.js"; -import { - runAutonomousAgent, - type AutonomousOutput, - type McpSpawnConfig -} from "./agent-runner.js"; +import { runAutonomousAgent, type AutonomousOutput, type McpSpawnConfig } from "./agent-runner.js"; import { resolveRoleCwd } from "./resolve-cwd.js"; import { resolveTemplate, type TemplateContext } from "./templates.js"; @@ -18,6 +15,7 @@ export type RunBuilderOptions = { promptOverride?: string; defaultCwd: string; logPath?: string; + agentSession?: AgentRunnerSession; }; export async function runBuilder( @@ -34,7 +32,8 @@ export async function runBuilder( prompt, cwd: resolveRoleCwd(doc.frontmatter.builder, doc.filePath, options.defaultCwd), mcpServers: buildMcpServers(doc), - ...(options.logPath ? { logPath: options.logPath } : {}) + ...(options.logPath ? { logPath: options.logPath } : {}), + ...(options.agentSession ? { session: options.agentSession } : {}) }); const log = extractLog(result); @@ -86,7 +85,13 @@ function extractLog(result: AutonomousOutput): string { return result; } - return readString(result.log) ?? readString(result.output) ?? readString(result.stdout) ?? readString(result.text) ?? ""; + return ( + readString(result.log) ?? + readString(result.output) ?? + readString(result.stdout) ?? + readString(result.text) ?? + "" + ); } function extractLogPath(result: AutonomousOutput, options: RunBuilderOptions): string { diff --git a/packages/superintendent/src/runtime/run-inspector.ts b/packages/superintendent/src/runtime/run-inspector.ts index c5ff0e2037..0b5a6de7e6 100644 --- a/packages/superintendent/src/runtime/run-inspector.ts +++ b/packages/superintendent/src/runtime/run-inspector.ts @@ -1,10 +1,7 @@ import "@poe-code/agent-spawn/register-factories"; +import type { AgentRunnerSession } from "@poe-code/agent-harness-tools"; import type { AgentRoleConfig, SuperintendentDoc } from "../document/parse.js"; -import { - runAutonomousAgent, - type AutonomousOutput, - type McpSpawnConfig -} from "./agent-runner.js"; +import { runAutonomousAgent, type AutonomousOutput, type McpSpawnConfig } from "./agent-runner.js"; import { resolveRoleCwd } from "./resolve-cwd.js"; import { buildInspectorSystemPrompt, prependSystemPrompt } from "./system-prompt.js"; import { resolveTemplate, type TemplateContext } from "./templates.js"; @@ -19,6 +16,7 @@ export type RunInspectorOptions = { promptOverride?: string; defaultCwd: string; logPath?: string; + agentSession?: AgentRunnerSession; }; export async function runInspector( @@ -29,8 +27,7 @@ export async function runInspector( options: RunInspectorOptions ): Promise { const userPrompt = - options.promptOverride ?? - resolveTemplate(config.prompt, buildTemplateContext(doc, context)); + options.promptOverride ?? resolveTemplate(config.prompt, buildTemplateContext(doc, context)); const systemPrompt = buildInspectorSystemPrompt({ inspectorName: name, ...(context.builder @@ -49,7 +46,8 @@ export async function runInspector( prompt, cwd: resolveRoleCwd(config, doc.filePath, options.defaultCwd), mcpServers: buildMcpServers(doc, config), - ...(options.logPath ? { logPath: options.logPath } : {}) + ...(options.logPath ? { logPath: options.logPath } : {}), + ...(options.agentSession ? { session: options.agentSession } : {}) }); const logPath = extractLogPath(output); @@ -89,7 +87,7 @@ function buildMcpServers( export async function runAllInspectors( doc: SuperintendentDoc, context: Partial, - options: { defaultCwd: string } + options: { defaultCwd: string; agentSession?: AgentRunnerSession } ): Promise { const inspectors = doc.frontmatter.inspectors; diff --git a/packages/superintendent/src/runtime/run-owner-review.ts b/packages/superintendent/src/runtime/run-owner-review.ts index d7c755642a..cfb1ceaf6d 100644 --- a/packages/superintendent/src/runtime/run-owner-review.ts +++ b/packages/superintendent/src/runtime/run-owner-review.ts @@ -1,18 +1,11 @@ import "@poe-code/agent-spawn/register-factories"; +import type { AgentRunnerSession } from "@poe-code/agent-harness-tools"; import type { McpConfig, SuperintendentDoc } from "../document/parse.js"; -import { - runAutonomousAgent, - type AutonomousOutput, - type McpSpawnConfig -} from "./agent-runner.js"; +import { runAutonomousAgent, type AutonomousOutput, type McpSpawnConfig } from "./agent-runner.js"; import { resolveRoleCwd } from "./resolve-cwd.js"; import { buildOwnerSystemPrompt, prependSystemPrompt } from "./system-prompt.js"; import { resolveTemplate, type TemplateContext } from "./templates.js"; -import { - createWorkflowTool, - parseWorkflowCall, - type WorkflowTransition -} from "./workflow-tool.js"; +import { createWorkflowTool, parseWorkflowCall, type WorkflowTransition } from "./workflow-tool.js"; type OwnerTransition = Extract< WorkflowTransition, @@ -42,6 +35,7 @@ const WORKFLOW_SERVER_TIMEOUT_SECONDS = 7200; export type RunOwnerReviewOptions = { defaultCwd: string; logPath?: string; + agentSession?: AgentRunnerSession; }; export async function runOwnerReview( @@ -60,7 +54,8 @@ export async function runOwnerReview( prompt, cwd: resolveRoleCwd(doc.frontmatter.owner, doc.filePath, options.defaultCwd), mcpServers: buildMcpServers(doc), - ...(options.logPath ? { logPath: options.logPath } : {}) + ...(options.logPath ? { logPath: options.logPath } : {}), + ...(options.agentSession ? { session: options.agentSession } : {}) }); const logPath = extractLogPath(result); @@ -121,7 +116,9 @@ function extractOwnerTransition(result: AutonomousOutput): OwnerTransition { const transition = extractTransition(result); if (transition === undefined) { - throw new Error(`Owner review must end with workflow_transition.${describeMissingTransition(result)}`); + throw new Error( + `Owner review must end with workflow_transition.${describeMissingTransition(result)}` + ); } if (transition.action !== "approve_completion" && transition.action !== "request_changes") { @@ -134,7 +131,11 @@ function extractOwnerTransition(result: AutonomousOutput): OwnerTransition { function describeMissingTransition(result: AutonomousOutput): string { const parts: string[] = []; const names = collectToolNames(result); - parts.push(names.length === 0 ? " No tool calls were captured." : ` Observed tool calls: ${names.join(", ")}.`); + parts.push( + names.length === 0 + ? " No tool calls were captured." + : ` Observed tool calls: ${names.join(", ")}.` + ); const logPath = extractLogPath(result); if (logPath) { diff --git a/packages/superintendent/src/runtime/run-superintendent.ts b/packages/superintendent/src/runtime/run-superintendent.ts index ce6a70f1ff..15c957d026 100644 --- a/packages/superintendent/src/runtime/run-superintendent.ts +++ b/packages/superintendent/src/runtime/run-superintendent.ts @@ -1,15 +1,9 @@ import "@poe-code/agent-spawn/register-factories"; +import type { AgentRunnerSession } from "@poe-code/agent-harness-tools"; import type { McpConfig, SuperintendentDoc } from "../document/parse.js"; -import { - runAutonomousAgent, - type AutonomousOutput, - type McpSpawnConfig -} from "./agent-runner.js"; +import { runAutonomousAgent, type AutonomousOutput, type McpSpawnConfig } from "./agent-runner.js"; import { resolveRoleCwd } from "./resolve-cwd.js"; -import { - buildSuperintendentSystemPrompt, - prependSystemPrompt -} from "./system-prompt.js"; +import { buildSuperintendentSystemPrompt, prependSystemPrompt } from "./system-prompt.js"; import { resolveTemplate, type TemplateContext } from "./templates.js"; import { parseWorkflowCall, type WorkflowTransition } from "./workflow-tool.js"; @@ -37,6 +31,7 @@ const SUPERINTENDENT_TOOLS_TIMEOUT_SECONDS = 7200; export type RunSuperintendentOptions = { defaultCwd: string; logPath?: string; + agentSession?: AgentRunnerSession; }; export async function runSuperintendent( @@ -59,7 +54,8 @@ export async function runSuperintendent( prompt, cwd: resolveRoleCwd(doc.frontmatter.superintendent, doc.filePath, options.defaultCwd), mcpServers: buildMcpServers(doc), - ...(options.logPath ? { logPath: options.logPath } : {}) + ...(options.logPath ? { logPath: options.logPath } : {}), + ...(options.agentSession ? { session: options.agentSession } : {}) }); const transition = extractTransition(result); const logPath = extractLogPath(result); @@ -202,12 +198,7 @@ function extractOutputText(result: AutonomousOutput): string { return result; } - return ( - readString(result.output) ?? - readString(result.stdout) ?? - readString(result.text) ?? - "" - ); + return readString(result.output) ?? readString(result.stdout) ?? readString(result.text) ?? ""; } function readToolCall(value: unknown): ToolCallLike | undefined { diff --git a/src/cli/commands/experiment-ralph.test.ts b/src/cli/commands/experiment-ralph.test.ts index 7ac52a38f1..454cc2aa0c 100644 --- a/src/cli/commands/experiment-ralph.test.ts +++ b/src/cli/commands/experiment-ralph.test.ts @@ -1,4 +1,4 @@ -import { afterEach, describe, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { Volume, createFsFromVolume } from "memfs"; import { Command } from "commander"; import { createCliContainer } from "../container.js"; @@ -46,6 +46,10 @@ vi.mock("../../sdk/spawn.js", () => ({ }) })); +vi.mock("../../sdk/spawn-session.js", () => ({ + createSpawnSession: vi.fn() +})); + vi.mock("@poe-code/design-system", async (importOriginal) => { const actual = await importOriginal(); return { @@ -64,6 +68,7 @@ import { } from "../../sdk/experiment.js"; import { runRalph as sdkRunRalph } from "../../sdk/ralph.js"; import { spawn as sdkSpawn } from "../../sdk/spawn.js"; +import { createSpawnSession } from "../../sdk/spawn-session.js"; import { acp, createDashboard, withOutputFormat } from "@poe-code/design-system"; const cwd = "/repo"; @@ -176,6 +181,14 @@ const expectedTimestamp = (() => { return `[${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}:${String(date.getSeconds()).padStart(2, "0")}]`; })(); describe("experiment run command", () => { + beforeEach(() => { + vi.mocked(createSpawnSession).mockReturnValue({ + run: vi.fn().mockResolvedValue({ stdout: "", stderr: "", exitCode: 0 }), + syncBack: vi.fn().mockResolvedValue({ files: 0, bytes: 0, conflicts: [] }), + close: vi.fn().mockResolvedValue(undefined) + }); + }); + afterEach(() => { vi.clearAllMocks(); isCancelMock.mockReturnValue(false); @@ -788,6 +801,166 @@ describe("experiment run command", () => { vi.doUnmock("@poe-code/braintrust"); }); + it("runs the non-dashboard integration agent through one synced spawn session", async () => { + const spawnMiddleware = vi.fn(async (_ctx, next: () => Promise) => { + await next(); + }); + vi.doMock("@poe-code/braintrust", () => ({ + bootstrap: vi.fn(async () => ({ + spawnMiddleware, + traceRun: async (_surface: string, _name: string, fn: () => Promise) => fn(), + shutdown: vi.fn(async () => undefined) + })) + })); + + const run = vi.fn().mockResolvedValue({ + stdout: "done", + stderr: "", + exitCode: 0 + }); + const close = vi.fn().mockResolvedValue(undefined); + vi.mocked(createSpawnSession).mockReturnValueOnce({ + run, + syncBack: vi.fn().mockResolvedValue({ files: 0, bytes: 0, conflicts: [] }), + close + }); + vi.mocked(sdkRunExperiment).mockImplementationOnce(async (options) => { + await options.runAgent?.({ + agent: "codex", + prompt: "Run integration experiment", + cwd, + model: "gpt-5.2" + }); + + return { + stopReason: "max_experiments", + docPath: options.docPath, + experimentsCompleted: 1, + experimentsKept: 0, + totalDurationMs: 1_000 + }; + }); + + const container = createCliContainer({ + fs: createMemFs({ + [`${homeDir}/.poe-code/config.json`]: JSON.stringify({ + integrations: { + braintrust: { + enabled: true, + apiKey: "key", + project: "project" + } + } + }), + "/repo/docs/loop.md": "# Loop" + }), + prompts: vi.fn().mockResolvedValue({}), + env: { cwd, homeDir }, + logger: () => {} + }); + const program = createBaseProgram(); + registerExperimentCommand(program, container); + + await program.parseAsync([ + "node", + "cli", + "--yes", + "experiment", + "run", + "docs/loop.md", + "--agent", + "codex", + "--max-experiments", + "1", + "--no-tui" + ]); + + expect(createSpawnSession).toHaveBeenCalledWith( + expect.objectContaining({ + service: "codex", + cwd, + mode: "yolo", + middlewares: [spawnMiddleware], + downloadConflict: "overwrite", + context: { + homeDir + } + }) + ); + expect(run).toHaveBeenCalledWith({ + agent: "codex", + prompt: "Run integration experiment", + cwd, + model: "gpt-5.2", + syncBack: true + }); + expect(close).toHaveBeenCalledTimes(1); + expect(vi.mocked(sdkSpawn.autonomous)).not.toHaveBeenCalled(); + + vi.doUnmock("@poe-code/braintrust"); + }); + + it("does not open an experiment spawn session for detached integration runs", async () => { + vi.doMock("@poe-code/braintrust", () => ({ + bootstrap: vi.fn(async () => ({ + spawnMiddleware: vi.fn(async (_ctx, next: () => Promise) => { + await next(); + }), + traceRun: async (_surface: string, _name: string, fn: () => Promise) => fn(), + shutdown: vi.fn(async () => undefined) + })) + })); + + const container = createCliContainer({ + fs: createMemFs({ + [`${homeDir}/.poe-code/config.json`]: JSON.stringify({ + integrations: { + braintrust: { + enabled: true, + apiKey: "key", + project: "project" + } + } + }), + "/repo/docs/loop.md": "# Loop" + }), + prompts: vi.fn().mockResolvedValue({}), + env: { cwd, homeDir }, + logger: () => {} + }); + const program = createBaseProgram(); + registerExperimentCommand(program, container); + + await program.parseAsync([ + "node", + "cli", + "--yes", + "experiment", + "run", + "docs/loop.md", + "--agent", + "codex", + "--max-experiments", + "1", + "--detach", + "--no-tui" + ]); + + expect(createSpawnSession).not.toHaveBeenCalled(); + expect(vi.mocked(sdkRunExperiment)).toHaveBeenCalledWith( + expect.objectContaining({ + detach: true + }) + ); + expect(vi.mocked(sdkRunExperiment)).toHaveBeenCalledWith( + expect.not.objectContaining({ + runAgent: expect.any(Function) + }) + ); + + vi.doUnmock("@poe-code/braintrust"); + }); + it("uses the experiment.tui config value when set", async () => { vi.useFakeTimers(); vi.setSystemTime(new Date(0)); @@ -1006,10 +1179,11 @@ describe("experiment run command", () => { const dashboardMock = createDashboardMock(); vi.mocked(createDashboard).mockReturnValueOnce(dashboardMock.dashboard); - vi.mocked(sdkSpawn.autonomous).mockImplementationOnce(async (_agent, input) => { + let stderrTee: { write(chunk: string): void } | undefined; + const run = vi.fn().mockImplementationOnce(async () => { acp.getAcpWriter()("Running experiment step"); acp.getAcpWriter()("Evaluating metrics"); - input.tee?.stderr?.write("Metric warning\npartial stderr"); + stderrTee?.write("Metric warning\npartial stderr"); return { stdout: "", @@ -1017,6 +1191,15 @@ describe("experiment run command", () => { exitCode: 0 }; }); + const close = vi.fn().mockResolvedValue(undefined); + vi.mocked(createSpawnSession).mockImplementationOnce((input) => { + stderrTee = input.tee?.stderr; + return { + run, + syncBack: vi.fn().mockResolvedValue({ files: 0, bytes: 0, conflicts: [] }), + close + }; + }); vi.mocked(sdkRunExperiment).mockImplementationOnce(async (options) => { options.onExperimentStart?.(1, "claude-code"); @@ -1077,19 +1260,26 @@ describe("experiment run command", () => { signal: expect.any(AbortSignal) }) ); - expect(vi.mocked(sdkSpawn.autonomous)).toHaveBeenCalledWith( - "claude-code", + expect(vi.mocked(createSpawnSession)).toHaveBeenCalledWith( expect.objectContaining({ - prompt: "Run experiment iteration", cwd, mode: "yolo", - signal: expect.any(AbortSignal), + service: "claude-code", useStdin: true, tee: expect.objectContaining({ stderr: expect.any(Object) }) }) ); + expect(run).toHaveBeenCalledWith({ + agent: "claude-code", + prompt: "Run experiment iteration", + cwd, + signal: expect.any(AbortSignal), + syncBack: true + }); + expect(close).toHaveBeenCalledTimes(1); + expect(vi.mocked(sdkSpawn.autonomous)).not.toHaveBeenCalled(); const outputs = dashboardMock.appendOutput.mock.calls.map(([item]) => item); expect( @@ -1694,6 +1884,14 @@ describe("experiment install command", () => { }); describe("ralph run command", () => { + beforeEach(() => { + vi.mocked(createSpawnSession).mockReturnValue({ + run: vi.fn().mockResolvedValue({ stdout: "", stderr: "", exitCode: 0 }), + syncBack: vi.fn().mockResolvedValue({ files: 0, bytes: 0, conflicts: [] }), + close: vi.fn().mockResolvedValue(undefined) + }); + }); + afterEach(() => { vi.clearAllMocks(); isCancelMock.mockReturnValue(false); @@ -1780,6 +1978,130 @@ describe("ralph run command", () => { ); }); + it("opens one spawn session for non-detached Ralph CLI runs and syncs back once", async () => { + const run = vi.fn().mockResolvedValue({ stdout: "ok", stderr: "", exitCode: 0 }); + const syncBack = vi.fn().mockResolvedValue({ files: 2, bytes: 4, conflicts: [] }); + const close = vi.fn().mockResolvedValue(undefined); + vi.mocked(createSpawnSession).mockReturnValueOnce({ run, syncBack, close }); + vi.mocked(sdkRunRalph).mockImplementationOnce(async (options) => { + await options.runAgent?.({ + agent: "claude-code", + prompt: "first", + cwd, + model: "sonnet", + signal: options.signal + }); + await options.runAgent?.({ + agent: "codex", + prompt: "second", + cwd, + model: "gpt-5.2", + signal: options.signal + }); + return { + stopReason: "max_iterations", + docPath: options.docPath, + iterationsCompleted: 2, + totalDurationMs: 1_000 + }; + }); + + const container = createCliContainer({ + fs: createMemFs({ + "/repo/docs/loop.md": "# Loop" + }), + prompts: vi.fn().mockResolvedValue({}), + env: { cwd, homeDir }, + logger: () => {} + }); + const program = createBaseProgram(); + registerRalphCommand(program, container); + + await program.parseAsync([ + "node", + "cli", + "ralph", + "run", + "docs/loop.md", + "--agent", + "claude:sonnet", + "--iterations", + "2", + "--runtime", + "e2b", + "--runtime-template", + "tmpl_test", + "--runner-sync", + "upload" + ]); + + expect(createSpawnSession).toHaveBeenCalledWith({ + service: "claude-code", + cwd, + model: "sonnet", + mode: "yolo", + runtime: "e2b", + runtimeTemplate: "tmpl_test", + runtimeConfigCwd: cwd, + runnerSync: "upload", + downloadConflict: "overwrite", + context: { + homeDir + } + }); + expect(run).toHaveBeenNthCalledWith(1, { + agent: "claude-code", + prompt: "first", + cwd, + model: "sonnet", + signal: undefined, + syncBack: false + }); + expect(run).toHaveBeenNthCalledWith(2, { + agent: "codex", + prompt: "second", + cwd, + model: "gpt-5.2", + signal: undefined, + syncBack: false + }); + expect(syncBack).toHaveBeenCalledTimes(1); + expect(close).toHaveBeenCalledTimes(1); + }); + + it("skips the spawn session for detached Ralph CLI runs", async () => { + const container = createCliContainer({ + fs: createMemFs({ + "/repo/docs/loop.md": "# Loop" + }), + prompts: vi.fn().mockResolvedValue({}), + env: { cwd, homeDir }, + logger: () => {} + }); + const program = createBaseProgram(); + registerRalphCommand(program, container); + + await program.parseAsync([ + "node", + "cli", + "ralph", + "run", + "docs/loop.md", + "--agent", + "claude", + "--iterations", + "1", + "--detach" + ]); + + expect(createSpawnSession).not.toHaveBeenCalled(); + expect(vi.mocked(sdkRunRalph)).toHaveBeenCalledWith( + expect.not.objectContaining({ + runAgent: expect.any(Function) + }) + ); + }); + it("reads agent and iterations from frontmatter and skips prompts", async () => { const container = createCliContainer({ fs: createMemFs({ @@ -2670,10 +2992,13 @@ describe("ralph run command", () => { const dashboardMock = createDashboardMock(); vi.mocked(createDashboard).mockReturnValueOnce(dashboardMock.dashboard); - vi.mocked(sdkSpawn.autonomous).mockImplementationOnce(async (_agent, input) => { + const run = vi.fn().mockImplementation(async () => { acp.getAcpWriter()("Analyzing doc"); acp.getAcpWriter()("Drafting update"); - input.tee?.stderr?.write("Tool warning\npartial stderr"); + const sessionOptions = vi.mocked(createSpawnSession).mock.calls[0]?.[0] as + | { tee?: { stderr?: { write(chunk: string): void } } } + | undefined; + sessionOptions?.tee?.stderr?.write("Tool warning\npartial stderr"); return { stdout: "", @@ -2681,6 +3006,9 @@ describe("ralph run command", () => { exitCode: 0 }; }); + const syncBack = vi.fn().mockResolvedValue({ files: 1, bytes: 2, conflicts: [] }); + const close = vi.fn().mockResolvedValue(undefined); + vi.mocked(createSpawnSession).mockReturnValueOnce({ run, syncBack, close }); vi.mocked(sdkRunRalph).mockImplementationOnce(async (options) => { options.onIterationStart?.(1, 5, "claude-code"); @@ -2732,19 +3060,28 @@ describe("ralph run command", () => { signal: expect.any(AbortSignal) }) ); - expect(vi.mocked(sdkSpawn.autonomous)).toHaveBeenCalledWith( - "claude-code", + expect(createSpawnSession).toHaveBeenCalledWith( expect.objectContaining({ - prompt: "Inspect the plan doc", + service: "claude-code", cwd, mode: "yolo", - signal: expect.any(AbortSignal), useStdin: true, tee: expect.objectContaining({ stderr: expect.any(Object) }) }) ); + expect(run).toHaveBeenCalledWith({ + agent: "claude-code", + prompt: "Inspect the plan doc", + cwd, + model: undefined, + signal: expect.any(AbortSignal), + syncBack: false + }); + expect(syncBack).toHaveBeenCalledTimes(1); + expect(close).toHaveBeenCalledTimes(1); + expect(vi.mocked(sdkSpawn.autonomous)).not.toHaveBeenCalled(); const outputs = dashboardMock.appendOutput.mock.calls.map(([item]) => item); expect( diff --git a/src/cli/commands/experiment.ts b/src/cli/commands/experiment.ts index f3ffb6de33..542e8d3347 100644 --- a/src/cli/commands/experiment.ts +++ b/src/cli/commands/experiment.ts @@ -41,7 +41,7 @@ import { readExperimentJournal as sdkReadExperimentJournal, appendExperimentJournalEntry as sdkAppendExperimentJournalEntry } from "../../sdk/experiment.js"; -import { spawn as sdkSpawn } from "../../sdk/spawn.js"; +import { createSpawnSession, type SpawnSession } from "../../sdk/spawn-session.js"; import { experimentConfigScope, planConfigScope } from "../../services/config.js"; import { loadIntegrations, @@ -59,7 +59,11 @@ import { registerDashboardQuitCommands, shouldUseInteractiveDashboard } from "./dashboard-loop-shared.js"; -import { addRuntimeOptions, pickRuntimeOptions, type RuntimeCliOptions } from "./runtime-options.js"; +import { + addRuntimeOptions, + pickRuntimeOptions, + type RuntimeCliOptions +} from "./runtime-options.js"; const DEFAULT_EXPERIMENT_AGENT = "claude-code"; const DEFAULT_EXPERIMENT_SCOPE: SkillScope = "local"; @@ -248,66 +252,88 @@ function formatExperimentStageLabel(index: number): string { } function createExperimentDashboardRunAgent(options: { + session: SpawnSession; appendOutput: (kind: "tool" | "error", message: string) => void; activeStage: () => string; - runtimeOptions: RuntimeCliOptions; - middlewares?: AcpMiddleware[]; + flushErrors: () => void; }): NonNullable { return async (input) => { - const errorBuffer = createDashboardLineBuffer((line) => { - options.appendOutput("error", `[${options.activeStage()}] ${line}`); - }); - try { - const result = await acp.withAcpWriter( + return await acp.withAcpWriter( (line) => { options.appendOutput("tool", `[${options.activeStage()}] ${line}`); }, async () => - await sdkSpawn.autonomous(input.agent, { + await options.session.run({ + agent: input.agent, prompt: input.prompt, cwd: input.cwd, - model: input.model, - mode: "yolo", - ...options.runtimeOptions, + ...(input.model ? { model: input.model } : {}), ...(input.signal ? { signal: input.signal } : {}), - ...(options.middlewares ? { middlewares: options.middlewares } : {}), - useStdin: true, - tee: { - stderr: { - write(chunk: string) { - errorBuffer.push(chunk); - } - } - } + syncBack: true }) ); - - errorBuffer.flush(); - return result; - } catch (error) { - errorBuffer.flush(); - throw error; + } finally { + options.flushErrors(); } }; } function createExperimentCliRunAgent(options: { - runtimeOptions: RuntimeCliOptions; - middlewares: AcpMiddleware[]; + session: SpawnSession; }): NonNullable { return async (input) => - sdkSpawn.autonomous(input.agent, { + await options.session.run({ + agent: input.agent, prompt: input.prompt, cwd: input.cwd, - model: input.model, - mode: "yolo", - ...options.runtimeOptions, + ...(input.model ? { model: input.model } : {}), ...(input.signal ? { signal: input.signal } : {}), - middlewares: options.middlewares + syncBack: true }); } +function createExperimentSpawnSession(options: { + agent: string | string[]; + cwd: string; + homeDir: string; + runtimeOptions: RuntimeCliOptions; + useStdin?: boolean; + tee?: { + stdout?: { write(chunk: string): void }; + stderr?: { write(chunk: string): void }; + }; + middlewares?: AcpMiddleware[]; +}): SpawnSession { + const initialAgent = resolveInitialExperimentAgent(options.agent); + + return createSpawnSession({ + service: initialAgent.agent, + cwd: options.cwd, + ...(initialAgent.model ? { model: initialAgent.model } : {}), + mode: "yolo", + ...options.runtimeOptions, + ...(options.useStdin ? { useStdin: true } : {}), + ...(options.tee ? { tee: options.tee } : {}), + ...(options.middlewares ? { middlewares: options.middlewares } : {}), + downloadConflict: "overwrite", + context: { + homeDir: options.homeDir + } + }); +} + +function resolveInitialExperimentAgent(agent: string | string[]): { + agent: string; + model?: string; +} { + const specifier = parseAgentSpecifier(Array.isArray(agent) ? agent[0]! : agent); + return { + agent: specifier.agent, + ...(specifier.model ? { model: specifier.model } : {}) + }; +} + async function runExperimentWithDashboard( options: ExperimentDashboardRunOptions ): Promise>> { @@ -378,70 +404,100 @@ async function runExperimentWithDashboard( }; process.on("SIGINT", sigintHandler); - const runAgent = createExperimentDashboardRunAgent({ - appendOutput, - activeStage: () => formatExperimentStageLabel(currentExperimentIndex), - runtimeOptions: options.runtimeOptions, - ...(options.integrations?.spawnMiddleware - ? { middlewares: [options.integrations.spawnMiddleware] } - : {}) - }); - try { - const runOptions: Parameters[0] = { - ...options.runOptions, - signal: abortController.signal, - runAgent, - onExperimentStart(index, currentAgent) { - currentExperimentIndex = index; - currentAction = formatExperimentCurrentAction(index, options.maxExperiments, currentAgent); - appendOutput( - "status", - options.maxExperiments === undefined - ? `Experiment ${index} (${currentAgent})` - : `Experiment ${index}/${options.maxExperiments} (${currentAgent})` - ); - syncStats(); - }, - onBaselineCollected(baseline) { - const entries = Object.entries(baseline) - .map(([name, value]) => `${name}=${value}`) - .join(", "); - appendOutput("info", `Baseline collected: ${entries}`); - }, - onCommit(commitHash) { - appendOutput("info", `Committed ${commitHash.slice(0, 7)}`); - }, - onMetricResult(metric, result) { - const score = result.score === null ? "-" : String(result.score); - const metricStatus = result.passed ? "passed" : "failed"; - appendOutput("info", `${metric.name}: ${score} (${metricStatus})`); - }, - onReset(targetHash) { - appendOutput("info", `Reset to ${targetHash.slice(0, 7)}`); - }, - onExperimentComplete(index, entry) { - iterations = Math.max(iterations, index); - appendOutput( - entry.status === "keep" ? "success" : "error", - `Experiment ${index} ${entry.status} in ${formatDashboardDuration(entry.durationMs)} · scores: ${formatExperimentScores(entry.scores)}` - ); - syncStats(); - } - }; - const result = await runExperimentWithIntegrations( - options.integrations, - options.docPath, - { + const errorBuffer = createDashboardLineBuffer((line) => { + appendOutput("error", `[${formatExperimentStageLabel(currentExperimentIndex)}] ${line}`); + }); + const session = + options.runtimeOptions.detach === true + ? undefined + : createExperimentSpawnSession({ + agent: options.agent, + cwd: options.runOptions.cwd, + homeDir: options.runOptions.homeDir, + runtimeOptions: options.runtimeOptions, + useStdin: true, + tee: { + stderr: { + write(chunk: string) { + errorBuffer.push(chunk); + } + } + }, + ...(options.integrations?.spawnMiddleware + ? { middlewares: [options.integrations.spawnMiddleware] } + : {}) + }); + + try { + const runOptions: Parameters[0] = { + ...options.runOptions, + signal: abortController.signal, + ...(session + ? { + runAgent: createExperimentDashboardRunAgent({ + session, + appendOutput, + activeStage: () => formatExperimentStageLabel(currentExperimentIndex), + flushErrors: () => { + errorBuffer.flush(); + } + }) + } + : {}), + onExperimentStart(index, currentAgent) { + currentExperimentIndex = index; + currentAction = formatExperimentCurrentAction( + index, + options.maxExperiments, + currentAgent + ); + appendOutput( + "status", + options.maxExperiments === undefined + ? `Experiment ${index} (${currentAgent})` + : `Experiment ${index}/${options.maxExperiments} (${currentAgent})` + ); + syncStats(); + }, + onBaselineCollected(baseline) { + const entries = Object.entries(baseline) + .map(([name, value]) => `${name}=${value}`) + .join(", "); + appendOutput("info", `Baseline collected: ${entries}`); + }, + onCommit(commitHash) { + appendOutput("info", `Committed ${commitHash.slice(0, 7)}`); + }, + onMetricResult(metric, result) { + const score = result.score === null ? "-" : String(result.score); + const metricStatus = result.passed ? "passed" : "failed"; + appendOutput("info", `${metric.name}: ${score} (${metricStatus})`); + }, + onReset(targetHash) { + appendOutput("info", `Reset to ${targetHash.slice(0, 7)}`); + }, + onExperimentComplete(index, entry) { + iterations = Math.max(iterations, index); + appendOutput( + entry.status === "keep" ? "success" : "error", + `Experiment ${index} ${entry.status} in ${formatDashboardDuration(entry.durationMs)} · scores: ${formatExperimentScores(entry.scores)}` + ); + syncStats(); + } + }; + const result = await runExperimentWithIntegrations(options.integrations, options.docPath, { ...runOptions, ...mergeExperimentCallbacks(runOptions, options.integrations?.experimentCallbacks) - } - ); + }); - status = "done"; - iterations = result.experimentsCompleted; - syncStats(); - return result; + status = "done"; + iterations = result.experimentsCompleted; + syncStats(); + return result; + } finally { + await session?.close(); + } } catch (error) { status = "error"; currentAction = undefined; @@ -461,8 +517,50 @@ async function runExperimentWithIntegrations( name: string, options: Parameters[0] ): Promise>> { - return integrations?.traceRun("experiment", name, () => sdkRunExperiment(options)) ?? - sdkRunExperiment(options); + return ( + integrations?.traceRun("experiment", name, () => sdkRunExperiment(options)) ?? + sdkRunExperiment(options) + ); +} + +async function runExperimentWithCliSession(options: { + agent: string | string[]; + cwd: string; + homeDir: string; + docPath: string; + runOptions: Parameters[0]; + runtimeOptions: RuntimeCliOptions; + integrations: Integrations | null; +}): Promise>> { + if (!options.integrations?.spawnMiddleware || options.runtimeOptions.detach === true) { + return await runExperimentWithIntegrations(options.integrations, options.docPath, { + ...options.runOptions, + ...mergeExperimentCallbacks(options.runOptions, options.integrations?.experimentCallbacks) + }); + } + + const session = createExperimentSpawnSession({ + agent: options.agent, + cwd: options.cwd, + homeDir: options.homeDir, + runtimeOptions: options.runtimeOptions, + ...(options.integrations.spawnMiddleware + ? { middlewares: [options.integrations.spawnMiddleware] } + : {}) + }); + + try { + const runOptions = { + ...options.runOptions, + runAgent: createExperimentCliRunAgent({ session }) + }; + return await runExperimentWithIntegrations(options.integrations, options.docPath, { + ...runOptions, + ...mergeExperimentCallbacks(runOptions, options.integrations?.experimentCallbacks) + }); + } finally { + await session.close(); + } } function resolveExperimentAgent(value: string | undefined, sourceLabel = "agent"): string { @@ -679,131 +777,127 @@ export function registerExperimentCommand(program: Command, container: CliContai .option("--tui", "Show a live dashboard while the experiment is running") .option("--no-tui", "Disable the live dashboard for this experiment run"); - addRuntimeOptions(run) - .action(async function (this: Command, docArg?: string) { - const flags = resolveCommandFlags(program); - const resources = createExecutionResources(container, flags, "experiment:run"); - const options = this.opts<{ + addRuntimeOptions(run).action(async function (this: Command, docArg?: string) { + const flags = resolveCommandFlags(program); + const resources = createExecutionResources(container, flags, "experiment:run"); + const options = this.opts< + { agent?: string; maxExperiments?: string; tui?: boolean; - } & RuntimeCliOptions>(); - const runtimeOptions = pickRuntimeOptions(options); + } & RuntimeCliOptions + >(); + const runtimeOptions = pickRuntimeOptions(options); - resources.logger.intro("experiment run"); + resources.logger.intro("experiment run"); - let integrations: Integrations | null = null; - try { - const commandConfig = await resolveExperimentCommandConfig(container); - integrations = await loadIntegrations(commandConfig.configDoc); - const docPath = await resolveDocPath({ - container, - program, - providedDoc: docArg, - planDirectory: commandConfig.planDirectory, - selectMessage: "Select the experiment doc to run:", - cancelMessage: "Experiment run cancelled." - }); - if (!docPath) { - return; - } + let integrations: Integrations | null = null; + try { + const commandConfig = await resolveExperimentCommandConfig(container); + integrations = await loadIntegrations(commandConfig.configDoc); + const docPath = await resolveDocPath({ + container, + program, + providedDoc: docArg, + planDirectory: commandConfig.planDirectory, + selectMessage: "Select the experiment doc to run:", + cancelMessage: "Experiment run cancelled." + }); + if (!docPath) { + return; + } - const doc = await readExperimentDoc(container, docPath); - const agent = await resolveRunAgent({ - container, - program, - providedAgent: options.agent, - frontmatterAgent: doc.frontmatter.agent - }); - if (!agent) { - return; - } + const doc = await readExperimentDoc(container, docPath); + const agent = await resolveRunAgent({ + container, + program, + providedAgent: options.agent, + frontmatterAgent: doc.frontmatter.agent + }); + if (!agent) { + return; + } - const maxExperiments = parseNonNegativeInt(options.maxExperiments, "max-experiments"); - const runOptions: Parameters[0] = { - agent, - cwd: container.env.cwd, - homeDir: container.env.homeDir, - docPath, - ...runtimeOptions, - ...(maxExperiments !== undefined ? { maxExperiments } : {}), - onExperimentStart(index, currentAgent) { - resources.logger.info(`Experiment ${index} (${currentAgent})`); - }, - onBaselineCollected(baseline) { - const entries = Object.entries(baseline) - .map(([name, value]) => `${name}=${value}`) - .join(", "); - resources.logger.info(`Baseline collected: ${entries}`); - }, - onCommit(commitHash) { - resources.logger.info(` Committed ${commitHash.slice(0, 7)}`); - }, - onMetricResult(metric, result) { - const score = result.score === null ? "-" : String(result.score); - const status = result.passed ? "passed" : "failed"; - resources.logger.info(` ${metric.name}: ${score} (${status})`); - }, - onReset(targetHash) { - resources.logger.info(` Reset to ${targetHash.slice(0, 7)}`); - }, - onExperimentComplete(index, entry) { - const scores = entry.scores - ? Object.entries(entry.scores) - .map(([k, v]) => `${k}=${v}`) - .join(", ") - : "-"; - resources.logger.info( - `Experiment ${index} ${entry.status} in ${formatDashboardDuration(entry.durationMs)} · scores: ${scores}` - ); - } - }; - if (integrations?.spawnMiddleware) { - runOptions.runAgent = createExperimentCliRunAgent({ + const maxExperiments = parseNonNegativeInt(options.maxExperiments, "max-experiments"); + const runOptions: Parameters[0] = { + agent, + cwd: container.env.cwd, + homeDir: container.env.homeDir, + docPath, + ...runtimeOptions, + ...(maxExperiments !== undefined ? { maxExperiments } : {}), + onExperimentStart(index, currentAgent) { + resources.logger.info(`Experiment ${index} (${currentAgent})`); + }, + onBaselineCollected(baseline) { + const entries = Object.entries(baseline) + .map(([name, value]) => `${name}=${value}`) + .join(", "); + resources.logger.info(`Baseline collected: ${entries}`); + }, + onCommit(commitHash) { + resources.logger.info(` Committed ${commitHash.slice(0, 7)}`); + }, + onMetricResult(metric, result) { + const score = result.score === null ? "-" : String(result.score); + const status = result.passed ? "passed" : "failed"; + resources.logger.info(` ${metric.name}: ${score} (${status})`); + }, + onReset(targetHash) { + resources.logger.info(` Reset to ${targetHash.slice(0, 7)}`); + }, + onExperimentComplete(index, entry) { + const scores = entry.scores + ? Object.entries(entry.scores) + .map(([k, v]) => `${k}=${v}`) + .join(", ") + : "-"; + resources.logger.info( + `Experiment ${index} ${entry.status} in ${formatDashboardDuration(entry.durationMs)} · scores: ${scores}` + ); + } + }; + const useDashboard = shouldUseInteractiveDashboard(options.tui ?? commandConfig.tui); + const result = useDashboard + ? await runExperimentWithDashboard({ + agent, + docPath, + maxExperiments, + runOptions, + runtimeOptions, + ...(integrations ? { integrations } : {}) + }) + : await runExperimentWithCliSession({ + agent, + cwd: container.env.cwd, + homeDir: container.env.homeDir, + docPath, + runOptions, runtimeOptions, - middlewares: [integrations.spawnMiddleware] + integrations }); - } - const useDashboard = shouldUseInteractiveDashboard(options.tui ?? commandConfig.tui); - const result = useDashboard - ? await runExperimentWithDashboard({ - agent, - docPath, - maxExperiments, - runOptions, - runtimeOptions, - ...(integrations ? { integrations } : {}) - }) - : await runExperimentWithIntegrations( - integrations, - docPath, - { - ...runOptions, - ...mergeExperimentCallbacks(runOptions, integrations?.experimentCallbacks) - } - ); - - const summary = [ - `Experiments: ${result.experimentsCompleted}`, - `Kept: ${result.experimentsKept}`, - `Doc: ${result.docPath}`, - `Duration: ${formatDashboardDuration(result.totalDurationMs)}` - ].join("\n "); - - if (result.stopReason === "cancelled") { - process.exitCode = 130; - resources.logger.warn("Experiment run cancelled."); - resources.logger.resolved("Run summary", summary); - return; - } + const summary = [ + `Experiments: ${result.experimentsCompleted}`, + `Kept: ${result.experimentsKept}`, + `Doc: ${result.docPath}`, + `Duration: ${formatDashboardDuration(result.totalDurationMs)}` + ].join("\n "); + + if (result.stopReason === "cancelled") { + process.exitCode = 130; + resources.logger.warn("Experiment run cancelled."); resources.logger.resolved("Run summary", summary); - resources.logger.success("Experiment run finished."); - } finally { - await integrations?.shutdown(); - resources.context.finalize(); + return; } - }); + + resources.logger.resolved("Run summary", summary); + resources.logger.success("Experiment run finished."); + } finally { + await integrations?.shutdown(); + resources.context.finalize(); + } + }); const journalCommand = experiment .command("journal") diff --git a/src/cli/commands/pipeline-command.test.ts b/src/cli/commands/pipeline-command.test.ts index c889434960..1566f3900d 100644 --- a/src/cli/commands/pipeline-command.test.ts +++ b/src/cli/commands/pipeline-command.test.ts @@ -38,8 +38,12 @@ vi.mock("../../sdk/pipeline.js", () => ({ }) })); -vi.mock("../../sdk/spawn.js", () => ({ - spawn: vi.fn() +vi.mock("../../sdk/spawn-session.js", () => ({ + createSpawnSession: vi.fn(() => ({ + run: vi.fn().mockResolvedValue({ stdout: "", stderr: "", exitCode: 0 }), + syncBack: vi.fn().mockResolvedValue({ files: 0, bytes: 0, conflicts: [] }), + close: vi.fn().mockResolvedValue(undefined) + })) })); vi.mock("@poe-code/agent-spawn", async (importOriginal) => { @@ -67,7 +71,7 @@ vi.mock("./pipeline-loop-agent.js", () => ({ import { runPipeline as sdkRunPipeline } from "../../sdk/pipeline.js"; import { runPipelineInit as sdkRunPipelineInit } from "../../sdk/pipeline.js"; -import { spawn as sdkSpawn } from "../../sdk/spawn.js"; +import { createSpawnSession } from "../../sdk/spawn-session.js"; import { createDashboard, withOutputFormat } from "@poe-code/design-system"; resolvePipelineLoopAgentMock.mockImplementation(resolveLoopAgent); @@ -331,6 +335,125 @@ describe("pipeline run command", () => { vi.doUnmock("@poe-code/braintrust"); }); + it("runs the non-dashboard integration agent through one deferred-sync spawn session", async () => { + const spawnMiddleware = vi.fn(async (_ctx, next: () => Promise) => { + await next(); + }); + vi.doMock("@poe-code/braintrust", () => ({ + bootstrap: vi.fn(async () => ({ + spawnMiddleware, + traceRun: async (_surface: string, _name: string, fn: () => Promise) => fn(), + shutdown: vi.fn(async () => undefined) + })) + })); + + const run = vi.fn().mockResolvedValue({ + stdout: "done", + stderr: "", + exitCode: 0 + }); + const syncBack = vi.fn().mockResolvedValue({ files: 0, bytes: 0, conflicts: [] }); + const close = vi.fn().mockResolvedValue(undefined); + vi.mocked(createSpawnSession).mockReturnValueOnce({ run, syncBack, close }); + vi.mocked(sdkRunPipeline).mockImplementationOnce(async (options) => { + await options.runAgent?.({ + agent: "codex", + prompt: "Ship it.", + cwd, + mode: "yolo", + model: "gpt-5.2" + }); + await options.runAgent?.({ + agent: "codex", + prompt: "Verify it.", + cwd, + mode: "read" + }); + + return { + stopReason: "completed", + planPath: "custom-plan.yaml", + runsCompleted: 2, + totalDurationMs: 1_000, + metrics: { + totalInputTokens: 0, + totalOutputTokens: 0, + totalCachedTokens: 0, + tasksCompleted: 1, + tasksFailed: 0, + stepsCompleted: 2 + } + }; + }); + + try { + const fs = createMemFs({ + [`${homeDir}/.poe-code/config.json`]: JSON.stringify({ + integrations: { + braintrust: { + enabled: true, + apiKey: "key", + project: "project" + } + } + }), + "/repo/custom-plan.yaml": "tasks: []\n" + }); + const container = createCliContainer({ + fs, + prompts: vi.fn().mockResolvedValue({}), + env: { cwd, homeDir }, + logger: () => {} + }); + const program = createBaseProgram(); + registerPipelineCommand(program, container); + + await program.parseAsync([ + "node", + "cli", + "--yes", + "pipeline", + "run", + "--plan", + "custom-plan.yaml", + "--agent", + "codex", + "--model", + "gpt-5.2", + "--no-tui" + ]); + + expect(createSpawnSession).toHaveBeenCalledWith( + expect.objectContaining({ + service: "codex", + cwd, + model: "gpt-5.2", + middlewares: [spawnMiddleware] + }) + ); + expect(run).toHaveBeenNthCalledWith(1, { + agent: "codex", + prompt: "Ship it.", + cwd, + mode: "yolo", + model: "gpt-5.2", + syncBack: false + }); + expect(run).toHaveBeenNthCalledWith(2, { + agent: "codex", + prompt: "Verify it.", + cwd, + mode: "read", + syncBack: false + }); + expect(syncBack).toHaveBeenCalledTimes(1); + expect(syncBack).toHaveBeenCalledBefore(close); + expect(close).toHaveBeenCalledTimes(1); + } finally { + vi.doUnmock("@poe-code/braintrust"); + } + }); + it("reads plan.plan_directory for pipeline discovery", async () => { const fs = createMemFs(); await fs.mkdir(`${homeDir}/.poe-code`, { recursive: true }); @@ -537,12 +660,8 @@ describe("pipeline run command", () => { expect( logs.some((message) => message.includes("Total tokens: 5000 input, 2000 output, 1000 cached")) ).toBe(true); - expect( - logs.some((message) => message.includes("Tasks: 1 completed, 0 failed")) - ).toBe(true); - expect( - logs.some((message) => message.includes("Steps: 1 completed")) - ).toBe(true); + expect(logs.some((message) => message.includes("Tasks: 1 completed, 0 failed"))).toBe(true); + expect(logs.some((message) => message.includes("Steps: 1 completed"))).toBe(true); }); it("reports pipeline failures without blocked retry messaging", async () => { @@ -1159,10 +1278,12 @@ describe("pipeline run command", () => { const dashboardMock = createDashboardMock(); vi.mocked(createDashboard).mockReturnValueOnce(dashboardMock.dashboard); - vi.mocked(sdkSpawn).mockImplementationOnce((_agent, input) => { - input.tee?.stdout?.write("Inspecting repo"); - input.tee?.stdout?.write("...\nsecond line\npartial"); - input.tee?.stderr?.write("Tool warning\npartial stderr"); + const run = vi.fn((input, options) => { + expect(options).toEqual({ streaming: true }); + const tee = vi.mocked(createSpawnSession).mock.calls[0]?.[0].tee; + tee?.stdout?.write("Inspecting repo"); + tee?.stdout?.write("...\nsecond line\npartial"); + tee?.stderr?.write("Tool warning\npartial stderr"); return { events: (async function* () {})(), @@ -1177,6 +1298,9 @@ describe("pipeline run command", () => { }) }; }); + const syncBack = vi.fn().mockResolvedValue({ files: 0, bytes: 0, conflicts: [] }); + const close = vi.fn().mockResolvedValue(undefined); + vi.mocked(createSpawnSession).mockReturnValueOnce({ run, syncBack, close }); vi.mocked(sdkRunPipeline).mockImplementationOnce(async (options) => { options.onTaskStart?.({ @@ -1194,6 +1318,16 @@ describe("pipeline run command", () => { prompt: "Inspect the repo", mode: "yolo", cwd, + logDir: "/repo/.poe-code/pipeline/logs", + logFileName: "auth-hardening-implement.jsonl", + model: "gpt-5.2", + signal: options.signal + }); + await options.runAgent?.({ + agent: "codex", + prompt: "Check status", + mode: "read", + cwd, model: "gpt-5.2", signal: options.signal }); @@ -1258,20 +1392,47 @@ describe("pipeline run command", () => { ]) ); - expect(vi.mocked(sdkSpawn)).toHaveBeenCalledWith( - "codex", + expect(createSpawnSession).toHaveBeenCalledWith( expect.objectContaining({ - prompt: "Inspect the repo", + service: "codex", cwd, model: "gpt-5.2", - mode: "yolo", - signal: expect.any(AbortSignal), tee: expect.objectContaining({ stdout: expect.any(Object), stderr: expect.any(Object) }) }) ); + expect(run).toHaveBeenCalledWith( + { + agent: "codex", + prompt: "Inspect the repo", + cwd, + logDir: "/repo/.poe-code/pipeline/logs", + logFileName: "auth-hardening-implement.jsonl", + model: "gpt-5.2", + mode: "yolo", + signal: expect.any(AbortSignal), + syncBack: false + }, + { streaming: true } + ); + expect(run).toHaveBeenNthCalledWith( + 2, + { + agent: "codex", + prompt: "Check status", + cwd, + model: "gpt-5.2", + mode: "read", + signal: expect.any(AbortSignal), + syncBack: false + }, + { streaming: true } + ); + expect(syncBack).toHaveBeenCalledTimes(1); + expect(close).toHaveBeenCalledTimes(1); + expect(syncBack).toHaveBeenCalledBefore(close); const outputs = dashboardMock.appendOutput.mock.calls.map(([item]) => item); expect( @@ -1316,9 +1477,11 @@ describe("pipeline run command", () => { const timeoutError = new Error("Timed out waiting for agent activity for 600000ms."); timeoutError.name = "ActivityTimeoutError"; - vi.mocked(sdkSpawn) - .mockImplementationOnce((_agent, input) => { - input.tee?.stdout?.write("first attempt output\n"); + const run = vi + .fn() + .mockImplementationOnce(() => { + const tee = vi.mocked(createSpawnSession).mock.calls[0]?.[0].tee; + tee?.stdout?.write("first attempt output\n"); return { events: (async function* () {})(), @@ -1337,6 +1500,9 @@ describe("pipeline run command", () => { } }) })); + const syncBack = vi.fn().mockResolvedValue({ files: 0, bytes: 0, conflicts: [] }); + const close = vi.fn().mockResolvedValue(undefined); + vi.mocked(createSpawnSession).mockReturnValueOnce({ run, syncBack, close }); vi.mocked(sdkRunPipeline).mockImplementationOnce(async (options) => { options.onTaskStart?.({ @@ -1354,6 +1520,8 @@ describe("pipeline run command", () => { prompt: "Inspect the repo", mode: "yolo", cwd, + logDir: "/repo/.poe-code/pipeline/logs", + logFileName: "auth-hardening-implement.jsonl", model: "gpt-5.2", signal: options.signal }); @@ -1418,7 +1586,7 @@ describe("pipeline run command", () => { ]) ); - expect(vi.mocked(sdkSpawn)).toHaveBeenCalledTimes(2); + expect(run).toHaveBeenCalledTimes(2); const outputs = dashboardMock.appendOutput.mock.calls.map(([item]) => item); expect( @@ -1479,15 +1647,7 @@ describe("pipeline init command", () => { const program = createBaseProgram(); registerPipelineCommand(program, container); - await expect( - program.parseAsync([ - "node", - "cli", - "--yes", - "pipeline", - "init" - ]) - ).rejects.toEqual( + await expect(program.parseAsync(["node", "cli", "--yes", "pipeline", "init"])).rejects.toEqual( new ValidationError("Provide --source or --sources when using --yes.") ); }); @@ -1565,9 +1725,13 @@ describe("pipeline init command", () => { }) ); expect(logs.some((message) => message.includes("Source 1/2: docs/plans/alpha.md"))).toBe(true); - expect(logs.some((message) => message.includes("Completed 1/2: docs/plans/alpha.md"))).toBe(true); + expect(logs.some((message) => message.includes("Completed 1/2: docs/plans/alpha.md"))).toBe( + true + ); expect(logs.some((message) => message.includes("Source 2/2: docs/plans/beta.md"))).toBe(true); - expect(logs.some((message) => message.includes("Completed 2/2: docs/plans/beta.md"))).toBe(true); + expect(logs.some((message) => message.includes("Completed 2/2: docs/plans/beta.md"))).toBe( + true + ); expect(logs.some((message) => message.includes("Pipeline init finished."))).toBe(true); }); diff --git a/src/cli/commands/pipeline.ts b/src/cli/commands/pipeline.ts index 70aa0a9513..95eadd250c 100644 --- a/src/cli/commands/pipeline.ts +++ b/src/cli/commands/pipeline.ts @@ -19,11 +19,7 @@ import { } from "@poe-code/agent-defs"; import { renderAcpEvent, type AcpEvent, type AcpMiddleware } from "@poe-code/agent-spawn"; import { skillPlanConfigSection } from "@poe-code/agent-harness-tools"; -import { - installSkill, - resolveAgentSupport, - type SkillScope -} from "@poe-code/agent-skill-config"; +import { installSkill, resolveAgentSupport, type SkillScope } from "@poe-code/agent-skill-config"; import { loadIntegrations, mergePipelineCallbacks, @@ -49,7 +45,7 @@ import { type PlanSummary, type TaskProgress } from "../../sdk/pipeline.js"; -import { spawn as sdkSpawn } from "../../sdk/spawn.js"; +import { createSpawnSession, type SpawnSession } from "../../sdk/spawn-session.js"; import { buildExecutionPrompt, interpolatePipelineVars, @@ -77,11 +73,7 @@ async function resolvePipelineCommandConfig(container: CliContainer): Promise<{ tui: boolean; }> { const [configDoc, pipelineYamlConfig] = await Promise.all([ - readMergedDocument( - container.fs, - container.env.configPath, - container.env.projectConfigPath - ), + readMergedDocument(container.fs, container.env.configPath, container.env.projectConfigPath), loadPipelineConfig({ cwd: container.env.cwd, homeDir: container.env.homeDir, @@ -360,9 +352,10 @@ async function streamAcpEventsToDashboard(options: { } function createPipelineDashboardRunAgent(options: { + session: SpawnSession; appendOutput: (kind: "tool" | "error", message: string) => void; activeStage: () => string; - middlewares?: AcpMiddleware[]; + teeTarget: PipelineDashboardTeeTarget; }): NonNullable { return async (input) => { const toolBuffer = createDashboardLineBuffer((line) => { @@ -371,93 +364,149 @@ function createPipelineDashboardRunAgent(options: { const errorBuffer = createDashboardLineBuffer((line) => { options.appendOutput("error", `[${options.activeStage()}] ${line}`); }); - let lastError: unknown; - for (let attempt = 0; attempt < PIPELINE_ACTIVITY_TIMEOUT_RETRY_COUNT; attempt++) { - let sawStdout = false; - let sawStderr = false; + options.teeTarget.tool = toolBuffer; + options.teeTarget.error = errorBuffer; + try { + let lastError: unknown; + for (let attempt = 0; attempt < PIPELINE_ACTIVITY_TIMEOUT_RETRY_COUNT; attempt++) { + options.teeTarget.sawStdout = false; + options.teeTarget.sawStderr = false; + let sawStdout = false; + let sawStderr = false; + + try { + const { events, result } = options.session.run( + { + agent: input.agent, + prompt: input.prompt, + cwd: input.cwd, + mode: input.mode, + ...(input.logDir ? { logDir: input.logDir } : {}), + ...(input.logFileName ? { logFileName: input.logFileName } : {}), + ...(input.model ? { model: input.model } : {}), + ...(input.mcpServers ? { mcpServers: input.mcpServers } : {}), + ...(input.signal ? { signal: input.signal } : {}), + syncBack: false + }, + { streaming: true } + ); - try { - const { events, result } = sdkSpawn(input.agent, { - prompt: input.prompt, - cwd: input.cwd, - logDir: input.logDir, - model: input.model, - mode: input.mode, - ...(input.mcpServers ? { mcpServers: input.mcpServers } : {}), - ...(input.signal ? { signal: input.signal } : {}), - ...(options.middlewares ? { middlewares: options.middlewares } : {}), - tee: { - stdout: { - write(chunk: string) { - sawStdout = true; - toolBuffer.push(chunk); - } + const eventStream = streamAcpEventsToDashboard({ + events, + onToolOutput(chunk) { + toolBuffer.push(chunk); }, - stderr: { - write(chunk: string) { - sawStderr = true; - errorBuffer.push(chunk); - } + onErrorOutput(chunk) { + errorBuffer.push(chunk); } - }, - activityTimeoutMs: 10 * 60 * 1000 - }); - - const eventStream = streamAcpEventsToDashboard({ - events, - onToolOutput(chunk) { - toolBuffer.push(chunk); - }, - onErrorOutput(chunk) { - errorBuffer.push(chunk); - } - }); + }); - const [spawnResult, sawEvents] = await Promise.all([result, eventStream]); + const [spawnResult, sawEvents] = await Promise.all([result, eventStream]); + sawStdout = options.teeTarget.sawStdout; + sawStderr = options.teeTarget.sawStderr; - if (!sawEvents && !sawStdout && spawnResult.stdout.length > 0) { - toolBuffer.push(spawnResult.stdout); - } + if (!sawEvents && !sawStdout && spawnResult.stdout.length > 0) { + toolBuffer.push(spawnResult.stdout); + } - if (!sawStderr && spawnResult.stderr.length > 0) { - errorBuffer.push(spawnResult.stderr); - } + if (!sawStderr && spawnResult.stderr.length > 0) { + errorBuffer.push(spawnResult.stderr); + } - toolBuffer.flush(); - errorBuffer.flush(); - return spawnResult; - } catch (error) { - if (!isActivityTimeoutError(error)) { toolBuffer.flush(); errorBuffer.flush(); - throw error; + return spawnResult; + } catch (error) { + if (!isActivityTimeoutError(error)) { + toolBuffer.flush(); + errorBuffer.flush(); + throw error; + } + lastError = error; } - lastError = error; } - } - toolBuffer.flush(); - errorBuffer.flush(); - throw lastError; + toolBuffer.flush(); + errorBuffer.flush(); + throw lastError; + } finally { + options.teeTarget.tool = undefined; + options.teeTarget.error = undefined; + options.teeTarget.sawStdout = false; + options.teeTarget.sawStderr = false; + } }; } function createPipelineCliRunAgent( - middlewares: AcpMiddleware[] + session: SpawnSession ): NonNullable { return async (input) => - sdkSpawn.autonomous(input.agent, { + await session.run({ + agent: input.agent, prompt: input.prompt, cwd: input.cwd, - logDir: input.logDir, - model: input.model, mode: input.mode, + ...(input.logDir ? { logDir: input.logDir } : {}), + ...(input.logFileName ? { logFileName: input.logFileName } : {}), + ...(input.model ? { model: input.model } : {}), ...(input.mcpServers ? { mcpServers: input.mcpServers } : {}), ...(input.signal ? { signal: input.signal } : {}), - middlewares + syncBack: false }); } +type PipelineDashboardTeeTarget = { + tool?: ReturnType; + error?: ReturnType; + sawStdout: boolean; + sawStderr: boolean; +}; + +function createPipelineDashboardSpawnSession(options: { + agent: string; + model?: string; + cwd: string; + middlewares?: AcpMiddleware[]; + teeTarget: PipelineDashboardTeeTarget; +}): SpawnSession { + return createSpawnSession({ + service: options.agent, + cwd: options.cwd, + ...(options.model ? { model: options.model } : {}), + ...(options.middlewares ? { middlewares: options.middlewares } : {}), + activityTimeoutMs: 10 * 60 * 1000, + tee: { + stdout: { + write(chunk: string) { + options.teeTarget.sawStdout = true; + options.teeTarget.tool?.push(chunk); + } + }, + stderr: { + write(chunk: string) { + options.teeTarget.sawStderr = true; + options.teeTarget.error?.push(chunk); + } + } + } + }); +} + +function createPipelineCliSpawnSession(options: { + agent: string; + model?: string; + cwd: string; + middlewares: AcpMiddleware[]; +}): SpawnSession { + return createSpawnSession({ + service: options.agent, + cwd: options.cwd, + ...(options.model ? { model: options.model } : {}), + middlewares: options.middlewares + }); +} + function dashboardStatusForResult(result: PipelineRunResult): "done" | "error" { return result.stopReason === "failed" ? "error" : "done"; } @@ -536,15 +585,28 @@ async function runPipelineWithDashboard( }; process.on("SIGINT", sigintHandler); + const teeTarget: PipelineDashboardTeeTarget = { + sawStdout: false, + sawStderr: false + }; + const session = createPipelineDashboardSpawnSession({ + agent: options.agent, + cwd: options.runOptions.cwd, + ...(options.model ? { model: options.model } : {}), + ...(options.integrations?.spawnMiddleware + ? { middlewares: [options.integrations.spawnMiddleware] } + : {}), + teeTarget + }); + try { const runOptions: PipelineRunOptions = { ...options.runOptions, runAgent: createPipelineDashboardRunAgent({ + session, appendOutput, activeStage: () => currentStage, - ...(options.integrations?.spawnMiddleware - ? { middlewares: [options.integrations.spawnMiddleware] } - : {}) + teeTarget }), signal: abortController.signal, onPlanReloadError(error: Error) { @@ -593,14 +655,10 @@ async function runPipelineWithDashboard( syncStats(); } }; - const result = await runPipelineWithIntegrations( - options.integrations, - options.planPath, - { - ...runOptions, - ...mergePipelineCallbacks(runOptions, options.integrations?.pipelineCallbacks) - } - ); + const result = await runPipelineWithIntegrations(options.integrations, options.planPath, { + ...runOptions, + ...mergePipelineCallbacks(runOptions, options.integrations?.pipelineCallbacks) + }); status = dashboardStatusForResult(result); syncStats(); @@ -612,10 +670,18 @@ async function runPipelineWithDashboard( syncStats(); throw error; } finally { - global.clearInterval(intervalId); - process.off("SIGINT", sigintHandler); - dashboard.stop(); - dashboard.destroy(); + try { + try { + await session.syncBack(); + } finally { + await session.close(); + } + } finally { + global.clearInterval(intervalId); + process.off("SIGINT", sigintHandler); + dashboard.stop(); + dashboard.destroy(); + } } } @@ -624,8 +690,10 @@ async function runPipelineWithIntegrations( name: string, options: PipelineRunOptions ): Promise { - return integrations?.traceRun("pipeline", name, () => sdkRunPipeline(options)) ?? - sdkRunPipeline(options); + return ( + integrations?.traceRun("pipeline", name, () => sdkRunPipeline(options)) ?? + sdkRunPipeline(options) + ); } function resolvePipelinePaths( @@ -758,11 +826,7 @@ export function registerPipelineCommand(program: Command, container: CliContaine dryRun?: boolean; }>(); const dryRun = flags.dryRun || Boolean(options.dryRun); - const resources = createExecutionResources( - container, - { ...flags, dryRun }, - "pipeline:run" - ); + const resources = createExecutionResources(container, { ...flags, dryRun }, "pipeline:run"); resources.logger.intro("pipeline run"); @@ -853,60 +917,76 @@ export function registerPipelineCommand(program: Command, container: CliContaine ...(dryRun ? { dryRun: true } : {}), assumeYes: flags.assumeYes }; - if (integrations?.spawnMiddleware) { - runOptions.runAgent = createPipelineCliRunAgent([integrations.spawnMiddleware]); - } const useDashboard = shouldUseInteractiveDashboard(options.tui ?? commandConfig.tui); - const result = useDashboard - ? await runPipelineWithDashboard({ - agent, - ...(options.model ? { model: options.model } : {}), - planPath, - planIndex: index, - totalPlans, - runOptions, - ...(integrations ? { integrations } : {}) - }) - : await runPipelineWithIntegrations( - integrations, - planPath, - { - ...runOptions, - onPlanReloadError(error: Error) { - resources.logger.warn( - `Plan reload failed, using last good state: ${error.message}` - ); - }, - ...mergePipelineCallbacks( - { - onLockStatusChange(lockStatus: PipelineLockStatus) { - resources.logger.info(lockStatus.message); - }, - onPlanResolved(summary: PlanSummary) { - resources.logger.resolved( - "Config", - formatPipelineConfigSummary({ - agent, - model: options.model, - planPath: summary.planPath, - planIndex: index, - totalPlans - }).replaceAll(" · ", "\n ") - ); - resources.logger.resolved("Tasks", formatPipelineTasksSummary(summary)); - }, - onTaskStart(progress: TaskProgress) { - resources.logger.info(formatTaskStartMessage(progress)); - }, - onTaskComplete(progress: TaskCompletion) { - resources.logger.info(formatTaskCompleteMessage(progress)); - } + let cliSession: SpawnSession | null = null; + if (!useDashboard && integrations?.spawnMiddleware) { + cliSession = createPipelineCliSpawnSession({ + agent, + cwd: container.env.cwd, + ...(options.model ? { model: options.model } : {}), + middlewares: [integrations.spawnMiddleware] + }); + runOptions.runAgent = createPipelineCliRunAgent(cliSession); + } + + const result = await (async () => { + try { + return useDashboard + ? await runPipelineWithDashboard({ + agent, + ...(options.model ? { model: options.model } : {}), + planPath, + planIndex: index, + totalPlans, + runOptions, + ...(integrations ? { integrations } : {}) + }) + : await runPipelineWithIntegrations(integrations, planPath, { + ...runOptions, + onPlanReloadError(error: Error) { + resources.logger.warn( + `Plan reload failed, using last good state: ${error.message}` + ); }, - integrations?.pipelineCallbacks - ) + ...mergePipelineCallbacks( + { + onLockStatusChange(lockStatus: PipelineLockStatus) { + resources.logger.info(lockStatus.message); + }, + onPlanResolved(summary: PlanSummary) { + resources.logger.resolved( + "Config", + formatPipelineConfigSummary({ + agent, + model: options.model, + planPath: summary.planPath, + planIndex: index, + totalPlans + }).replaceAll(" · ", "\n ") + ); + resources.logger.resolved("Tasks", formatPipelineTasksSummary(summary)); + }, + onTaskStart(progress: TaskProgress) { + resources.logger.info(formatTaskStartMessage(progress)); + }, + onTaskComplete(progress: TaskCompletion) { + resources.logger.info(formatTaskCompleteMessage(progress)); + } + }, + integrations?.pipelineCallbacks + ) + }); + } finally { + if (cliSession) { + try { + await cliSession.syncBack(); + } finally { + await cliSession.close(); } - ); + } + } + })(); const summary = formatRunSummary(result); @@ -1305,7 +1385,10 @@ export function registerPipelineCommand(program: Command, container: CliContaine } } - const legacyDefaultStepsExists = await pathExists(container.fs, pipelinePaths.legacyDefaultStepsPath); + const legacyDefaultStepsExists = await pathExists( + container.fs, + pipelinePaths.legacyDefaultStepsPath + ); let stepsExists = await pathExists(container.fs, pipelinePaths.stepsPath); if (legacyDefaultStepsExists && !stepsExists) { @@ -1314,7 +1397,10 @@ export function registerPipelineCommand(program: Command, container: CliContaine `Would rename: ${pipelinePaths.displayStepsPath} (migrate from steps/default.yaml)` ); } else { - await container.fs.rename(pipelinePaths.legacyDefaultStepsPath, pipelinePaths.stepsPath); + await container.fs.rename( + pipelinePaths.legacyDefaultStepsPath, + pipelinePaths.stepsPath + ); resources.logger.info( `Rename: steps/default.yaml -> ${pipelinePaths.displayStepsPath}` ); diff --git a/src/cli/commands/ralph.ts b/src/cli/commands/ralph.ts index c9a329d717..d46b4f1aab 100644 --- a/src/cli/commands/ralph.ts +++ b/src/cli/commands/ralph.ts @@ -33,6 +33,7 @@ import { type RalphRunResult } from "../../sdk/ralph.js"; import { spawn as sdkSpawn } from "../../sdk/spawn.js"; +import { createSpawnSession, type SpawnSession } from "../../sdk/spawn-session.js"; import { createDashboardLineBuffer, formatDashboardDuration, @@ -58,6 +59,19 @@ type RalphDashboardRunOptions = { runtimeOptions: RuntimeCliOptions; }; +type RalphSessionOptions = { + agent: string | string[]; + cwd: string; + homeDir: string; + runtimeConfigCwd: string; + runtimeOptions: RuntimeCliOptions; + useStdin?: boolean; + tee?: { + stdout?: { write(chunk: string): void }; + stderr?: { write(chunk: string): void }; + }; +}; + function formatRalphAgentSummary(agent: string | string[]): string { return Array.isArray(agent) ? agent.join(", ") : agent; } @@ -132,6 +146,92 @@ function createRalphDashboardRunAgent(options: { }; } +function createRalphSessionDashboardRunAgent(options: { + session: SpawnSession; + appendOutput: (kind: "tool" | "error", message: string) => void; + activeStage: () => string; + flushErrors: () => void; +}): NonNullable { + return async (input) => { + try { + return await acp.withAcpWriter( + (line) => { + options.appendOutput("tool", `[${options.activeStage()}] ${line}`); + }, + async () => + await options.session.run({ + agent: input.agent, + prompt: input.prompt, + model: input.model, + cwd: input.cwd, + signal: input.signal, + syncBack: false + }) + ); + } finally { + options.flushErrors(); + } + }; +} + +function createRalphSessionRunAgent( + session: SpawnSession +): NonNullable { + return async (input) => + await session.run({ + agent: input.agent, + prompt: input.prompt, + model: input.model, + cwd: input.cwd, + signal: input.signal, + syncBack: false + }); +} + +function createRalphSessionFinalizer(session: SpawnSession): () => Promise { + let finished = false; + + return async () => { + if (finished) { + return; + } + + finished = true; + try { + await session.syncBack(); + } finally { + await session.close(); + } + }; +} + +function createRalphSpawnSession(options: RalphSessionOptions): SpawnSession { + const initialAgent = resolveInitialRalphAgent(options.agent); + + return createSpawnSession({ + service: initialAgent.agent, + cwd: options.cwd, + ...(initialAgent.model ? { model: initialAgent.model } : {}), + mode: "yolo", + ...options.runtimeOptions, + runtimeConfigCwd: options.runtimeConfigCwd, + ...(options.useStdin ? { useStdin: true } : {}), + ...(options.tee ? { tee: options.tee } : {}), + downloadConflict: "overwrite", + context: { + homeDir: options.homeDir + } + }); +} + +function resolveInitialRalphAgent(agent: string | string[]): { agent: string; model?: string } { + const specifier = parseAgentSpecifier(Array.isArray(agent) ? agent[0]! : agent); + return { + agent: specifier.agent, + ...(specifier.model ? { model: specifier.model } : {}) + }; +} + function dashboardStatusForResult(result: RalphRunResult): "done" | "error" { return result.stopReason === "failed" ? "error" : "done"; } @@ -205,34 +305,81 @@ async function runRalphWithDashboard(options: RalphDashboardRunOptions): Promise process.on("SIGINT", sigintHandler); try { - const result = await sdkRunRalph({ - ...options.runOptions, - runAgent: createRalphDashboardRunAgent({ - appendOutput, - activeStage: () => currentStage, - runtimeOptions: options.runtimeOptions - }), - signal: abortController.signal, - onIterationStart(iteration, totalIterations, currentAgent) { - currentStage = formatRalphStageLabel(iteration); - currentAction = formatRalphCurrentAction(iteration, totalIterations, currentAgent); - appendOutput("status", `Iteration ${iteration}/${totalIterations} (${currentAgent})`); - syncStats(); - }, - onIterationComplete(iteration, durationMs, success) { - iterations = Math.max(iterations, iteration); - appendOutput( - success ? "success" : "error", - `Iteration ${iteration} ${success ? "done" : "failed"} in ${formatDashboardDuration(durationMs)}` - ); - syncStats(); - } + const errorBuffer = createDashboardLineBuffer((line) => { + appendOutput("error", `[${currentStage}] ${line}`); }); + const session = + options.runOptions.detach === true + ? null + : createRalphSpawnSession({ + agent: options.agent, + cwd: options.cwd, + homeDir: options.runOptions.homeDir, + runtimeConfigCwd: options.runOptions.runtimeConfigCwd ?? options.cwd, + runtimeOptions: options.runtimeOptions, + useStdin: true, + tee: { + stderr: { + write(chunk: string) { + errorBuffer.push(chunk); + } + } + } + }); + const finishSession = session === null ? null : createRalphSessionFinalizer(session); - status = dashboardStatusForResult(result); - iterations = result.iterationsCompleted; - syncStats(); - return result; + try { + const result = await sdkRunRalph({ + ...options.runOptions, + ...(finishSession + ? { + prepareFinalWorkspace: async () => { + await options.runOptions.prepareFinalWorkspace?.(); + await finishSession(); + } + } + : {}), + runAgent: + session === null + ? createRalphDashboardRunAgent({ + appendOutput, + activeStage: () => currentStage, + runtimeOptions: options.runtimeOptions + }) + : createRalphSessionDashboardRunAgent({ + session, + appendOutput, + activeStage: () => currentStage, + flushErrors: () => { + errorBuffer.flush(); + } + }), + signal: abortController.signal, + onIterationStart(iteration, totalIterations, currentAgent) { + currentStage = formatRalphStageLabel(iteration); + currentAction = formatRalphCurrentAction(iteration, totalIterations, currentAgent); + appendOutput("status", `Iteration ${iteration}/${totalIterations} (${currentAgent})`); + syncStats(); + }, + onIterationComplete(iteration, durationMs, success) { + iterations = Math.max(iterations, iteration); + appendOutput( + success ? "success" : "error", + `Iteration ${iteration} ${success ? "done" : "failed"} in ${formatDashboardDuration(durationMs)}` + ); + syncStats(); + } + }); + + status = dashboardStatusForResult(result); + iterations = result.iterationsCompleted; + syncStats(); + return result; + } finally { + if (finishSession !== null) { + await finishSession(); + } + } } catch (error) { status = "error"; currentAction = undefined; @@ -749,6 +896,17 @@ export function registerRalphCommand(program: Command, container: CliContainer): ...runtimeOptions }; const useDashboard = shouldUseInteractiveDashboard(options.tui ?? commandConfig.tui); + const runCallbacks: Pick = { + onIterationStart(iteration, total, currentAgent) { + resources.logger.info(`Iteration ${iteration}/${total} (${currentAgent})`); + }, + onIterationComplete(iteration, durationMs, success) { + const status = success ? "done" : "failed"; + resources.logger.info( + `Iteration ${iteration} ${status} in ${formatDashboardDuration(durationMs)}` + ); + } + }; const result = useDashboard ? await runRalphWithDashboard({ agent, @@ -758,18 +916,35 @@ export function registerRalphCommand(program: Command, container: CliContainer): runOptions, runtimeOptions }) - : await sdkRunRalph({ - ...runOptions, - onIterationStart(iteration, total, currentAgent) { - resources.logger.info(`Iteration ${iteration}/${total} (${currentAgent})`); - }, - onIterationComplete(iteration, durationMs, success) { - const status = success ? "done" : "failed"; - resources.logger.info( - `Iteration ${iteration} ${status} in ${formatDashboardDuration(durationMs)}` - ); - } - }); + : runOptions.detach === true + ? await sdkRunRalph({ + ...runOptions, + ...runCallbacks + }) + : await (async () => { + const session = createRalphSpawnSession({ + agent, + cwd: runCwd, + homeDir: container.env.homeDir, + runtimeConfigCwd: container.env.cwd, + runtimeOptions + }); + const finishSession = createRalphSessionFinalizer(session); + + try { + return await sdkRunRalph({ + ...runOptions, + prepareFinalWorkspace: async () => { + await runOptions.prepareFinalWorkspace?.(); + await finishSession(); + }, + runAgent: createRalphSessionRunAgent(session), + ...runCallbacks + }); + } finally { + await finishSession(); + } + })(); const summary = [ `Iterations: ${result.iterationsCompleted}/${maxIterations}`, diff --git a/src/index.ts b/src/index.ts index e3cf11f698..2a2fbede53 100644 --- a/src/index.ts +++ b/src/index.ts @@ -4,6 +4,12 @@ import { pathToFileURL } from "node:url"; // SDK exports export { spawn } from "./sdk/spawn.js"; +export { + createSpawnSession, + type CreateSpawnSessionOptions, + type SpawnSession, + type SpawnSessionRunInput +} from "./sdk/spawn-session.js"; export { runPipeline, runPipelineInit } from "./sdk/pipeline.js"; export { createLogWriter, diff --git a/src/sdk/experiment.ts b/src/sdk/experiment.ts index 9f62047396..3c6fb7f166 100644 --- a/src/sdk/experiment.ts +++ b/src/sdk/experiment.ts @@ -9,6 +9,8 @@ import { type ExperimentRunResult, type JournalEntry } from "@poe-code/experiment-loop"; +import { parseAgentSpecifier } from "@poe-code/agent-defs"; +import { createSpawnSession, type SpawnSession } from "./spawn-session.js"; import { spawn as sdkSpawn } from "./spawn.js"; export type { @@ -67,26 +69,93 @@ function resolveJournalPath(docPath: string): string { } export async function runExperiment(options: ExperimentRunOptions): Promise { - return runWorkspaceExperimentLoop({ - ...options, - runAgent: async (input: Parameters>[0]) => { - return await sdkSpawn.autonomous(input.agent, { - prompt: input.prompt, - cwd: input.cwd, - model: input.model, - mode: "yolo", - ...(options.runtime ? { runtime: options.runtime } : {}), - ...(options.runtimeImage ? { runtimeImage: options.runtimeImage } : {}), - ...(options.runtimeTemplate ? { runtimeTemplate: options.runtimeTemplate } : {}), - ...(options.detach ? { detach: options.detach } : {}), - ...(options.mountPoeCode ? { mountPoeCode: options.mountPoeCode } : {}), - ...(options.runnerSync ? { runnerSync: options.runnerSync } : {}), - ...(input.signal ? { signal: input.signal } : {}) - }); + if (options.runAgent || options.detach === true) { + return await runWorkspaceExperimentLoop({ + ...options, + runAgent: options.runAgent ?? createDefaultExperimentRunAgent(options) + }); + } + + const session = createExperimentSpawnSession(options); + try { + return await runWorkspaceExperimentLoop({ + ...options, + runAgent: createSessionExperimentRunAgent(session) + }); + } finally { + await session.close(); + } +} + +function createDefaultExperimentRunAgent( + options: ExperimentRunOptions +): NonNullable { + return async (input) => + await sdkSpawn.autonomous(input.agent, { + prompt: input.prompt, + cwd: input.cwd, + model: input.model, + mode: "yolo", + ...(options.runtime ? { runtime: options.runtime } : {}), + ...(options.runtimeImage ? { runtimeImage: options.runtimeImage } : {}), + ...(options.runtimeTemplate ? { runtimeTemplate: options.runtimeTemplate } : {}), + ...(options.detach ? { detach: options.detach } : {}), + ...(options.mountPoeCode ? { mountPoeCode: options.mountPoeCode } : {}), + ...(options.runnerSync ? { runnerSync: options.runnerSync } : {}), + ...(input.signal ? { signal: input.signal } : {}) + }); +} + +function createExperimentSpawnSession(options: ExperimentRunOptions): SpawnSession { + const initialAgent = resolveInitialExperimentAgent( + options.agent, + (options as { model?: string }).model + ); + + return createSpawnSession({ + service: initialAgent.agent, + cwd: options.cwd, + ...(initialAgent.model ? { model: initialAgent.model } : {}), + mode: "yolo", + ...(options.runtime ? { runtime: options.runtime } : {}), + ...(options.runtimeImage ? { runtimeImage: options.runtimeImage } : {}), + ...(options.runtimeTemplate ? { runtimeTemplate: options.runtimeTemplate } : {}), + ...(options.mountPoeCode ? { mountPoeCode: options.mountPoeCode } : {}), + ...(options.runnerSync ? { runnerSync: options.runnerSync } : {}), + downloadConflict: "overwrite", + context: { + homeDir: options.homeDir } }); } +function createSessionExperimentRunAgent( + session: SpawnSession +): NonNullable { + return async (input) => + await session.run({ + agent: input.agent, + prompt: input.prompt, + cwd: input.cwd, + ...(input.model ? { model: input.model } : {}), + ...(input.signal ? { signal: input.signal } : {}), + syncBack: true + }); +} + +function resolveInitialExperimentAgent( + agent: ExperimentRunOptions["agent"], + model: string | undefined +): { agent: string; model?: string } { + const value = Array.isArray(agent) ? agent[0] : agent; + const specifier = parseAgentSpecifier(value ?? "claude-code"); + const initialModel = specifier.model ?? model; + return { + agent: specifier.agent, + ...(initialModel ? { model: initialModel } : {}) + }; +} + export async function readExperimentJournal( options: ExperimentJournalOptions ): Promise { diff --git a/src/sdk/pipeline.test.ts b/src/sdk/pipeline.test.ts index 309f410b4e..0f7fd5ca49 100644 --- a/src/sdk/pipeline.test.ts +++ b/src/sdk/pipeline.test.ts @@ -3,7 +3,9 @@ import { fs, vol } from "memfs"; import type { PipelineRunResult } from "@poe-code/pipeline"; const workspaceRunPipelineMock = vi.hoisted(() => vi.fn()); -const pipelineSkillPlanPath = new URL("../templates/pipeline/SKILL_plan.md", import.meta.url).pathname; +const createSpawnSessionMock = vi.hoisted(() => vi.fn()); +const pipelineSkillPlanPath = new URL("../templates/pipeline/SKILL_plan.md", import.meta.url) + .pathname; vi.mock("node:fs/promises", async () => { const { fs } = await import("memfs"); @@ -14,6 +16,10 @@ vi.mock("./spawn.js", () => ({ spawn: vi.fn() })); +vi.mock("./spawn-session.js", () => ({ + createSpawnSession: createSpawnSessionMock +})); + vi.mock("@poe-code/pipeline", async (importOriginal) => { const actual = await importOriginal(); return { @@ -43,10 +49,13 @@ const workspaceResult: PipelineRunResult = { function seedFs(files: Record): void { vol.reset(); - vol.fromJSON({ - [pipelineSkillPlanPath]: "Pipeline skill template", - ...files - }, "/"); + vol.fromJSON( + { + [pipelineSkillPlanPath]: "Pipeline skill template", + ...files + }, + "/" + ); vol.mkdirSync(cwd, { recursive: true }); vol.mkdirSync(homeDir, { recursive: true }); } @@ -78,6 +87,7 @@ function createActivityTimeoutError(): Error { describe("SDK pipeline", () => { beforeEach(() => { workspaceRunPipelineMock.mockReset(); + createSpawnSessionMock.mockReset(); }); afterEach(() => { @@ -226,14 +236,11 @@ describe("SDK pipeline", () => { }); const timeoutError = createActivityTimeoutError(); - const runAgent = vi - .fn() - .mockRejectedValueOnce(timeoutError) - .mockResolvedValueOnce({ - stdout: "done", - stderr: "", - exitCode: 0 - }); + const runAgent = vi.fn().mockRejectedValueOnce(timeoutError).mockResolvedValueOnce({ + stdout: "done", + stderr: "", + exitCode: 0 + }); workspaceRunPipelineMock.mockImplementationOnce(async (options) => { await options.runAgent?.({ agent: "codex", @@ -256,6 +263,109 @@ describe("SDK pipeline", () => { expect(runAgent).toHaveBeenCalledTimes(2); }); + it("reuses a spawn session for default agent runs and syncs back once at the end", async () => { + seedFs({ + "/repo/feature.md": initializedPlan() + }); + + const run = vi.fn().mockResolvedValue({ + stdout: "done", + stderr: "", + exitCode: 0 + }); + const syncBack = vi.fn().mockResolvedValue({ files: 1, bytes: 2, conflicts: [] }); + const close = vi.fn().mockResolvedValue(undefined); + createSpawnSessionMock.mockReturnValue({ run, syncBack, close }); + workspaceRunPipelineMock.mockImplementationOnce(async (options) => { + await options.runAgent?.({ + agent: "codex", + prompt: "Ship it.", + mode: "yolo", + cwd, + logDir: "/repo/.poe-code/pipeline/logs", + logFileName: "ship-feature.jsonl", + model: "gpt-5" + }); + await options.runAgent?.({ + agent: "codex", + prompt: "Verify it.", + mode: "read", + cwd + }); + + return workspaceResult; + }); + + const result = await runPipeline({ + agent: "codex", + cwd, + homeDir, + plan: "feature.md", + model: "gpt-5" + }); + + expect(result).toEqual(workspaceResult); + expect(createSpawnSessionMock).toHaveBeenCalledTimes(1); + expect(createSpawnSessionMock).toHaveBeenCalledWith({ + service: "codex", + cwd, + model: "gpt-5" + }); + expect(run).toHaveBeenCalledTimes(2); + expect(run).toHaveBeenNthCalledWith(1, { + agent: "codex", + prompt: "Ship it.", + mode: "yolo", + cwd, + logDir: "/repo/.poe-code/pipeline/logs", + logFileName: "ship-feature.jsonl", + model: "gpt-5", + syncBack: false + }); + expect(run).toHaveBeenNthCalledWith(2, { + agent: "codex", + prompt: "Verify it.", + mode: "read", + cwd, + syncBack: false + }); + expect(syncBack).toHaveBeenCalledTimes(1); + expect(close).toHaveBeenCalledTimes(1); + expect(syncBack).toHaveBeenCalledBefore(close); + }); + + it("keeps custom runAgent overrides outside the default spawn session", async () => { + seedFs({ + "/repo/feature.md": initializedPlan() + }); + + const runAgent = vi.fn().mockResolvedValue({ + stdout: "custom", + stderr: "", + exitCode: 0 + }); + workspaceRunPipelineMock.mockImplementationOnce(async (options) => { + await options.runAgent?.({ + agent: "codex", + prompt: "Ship it.", + mode: "yolo", + cwd + }); + return workspaceResult; + }); + + await runPipeline({ + agent: "codex", + cwd, + homeDir, + plan: "feature.md", + runAgent + }); + + expect(createSpawnSessionMock).not.toHaveBeenCalled(); + expect(runAgent).toHaveBeenCalledTimes(1); + }); + it("does not retry non-timeout errors", async () => { seedFs({ "/repo/feature.md": initializedPlan() diff --git a/src/sdk/pipeline.ts b/src/sdk/pipeline.ts index 5232f3d88d..068af10d72 100644 --- a/src/sdk/pipeline.ts +++ b/src/sdk/pipeline.ts @@ -9,6 +9,7 @@ import { import { buildPipelineInitPrompt } from "../cli/commands/pipeline-init.js"; import pipelineSkillPlan from "../templates/pipeline/SKILL_plan.md"; import { spawn as sdkSpawn } from "./spawn.js"; +import { createSpawnSession, type SpawnSession } from "./spawn-session.js"; export type { AgentRunUsage, @@ -89,10 +90,7 @@ async function planNeedsInit(absolutePath: string): Promise { return !Array.isArray(tasks) || tasks.length === 0; } -async function runWithRetry( - fn: () => Promise, - maxAttempts: number -): Promise { +async function runWithRetry(fn: () => Promise, maxAttempts: number): Promise { let lastError: unknown; for (let attempt = 0; attempt < maxAttempts; attempt++) { try { @@ -105,65 +103,96 @@ async function runWithRetry( throw lastError; } -export async function runPipeline( - options: PipelineRunOptions -): Promise { - const userRunAgent = options.runAgent ?? (async (input: PipelineAgentRunnerInput) => { - return await sdkSpawn.autonomous(input.agent, { - prompt: input.prompt, - cwd: input.cwd, - logDir: input.logDir, - model: input.model, - mode: input.mode, - ...(input.mcpServers ? { mcpServers: input.mcpServers } : {}), - ...(input.signal ? { signal: input.signal } : {}) - }); - }); +export async function runPipeline(options: PipelineRunOptions): Promise { + const session = options.runAgent ? null : createPipelineSpawnSession(options); + const userRunAgent = + options.runAgent ?? createPipelineSessionRunAgent(session as SpawnSession, false); - if (options.plan) { - const planAbsolutePath = path.resolve(options.cwd, options.plan); - if (await planNeedsInit(planAbsolutePath)) { - const sourceDocContent = await fsPromises.readFile(planAbsolutePath, "utf8"); - const prompt = buildPipelineInitPrompt({ - sourceDocPath: options.plan, - sourceDocContent, - skillContent: pipelineSkillPlan - }); - await runWithRetry( - () => userRunAgent({ - agent: options.agent, - prompt, - mode: "yolo", - cwd: options.cwd, - ...(options.model ? { model: options.model } : {}), - ...(options.signal ? { signal: options.signal } : {}) - }), - PIPELINE_ACTIVITY_TIMEOUT_RETRY_COUNT - ); + try { + if (options.plan) { + const planAbsolutePath = path.resolve(options.cwd, options.plan); + if (await planNeedsInit(planAbsolutePath)) { + const sourceDocContent = await fsPromises.readFile(planAbsolutePath, "utf8"); + const prompt = buildPipelineInitPrompt({ + sourceDocPath: options.plan, + sourceDocContent, + skillContent: pipelineSkillPlan + }); + const initRunAgent = session ? createPipelineSessionRunAgent(session, true) : userRunAgent; + await runWithRetry( + () => + initRunAgent({ + agent: options.agent, + prompt, + mode: "yolo", + cwd: options.cwd, + ...(options.model ? { model: options.model } : {}), + ...(options.signal ? { signal: options.signal } : {}) + }), + PIPELINE_ACTIVITY_TIMEOUT_RETRY_COUNT + ); + } } - } - const retryRunAgent: PipelineAgentRunner = (input) => - runWithRetry(() => userRunAgent(input), PIPELINE_ACTIVITY_TIMEOUT_RETRY_COUNT); + const retryRunAgent: PipelineAgentRunner = (input) => + runWithRetry(() => userRunAgent(input), PIPELINE_ACTIVITY_TIMEOUT_RETRY_COUNT); + + return await runWorkspacePipeline({ + ...options, + runAgent: retryRunAgent + }); + } finally { + if (session) { + try { + await session.syncBack(); + } finally { + await session.close(); + } + } + } +} - return runWorkspacePipeline({ - ...options, - runAgent: retryRunAgent +function createPipelineSpawnSession(options: PipelineRunOptions): SpawnSession { + return createSpawnSession({ + service: options.agent, + cwd: options.cwd, + ...(options.model ? { model: options.model } : {}) }); } +function createPipelineSessionRunAgent( + session: SpawnSession, + syncBack: boolean +): PipelineAgentRunner { + return async (input) => + await session.run({ + agent: input.agent, + prompt: input.prompt, + mode: input.mode, + cwd: input.cwd, + ...(input.logDir ? { logDir: input.logDir } : {}), + ...(input.logFileName ? { logFileName: input.logFileName } : {}), + ...(input.model ? { model: input.model } : {}), + ...(input.mcpServers ? { mcpServers: input.mcpServers } : {}), + ...(input.signal ? { signal: input.signal } : {}), + syncBack + }); +} + export async function runPipelineInit( options: PipelineInitRunOptions ): Promise { - const runAgent = options.runAgent ?? (async (input: PipelineAgentRunnerInput) => { - return await sdkSpawn.autonomous(input.agent, { - prompt: input.prompt, - cwd: input.cwd, - model: input.model, - mode: input.mode, - ...(input.signal ? { signal: input.signal } : {}) + const runAgent = + options.runAgent ?? + (async (input: PipelineAgentRunnerInput) => { + return await sdkSpawn.autonomous(input.agent, { + prompt: input.prompt, + cwd: input.cwd, + model: input.model, + mode: input.mode, + ...(input.signal ? { signal: input.signal } : {}) + }); }); - }); if (options.signal?.aborted) { return { diff --git a/src/sdk/ralph.test.ts b/src/sdk/ralph.test.ts index 510452a0cf..cf26894ed9 100644 --- a/src/sdk/ralph.test.ts +++ b/src/sdk/ralph.test.ts @@ -3,9 +3,8 @@ import type { RalphRunOptions } from "@poe-code/ralph"; const runWorkspaceRalphMock = vi.hoisted(() => vi.fn()); const spawnAutonomousMock = vi.hoisted(() => vi.fn()); -const buildSpawnArgsMock = vi.hoisted(() => vi.fn()); -const createPoeCommandSessionMock = vi.hoisted(() => vi.fn()); -const resolvePoeCommandExecutionMock = vi.hoisted(() => vi.fn()); +const createSpawnSessionMock = vi.hoisted(() => vi.fn()); +const getPoeApiKeyMock = vi.hoisted(() => vi.fn()); vi.mock("@poe-code/ralph", async (importOriginal) => { const actual = await importOriginal(); @@ -22,12 +21,11 @@ vi.mock("./spawn.js", () => ({ })); vi.mock("@poe-code/agent-spawn", () => ({ - buildSpawnArgs: buildSpawnArgsMock + createSpawnSession: createSpawnSessionMock })); -vi.mock("@poe-code/agent-harness-tools", () => ({ - createPoeCommandSession: createPoeCommandSessionMock, - resolvePoeCommandExecution: resolvePoeCommandExecutionMock +vi.mock("./credentials.js", () => ({ + getPoeApiKey: getPoeApiKeyMock })); import { runRalph } from "./ralph.js"; @@ -36,9 +34,9 @@ describe("SDK ralph", () => { beforeEach(() => { runWorkspaceRalphMock.mockReset(); spawnAutonomousMock.mockReset(); - buildSpawnArgsMock.mockReset(); - createPoeCommandSessionMock.mockReset(); - resolvePoeCommandExecutionMock.mockReset(); + createSpawnSessionMock.mockReset(); + getPoeApiKeyMock.mockReset(); + getPoeApiKeyMock.mockResolvedValue("sk-test"); }); it("preserves a caller-provided runAgent", async () => { @@ -70,7 +68,7 @@ describe("SDK ralph", () => { expect(spawnAutonomousMock).not.toHaveBeenCalled(); }); - it("wires the default autonomous runner when no runAgent is provided", async () => { + it("uses the autonomous runner when detach is enabled", async () => { const expectedResult = { stopReason: "max_iterations" as const, docPath: "docs/loop.md", @@ -132,39 +130,19 @@ describe("SDK ralph", () => { }); }); - it("reuses one e2b command session for the default Ralph runner", async () => { + it("reuses one command session for the default Ralph runner", async () => { const run = vi.fn().mockResolvedValue({ - kind: "sync", stdout: "done", stderr: "", - exitCode: 0, - download: { files: 1, bytes: 12, conflicts: [] } + exitCode: 0 }); + const syncBack = vi.fn().mockResolvedValue({ files: 1, bytes: 2, conflicts: [] }); const close = vi.fn().mockResolvedValue(undefined); - const factory = { type: "e2b" }; - const state = { jobs: {} }; let capturedOptions: RalphRunOptions | undefined; const originalPoeApiKey = process.env.POE_API_KEY; process.env.POE_API_KEY = "sk-test"; - buildSpawnArgsMock - .mockReturnValueOnce({ binaryName: "claude", args: ["-p", "first"] }) - .mockReturnValueOnce({ binaryName: "claude", args: ["-p", "second"] }); - resolvePoeCommandExecutionMock.mockReturnValue({ - factory, - state, - detach: false, - openSpec: { - cwd: "/tmp/ralph", - runner: { - detach: false, - upload_max_file_mb: 100, - download_conflict: "refuse" - }, - jobLabel: { tool: "claude-code", argv: ["claude", "-p", "prompt"] } - } - }); - createPoeCommandSessionMock.mockReturnValue({ run, close }); + createSpawnSessionMock.mockReturnValue({ run, syncBack, close }); runWorkspaceRalphMock.mockImplementationOnce(async (options: RalphRunOptions) => { capturedOptions = options; await options.runAgent?.({ @@ -192,8 +170,10 @@ describe("SDK ralph", () => { cwd: "/tmp/ralph", homeDir: "/home/test", docPath: "/tmp/ralph/plan.md", - runtime: "e2b", - runtimeTemplate: "tmpl_test" + runtime: "docker", + runtimeImage: "poe-code:test", + runtimeTemplate: "tmpl_test", + runnerSync: "upload" }); } finally { if (originalPoeApiKey === undefined) { @@ -205,25 +185,112 @@ describe("SDK ralph", () => { expect(capturedOptions?.runAgent).toEqual(expect.any(Function)); expect(spawnAutonomousMock).not.toHaveBeenCalled(); - expect(createPoeCommandSessionMock).toHaveBeenCalledTimes(1); - expect(createPoeCommandSessionMock).toHaveBeenCalledWith({ factory, state }); - expect(buildSpawnArgsMock).toHaveBeenNthCalledWith(1, "claude-code", { - prompt: "first", - model: "sonnet", - mode: "yolo" + expect(createSpawnSessionMock).toHaveBeenCalledTimes(1); + expect(createSpawnSessionMock).toHaveBeenCalledWith({ + service: "claude-code", + cwd: "/tmp/ralph", + mode: "yolo", + runtime: "docker", + runtimeImage: "poe-code:test", + runtimeTemplate: "tmpl_test", + runnerSync: "upload", + downloadConflict: "overwrite", + context: { + homeDir: "/home/test" + } }); - expect(buildSpawnArgsMock).toHaveBeenNthCalledWith(2, "claude-code", { + expect(run).toHaveBeenNthCalledWith(2, { prompt: "second", + agent: "claude-code", + cwd: "/tmp/ralph", model: "sonnet", - mode: "yolo" + signal: undefined, + syncBack: false }); expect(run).toHaveBeenCalledTimes(2); - expect(run.mock.calls[0]?.[0]).toEqual( - expect.objectContaining({ - runner: expect.objectContaining({ download_conflict: "overwrite" }) + expect(run.mock.calls[0]?.[0]).toEqual({ + prompt: "first", + agent: "claude-code", + cwd: "/tmp/ralph", + model: "sonnet", + signal: undefined, + syncBack: false + }); + expect(syncBack).toHaveBeenCalledTimes(1); + expect(close).toHaveBeenCalledTimes(1); + }); + + it("syncs back and closes the command session when Ralph fails", async () => { + const run = vi.fn().mockResolvedValue({ + stdout: "done", + stderr: "", + exitCode: 0 + }); + const syncBack = vi.fn().mockResolvedValue({ files: 1, bytes: 2, conflicts: [] }); + const close = vi.fn().mockResolvedValue(undefined); + const failure = new Error("ralph failed"); + + createSpawnSessionMock.mockReturnValue({ run, syncBack, close }); + runWorkspaceRalphMock.mockRejectedValueOnce(failure); + + await expect( + runRalph({ + cwd: "/repo", + homeDir: "/home/test", + docPath: "docs/loop.md" }) - ); - expect(resolvePoeCommandExecutionMock).toHaveBeenCalledTimes(2); + ).rejects.toThrow("ralph failed"); + + expect(syncBack).toHaveBeenCalledTimes(1); + expect(close).toHaveBeenCalledTimes(1); + }); + + it("finalizes the command session when Ralph prepares terminal status writes", async () => { + const events: string[] = []; + const run = vi.fn().mockResolvedValue({ + stdout: "done", + stderr: "", + exitCode: 0 + }); + const syncBack = vi.fn(async () => { + events.push("sync"); + return { files: 1, bytes: 2, conflicts: [] }; + }); + const close = vi.fn(async () => { + events.push("close"); + }); + const originalPoeApiKey = process.env.POE_API_KEY; + + process.env.POE_API_KEY = "sk-test"; + createSpawnSessionMock.mockReturnValue({ run, syncBack, close }); + runWorkspaceRalphMock.mockImplementationOnce(async (options: RalphRunOptions) => { + await options.prepareFinalWorkspace?.(); + events.push("status"); + await options.prepareFinalWorkspace?.(); + return { + stopReason: "max_iterations", + docPath: "docs/loop.md", + iterationsCompleted: 1, + totalDurationMs: 1_000 + }; + }); + + try { + await runRalph({ + cwd: "/repo", + homeDir: "/home/test", + docPath: "docs/loop.md" + }); + } finally { + if (originalPoeApiKey === undefined) { + delete process.env.POE_API_KEY; + } else { + process.env.POE_API_KEY = originalPoeApiKey; + } + } + + expect(events).toEqual(["sync", "close", "status"]); + expect(syncBack).toHaveBeenCalledTimes(1); expect(close).toHaveBeenCalledTimes(1); }); }); diff --git a/src/sdk/ralph.ts b/src/sdk/ralph.ts index 0c7d53805c..679d0b585e 100644 --- a/src/sdk/ralph.ts +++ b/src/sdk/ralph.ts @@ -3,12 +3,9 @@ import { type RalphRunOptions, type RalphRunResult } from "@poe-code/ralph"; -import { - createPoeCommandSession, - resolvePoeCommandExecution, - type PoeCommandSession -} from "@poe-code/agent-harness-tools"; -import { buildSpawnArgs } from "@poe-code/agent-spawn"; +import { parseAgentSpecifier } from "@poe-code/agent-defs"; +import type { SpawnSession } from "./spawn-session.js"; +import { createSpawnSession } from "./spawn-session.js"; import { spawn as sdkSpawn } from "./spawn.js"; import { getPoeApiKey } from "./credentials.js"; @@ -20,18 +17,30 @@ export type { RalphStopReason } from "@poe-code/ralph"; +const DEFAULT_RALPH_AGENT = "claude-code"; + export async function runRalph(options: RalphRunOptions): Promise { - const reusableE2b = options.runtime === "e2b" && options.detach !== true; - const e2bRunner = reusableE2b && !options.runAgent ? createReusableE2bRalphRunner(options) : null; - const runAgent = options.runAgent ?? e2bRunner?.runAgent ?? createDefaultRalphRunAgent(options); + if (options.runAgent || options.detach === true) { + return await runWorkspaceRalph({ + ...options, + runAgent: options.runAgent ?? createDefaultRalphRunAgent(options) + }); + } + await ensurePoeApiKey(); + const session = createRalphSpawnSession(options); + const finishSession = createRalphSessionFinalizer(session); try { return await runWorkspaceRalph({ ...options, - runAgent + prepareFinalWorkspace: async () => { + await options.prepareFinalWorkspace?.(); + await finishSession(); + }, + runAgent: createSessionRalphRunAgent(session) }); } finally { - await e2bRunner?.close(); + await finishSession(); } } @@ -55,82 +64,64 @@ function createDefaultRalphRunAgent( }); } -function createReusableE2bRalphRunner(options: RalphRunOptions): { - runAgent: NonNullable; - close(): Promise; -} { - let session: PoeCommandSession | null = null; - let sessionFactory: unknown; - let sessionState: ReturnType["state"] | undefined; +function createRalphSpawnSession(options: RalphRunOptions): SpawnSession { + const initialAgent = resolveInitialAgent(options.agent); - return { - async runAgent(input) { - await ensurePoeApiKey(); - const spawnArgs = buildSpawnArgs(input.agent, { - prompt: input.prompt, - model: input.model, - mode: "yolo" - }); - const processEnv = spawnArgs.env ? { ...process.env, ...spawnArgs.env } : process.env; - const execution = resolvePoeCommandExecution({ - cwd: input.cwd, - runtimeConfigCwd: options.runtimeConfigCwd, - env: processEnv as Record, - argv: [spawnArgs.binaryName, ...spawnArgs.args], - tool: input.agent, - runtime: { - runtime: options.runtime, - runtimeImage: options.runtimeImage, - runtimeTemplate: options.runtimeTemplate, - mountPoeCode: options.mountPoeCode, - runnerSync: options.runnerSync - }, - context: { - homeDir: options.homeDir, - ...(sessionState ? { state: sessionState } : {}) - }, - openSpec: { - execution: { - wrapForLogTee: false, - stdin: "inherit", - stdout: "pipe", - stderr: "pipe", - env: processEnv as Record, - captureOutput: true - } - } - }); + return createSpawnSession({ + service: initialAgent.agent, + cwd: options.cwd, + ...(initialAgent.model ? { model: initialAgent.model } : {}), + mode: "yolo", + ...(options.runtime ? { runtime: options.runtime } : {}), + ...(options.runtimeImage ? { runtimeImage: options.runtimeImage } : {}), + ...(options.runtimeTemplate ? { runtimeTemplate: options.runtimeTemplate } : {}), + ...(options.runtimeConfigCwd ? { runtimeConfigCwd: options.runtimeConfigCwd } : {}), + ...(options.mountPoeCode ? { mountPoeCode: options.mountPoeCode } : {}), + ...(options.runnerSync ? { runnerSync: options.runnerSync } : {}), + downloadConflict: "overwrite", + context: { + homeDir: options.homeDir + } + }); +} - if (session === null) { - sessionFactory = execution.factory; - sessionState = execution.state; - session = createPoeCommandSession({ - factory: execution.factory, - state: execution.state - }); - } else if (execution.factory !== sessionFactory) { - throw new Error("Ralph e2b runtime changed during a reusable session."); - } +function createSessionRalphRunAgent( + session: SpawnSession +): NonNullable { + return async (input) => + await session.run({ + prompt: input.prompt, + agent: input.agent, + cwd: input.cwd, + model: input.model, + signal: input.signal, + syncBack: false + }); +} + +function createRalphSessionFinalizer(session: SpawnSession): () => Promise { + let finished = false; - const openSpec = execution.openSpec.runner - ? { - ...execution.openSpec, - runner: { - ...execution.openSpec.runner, - download_conflict: "overwrite" as const - } - } - : execution.openSpec; - const result = await session.run(openSpec, input.signal); - return { - stdout: result.stdout ?? "", - stderr: result.stderr ?? "", - exitCode: result.exitCode - }; - }, - async close() { - await session?.close(); + return async () => { + if (finished) { + return; } + + finished = true; + try { + await session.syncBack(); + } finally { + await session.close(); + } + }; +} + +function resolveInitialAgent(agent: RalphRunOptions["agent"]): { agent: string; model?: string } { + const value = Array.isArray(agent) ? agent[0] : agent; + const specifier = parseAgentSpecifier(value ?? DEFAULT_RALPH_AGENT); + return { + agent: specifier.agent, + ...(specifier.model ? { model: specifier.model } : {}) }; } diff --git a/src/sdk/sdk-core.test.ts b/src/sdk/sdk-core.test.ts index 3188e52ef6..1c062e35d5 100644 --- a/src/sdk/sdk-core.test.ts +++ b/src/sdk/sdk-core.test.ts @@ -89,6 +89,12 @@ vi.mock("./spawn.js", () => ({ }) })); +const createSpawnSessionMock = vi.hoisted(() => vi.fn()); + +vi.mock("./spawn-session.js", () => ({ + createSpawnSession: createSpawnSessionMock +})); + import { createSdkContainer } from "./container.js"; import { followLaunchLogs, @@ -658,9 +664,10 @@ describe("SDK experiment", () => { beforeEach(() => { runExperimentLoopMock.mockReset(); spawnAutonomousMock.mockReset(); + createSpawnSessionMock.mockReset(); }); - it("forwards CLI-parity options and wires the default agent runner", async () => { + it("forwards CLI-parity options and wires the default session agent runner", async () => { const expectedResult = { stopReason: "max_experiments" as const, docPath: "docs/loop.md", @@ -670,18 +677,32 @@ describe("SDK experiment", () => { }; const onExperimentStart = vi.fn(); const onExperimentComplete = vi.fn(); + const run = vi.fn().mockResolvedValue({ + stdout: "done", + stderr: "", + exitCode: 0 + }); + const close = vi.fn().mockResolvedValue(undefined); let capturedOptions: ExperimentRunOptions | undefined; runExperimentLoopMock.mockImplementationOnce(async (options: ExperimentRunOptions) => { capturedOptions = options; + await options.runAgent?.({ + agent: "codex", + prompt: "Improve the metric", + cwd: "/repo", + model: "gpt-5.2" + }); + await options.runAgent?.({ + agent: "claude-code", + prompt: "Try another approach", + cwd: "/repo", + model: "claude" + }); return expectedResult; }); - spawnAutonomousMock.mockResolvedValue({ - stdout: "done", - stderr: "", - exitCode: 0 - }); + createSpawnSessionMock.mockReturnValue({ run, close }); const result = await runExperiment({ cwd: "/repo", @@ -712,27 +733,82 @@ describe("SDK experiment", () => { }) ); - const agentResult = await capturedOptions?.runAgent?.({ - agent: "codex", - prompt: "Improve the metric", + expect(createSpawnSessionMock).toHaveBeenCalledTimes(1); + expect(createSpawnSessionMock).toHaveBeenCalledWith({ + service: "codex", cwd: "/repo", - model: "gpt-5.2" + model: "gpt-5.2", + mode: "yolo", + runtime: "e2b", + runtimeTemplate: "tpl_123", + mountPoeCode: true, + downloadConflict: "overwrite", + context: { + homeDir: "/home/test" + } }); - expect(spawnAutonomousMock).toHaveBeenCalledWith("codex", { + expect(run).toHaveBeenCalledTimes(2); + expect(run).toHaveBeenNthCalledWith(1, { + agent: "codex", prompt: "Improve the metric", cwd: "/repo", model: "gpt-5.2", - mode: "yolo", - runtime: "e2b", - runtimeTemplate: "tpl_123", - mountPoeCode: true + syncBack: true }); - expect(agentResult).toEqual({ - stdout: "done", + expect(run).toHaveBeenNthCalledWith(2, { + agent: "claude-code", + prompt: "Try another approach", + cwd: "/repo", + model: "claude", + syncBack: true + }); + expect(close).toHaveBeenCalledTimes(1); + expect(spawnAutonomousMock).not.toHaveBeenCalled(); + }); + + it("keeps detached experiment runs on the autonomous runner", async () => { + const expectedResult = { + stopReason: "max_experiments" as const, + docPath: "docs/loop.md", + experimentsCompleted: 1, + experimentsKept: 0, + totalDurationMs: 100 + }; + + runExperimentLoopMock.mockImplementationOnce(async (options: ExperimentRunOptions) => { + await options.runAgent?.({ + agent: "codex", + prompt: "Launch detached experiment", + cwd: "/repo", + model: "gpt-5" + }); + return expectedResult; + }); + spawnAutonomousMock.mockResolvedValue({ + stdout: "", stderr: "", exitCode: 0 }); + + await expect( + runExperiment({ + cwd: "/repo", + homeDir: "/home/test", + docPath: "docs/loop.md", + agent: "codex", + detach: true + }) + ).resolves.toEqual(expectedResult); + + expect(createSpawnSessionMock).not.toHaveBeenCalled(); + expect(spawnAutonomousMock).toHaveBeenCalledWith("codex", { + prompt: "Launch detached experiment", + cwd: "/repo", + model: "gpt-5", + mode: "yolo", + detach: true + }); }); }); diff --git a/src/sdk/spawn-session.ts b/src/sdk/spawn-session.ts new file mode 100644 index 0000000000..53b6432b15 --- /dev/null +++ b/src/sdk/spawn-session.ts @@ -0,0 +1,6 @@ +export { + createSpawnSession, + type CreateSpawnSessionOptions, + type SpawnSession, + type SpawnSessionRunInput +} from "@poe-code/agent-spawn"; From 40dd8548c7f7816c459aec8b858992641f7643cf Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 12:51:06 -0500 Subject: [PATCH 108/111] docs: drop superseded plan files --- .../02-ai-sdk-provider-poe-integration.md | 200 ----- .../plans/02-http-mcp-production-readiness.md | 34 - docs/plans/04-js-subset-sandbox.md | 743 ------------------ docs/plans/24-harness-session-runtime.md.lock | 1 - 4 files changed, 978 deletions(-) delete mode 100644 docs/plans/02-ai-sdk-provider-poe-integration.md delete mode 100644 docs/plans/02-http-mcp-production-readiness.md delete mode 100644 docs/plans/04-js-subset-sandbox.md delete mode 100644 docs/plans/24-harness-session-runtime.md.lock diff --git a/docs/plans/02-ai-sdk-provider-poe-integration.md b/docs/plans/02-ai-sdk-provider-poe-integration.md deleted file mode 100644 index bb77449885..0000000000 --- a/docs/plans/02-ai-sdk-provider-poe-integration.md +++ /dev/null @@ -1,200 +0,0 @@ -# Integration: ai-sdk-provider-poe - -## Summary - -Replace the hand-rolled HTTP calls across poe-code with [`ai-sdk-provider-poe`](https://github.com/poe-platform/ai-sdk-provider-poe), gaining first-party AI SDK routing (Anthropic Messages API, OpenAI Responses API, Google, etc.) and runtime model discovery with rich metadata. - -Three integration surfaces: - -| Surface | Current | After | -|---------|---------|-------| -| **poe-agent** (`packages/poe-agent`) | `PoeChatService` — raw fetch to `/v1/chat/completions` | Vercel AI SDK `generateText()` via `poe()` provider — first-party routing, streaming, tool calling | -| **generate** (`src/sdk/generate.ts`, `src/services/llm-client.ts`) | Raw fetch to `/v1/chat/completions` | `generateText()` / `streamText()` via `poe()` — typed responses, proper error handling | -| **models CLI** (`src/cli/commands/models.ts`) | Raw fetch to `/v1/models` | `fetchPoeModels()` — typed model metadata with capabilities, pricing, reasoning support | - -## Dependencies - -``` -npm install ai-sdk-provider-poe ai -``` - -- `ai` — Vercel AI SDK core (peer dep of `ai-sdk-provider-poe`) -- `ai-sdk-provider-poe` — Poe provider for Vercel AI SDK - -## Phase 1: models CLI → `fetchPoeModels()` - -**Why first**: Lowest risk, self-contained command, validates the SDK works with existing auth. - -### Changes - -1. **`src/cli/commands/models.ts`** — Replace raw HTTP fetch with `fetchPoeModels()` - - Current: - ```ts - const response = await container.httpClient(`${container.env.poeBaseUrl}/v1/models`, { ... }); - const result = await response.json(); - ``` - - After: - ```ts - import { fetchPoeModels } from "ai-sdk-provider-poe"; - - const models = await fetchPoeModels({ apiKey }); - ``` - - The `fetchPoeModels()` returns typed model objects with: `id`, `rawId`, `ownedBy`, `contextWindow`, `maxOutputTokens`, `supportsImages`, `supportsPromptCache`, `supportsReasoningBudget`, `supportsReasoningEffort`, `pricing`. - -2. **Map SDK model shape → existing `ModelEntry` interface** (or replace it). The SDK gives us richer metadata than the raw API — we get `supportsReasoningBudget`, `supportsReasoningEffort`, `supportsPromptCache` as booleans instead of opaque feature arrays. - -3. **Keep existing filter/view logic** — filters and table rendering stay the same, just the data source changes. - -### Tests - -- Unit test: mock `fetchPoeModels` → verify filtering, views, formatting still work -- Screenshot: `npm run screenshot-poe-code -- models --provider anthropic` - -## Phase 2: generate → Vercel AI SDK `generateText()` - -**Why second**: Replaces `LlmClient` with typed AI SDK calls, benefiting both CLI and SDK. - -### Changes - -1. **`src/services/llm-client.ts`** — Rewrite `createPoeClient()` to use `poe()` provider internally - - Current: - ```ts - // Raw fetch to /v1/chat/completions - const response = await httpClient(`${baseUrl}/chat/completions`, { ... }); - ``` - - After: - ```ts - import { createPoe } from "ai-sdk-provider-poe"; - import { generateText } from "ai"; - - const provider = createPoe({ apiKey }); - const { text } = await generateText({ - model: provider(modelId), - prompt, - }); - ``` - - The `LlmClient` interface stays the same (text/media methods) — only the implementation changes. This preserves all downstream consumers. - -2. **Media generation**: The Vercel AI SDK doesn't have a native media generation path. Two options: - - **Option A**: Keep raw HTTP for media, only migrate text → cleanest separation - - **Option B**: Use `generateText()` and parse the response for URLs (current behavior already parses JSON/markdown from text responses) - - Recommend **Option A** — media generation is a Poe-specific feature that doesn't map to the standard AI SDK abstraction. - -3. **`src/sdk/generate.ts`** — No interface changes. It calls `LlmClient.text()` which is the seam we're replacing. - -4. **Extended thinking support** — The Poe SDK supports `reasoningBudget` for Anthropic models. Surface this as a new `--reasoning-budget` param on the generate CLI. - -### Tests - -- Unit test: mock at AI SDK level → verify generate still returns content -- Existing generate tests should pass with mocked provider - -## Phase 3: poe-agent → Vercel AI SDK with tool calling - -**Why last**: Most complex, touches the agent runtime, needs careful streaming/tool-call handling. - -### Changes - -1. **`packages/poe-agent/src/chat.ts`** — Replace `PoeChatService` with AI SDK - - Current flow: - ``` - POST /v1/chat/completions → parse tool_calls → execute tools → POST again → loop - ``` - - After: - ```ts - import { createPoe } from "ai-sdk-provider-poe"; - import { generateText } from "ai"; - - const provider = createPoe({ apiKey, baseUrl }); - const result = await generateText({ - model: provider(modelId), - messages, - tools: convertedTools, - maxSteps: maxToolCallIterations, // AI SDK handles the tool loop - }); - ``` - - Key benefits: - - AI SDK handles the tool-call loop natively (`maxSteps`) - - First-party routing means Anthropic models use the Messages API (better tool calling) - - OpenAI models use the Responses API - - Streaming via `streamText()` for real-time session updates - -2. **Tool definition conversion** — Current tools use OpenAI function-calling format. AI SDK uses its own `tool()` helper: - - ```ts - import { tool } from "ai"; - import { z } from "zod"; - - const readFileTool = tool({ - description: "Read file content", - parameters: z.object({ path: z.string() }), - execute: async ({ path }) => executor.readFile(path), - }); - ``` - - This means converting `DefaultToolExecutor` and `McpToolExecutor` tool definitions to AI SDK format. - -3. **Session update streaming** — Replace manual chunk parsing with AI SDK's `streamText()`: - - ```ts - const result = streamText({ - model: provider(modelId), - messages, - tools, - maxSteps, - onStepFinish: (step) => { - // Emit ACP-compatible session updates - }, - }); - - for await (const chunk of result.textStream) { - onSessionUpdate({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: chunk } }); - } - ``` - -4. **`packages/poe-agent/package.json`** — Add deps: - ```json - "ai-sdk-provider-poe": "^x.x.x", - "ai": "^x.x.x", - "zod": "^3.x.x" - ``` - -### Tests - -- Unit test: mock AI SDK `generateText` → verify tool loop, session updates, error handling -- E2E: `npm run e2e:verbose` (poe-agent spawn flow) -- Spot test: `npm run dev -- spawn poe-agent "list files"` - -## Migration Strategy - -Each phase is independently shippable. The `LlmClient` interface acts as the seam — we can swap the implementation without changing consumers. - -``` -Phase 1 (models) → commit + merge -Phase 2 (generate) → commit + merge -Phase 3 (poe-agent) → commit + merge -``` - -No breaking changes to the SDK public API (`spawn`, `generate`, `generateImage`, etc.). - -## Risks & Considerations - -1. **Bundle size** — `ai` package is substantial. Need to verify it doesn't bloat the CLI bundle excessively. The `ai-sdk-provider-poe` itself is lightweight. - -2. **Media generation** — AI SDK doesn't have a standard media generation path. We keep raw HTTP for image/video/audio. - -3. **Error mapping** — AI SDK errors may differ from current `ApiError` format. Need adapter layer in `llm-client.ts`. - -4. **Streaming compatibility** — The poe-agent emits `SessionUpdate` events. Need to verify AI SDK's streaming callbacks map cleanly to the existing event model. - -5. **zod dependency** — AI SDK tool definitions require zod schemas. The `poe-agent` package currently has no zod dependency. This adds a new dep to the agent package. diff --git a/docs/plans/02-http-mcp-production-readiness.md b/docs/plans/02-http-mcp-production-readiness.md deleted file mode 100644 index 6e17bc65fb..0000000000 --- a/docs/plans/02-http-mcp-production-readiness.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -$schema: https://poe-platform.github.io/poe-code/schemas/plans/plan.schema.json -kind: plan -version: 1 ---- - -# HTTP MCP Production Readiness - -Make `tiny-http-mcp-server` production-grade for remote tool-only MCP HTTP deployments. - -## 1. What we're building - -Fix all production-readiness gaps in the HTTP MCP server package so it is safe, durable, and spec-conformant enough for real remote MCP tool deployments. - -The scope includes: - -- Origin validation and DNS rebinding protection for HTTP MCP endpoints. -- Per-session protocol lifecycle instead of relying on the base stdio server's global initialized state. -- Protocol-version negotiation and request-header enforcement for stateful HTTP sessions. -- Correct Streamable HTTP SSE behavior for multiple connected streams, including resumable delivery support. -- Resource limits for request bodies, batches, sessions, streams, and concurrent tool calls. -- Pluggable/expiring session storage suitable for long-running servers and multi-instance deployments. -- First-class production OAuth token verification using the existing `mcp-oauth` package, including JWKS caching and clear auth errors. -- HTTP hardening around request errors, timeouts, trusted proxy handling, CORS/preflight, and response headers. -- Observability hooks for logs, metrics, request IDs, auth failures, tool latency, and session lifecycle. - -Explicit non-goals for this plan: - -- Do not replace the `tiny-stdio-mcp-server` package with the official MCP SDK. -- Do not add provider-specific branches or special cases. -- Do not add README changes without explicit user permission. -- Do not implement a hosted OAuth authorization server in `tiny-http-mcp-server`; the package remains a protected-resource server and consumes/verifies bearer tokens. -- Do not add MCP capabilities beyond tools in this plan: no resources, prompts, completion, roots, sampling, elicitation, or generalized server-initiated request/response support. -- Do not write screenshot tests. Any visual CLI impact should be validated with ad hoc screenshots only. diff --git a/docs/plans/04-js-subset-sandbox.md b/docs/plans/04-js-subset-sandbox.md deleted file mode 100644 index 1e34130ec1..0000000000 --- a/docs/plans/04-js-subset-sandbox.md +++ /dev/null @@ -1,743 +0,0 @@ ---- -$schema: https://poe-platform.github.io/poe-code/schemas/plans/plan.schema.json -kind: plan -version: 1 ---- - -# agent-script - -A safely-evaluated JavaScript subset that **is** the harness. The script drives the orchestration — spawns agents, calls MCP tools, persists state, branches and loops — using a small set of host primitives. Zero runtime deps. - -## 1. What we're building - -A JavaScript subset, evaluated by JavaScript, but safely — like a sandbox. The script is the harness: it owns the control flow. Today's harnesses (experiment, superintendent, pipeline) are different YAML/markdown formats glued to different runners; under agent-script they collapse into one model — a script + a curated set of host primitives. - -Purpose: - -- agent-script *is* the harness; no separate harness file format -- MCP composition and execution from inside the script -- existing harness packages (experiment, superintendent, pipeline) become thin runners that expose primitives and load an `.ajs` file - -Constraints: - -- zero runtime deps -- no `async`/`await` keywords in the subset; host primitives are sync-looking but async-internally (the interpreter is async and `await`s host calls between subset steps) -- adversarial-safe: from-scratch parser + tree-walking interpreter; subset code never holds host references; step/time/memory budgets enforced - -Non-goals: - -- not a full JS implementation -- not a generic scripting language outside the agent-script runner — the host primitives are the API - -## 2. User-facing shape - -### 2.1 Package - -New package `@poe-code/agent-script`. Zero runtime deps. Public API: - -```ts -import { parse, lint, run, dump, restore } from "@poe-code/agent-script"; - -// Lint — strongly recommended before run; flags every disallowed construct. -const diagnostics = lint(source, { filename: "pipeline.ajs", modules }); -// diagnostics: Array<{ severity, code, message, filename, line, column, span, hint? }> - -// Run — fresh execution -const result = await run(source, { - filename: "pipeline.ajs", - modules, // registered modules: Record - budget: { - steps: 10_000_000, - ms: 6 * 60 * 60 * 1000, - stringLength: 10_000_000, - arrayLength: 1_000_000, - callDepth: 256, - }, - signal: abortController.signal, - snapshotPath: "pipeline.snapshot.json", // optional; runtime checkpoints here -}); - -// result.ok — boolean -// result.returnValue — final expression / explicit return; usually ignored -// result.error — { kind, message, filename, line, column, excerpt, caret } -// result.snapshot — last serialized interpreter state (also written to snapshotPath) -// result.stats — { stepsUsed, durationMs, peakCallDepth, hostCalls } - -// Pause — request a graceful checkpoint. Runtime serializes at the next yield point. -// Returns the serialized snapshot once the in-flight host call settles. -const snapshot = await dump(result); - -// Restore — resume from a snapshot rather than starting fresh. -const result2 = await restore(snapshot, { source, modules, budget, signal }); -``` - -The package-level `run` and `restore` are async because the interpreter is async — subset code uses `async`/`await` and the interpreter awaits real host promises behind the scenes. - -### 2.2 The subset - -**In:** - -- literals: number, string, template strings (no tagged templates), boolean, null, undefined, array, object -- identifiers, `const`, `let` (no `var`) -- arithmetic / comparison / logical / nullish-coalescing / optional-chaining operators -- ternary -- member access, computed member access, function calls -- arrow functions, including async arrows: `async (x) => { const y = await spawn(...); return y; }` -- `await` expressions inside async functions and at the top level of the script -- object and array destructuring; spread/rest in arrays, objects, params, call args -- block statements, `if`/`else`, `for...of`, `for` (C-style), `while`, `return`, `break`, `continue` -- `try`/`catch`/`finally`, `throw` -- ES module imports — bare specifiers only: `import { x } from "name"`, `import x from "name"`, `import * as ns from "name"`. `name` resolves against the runner's module registry. No relative paths, no URL imports. -- top level: either a single bare expression *(file = expression)*, or statements ending in `return value;` - -**Out:** - -- `function` keyword, `class`, `new`, `this`, generators (`function*`, `yield`) -- `import`/`export` from filesystem paths, dynamic `import()`, `require`, `eval`, `Function` -- regex literals, `RegExp`, `BigInt`, `Symbol` -- prototype access (`__proto__`, `prototype`, `constructor`) -- `with`, labels, `var`, `do`/`while`, `switch` (deferred — add later if asked) - -**Closures capture `const` only.** A lambda may close over `const`-bound variables, function parameters, and module imports. Closing over a `let`-bound variable is a lint error: "closure cannot capture mutable binding `x`; use `const`, or pass as a parameter." This rule keeps closure environments serializable and makes snapshot pause/resume tractable. `let` is intentionally local; if you need shared mutable state, model it with a `const` reference to an object or array (those values are mutable; the binding isn't). - -**Promises.** Promise built-ins are subset values, not real JS Promises. Behavior: - -- `Promise.all(iter)`, `Promise.allSettled(iter)`, `Promise.race(iter)`, `Promise.any(iter)`, `Promise.resolve(v)`, `Promise.reject(v)` — provided as built-ins -- `await p` resolves to the value, or throws the rejection reason -- async arrows always return a subset Promise -- not spec-compliant: no `then`/`catch`/`finally` chaining, no microtask ordering guarantees, no PromiseSubclassing. The intent is "concurrency for orchestration," not Promise/A+ conformance - -**Values:** plain JS primitives, plain objects, plain arrays, subset functions (closures), and subset Promises — all in the interpreter's own value space. No host references ever leak in. Property reads on objects look up own keys only — no prototype walking. - -### 2.3 Host API exposed by default - -Always-available globals: - -```js -console.log(...args), console.error(...args) -JSON.parse(text), JSON.stringify(value, null?, indent?) -Math.{min, max, abs, floor, ceil, round, trunc, sign, pow, sqrt, log, log2, log10, exp, sin, cos, tan, PI, E, random} -Object.{keys, values, entries, fromEntries, freeze, assign} -Array.{isArray, from, of} -String, Number, Boolean // coercion functions only, not constructors -Error(message), TypeError(message) // sandbox-internal error values -``` - -Methods on primitive and built-in values (intercepted by the interpreter — no host prototype is exposed): - -```js -// strings -.length -.charAt(i), .charCodeAt(i), .codePointAt(i) -.includes(s), .startsWith(s), .endsWith(s), .indexOf(s), .lastIndexOf(s) -.slice(a, b), .substring(a, b), .substr(a, n) -.split(separator) // string separator only — no RegExp -.replace(needle, replacement) // both args strings — no RegExp, no fn replacer -.replaceAll(needle, replacement) -.toLowerCase(), .toUpperCase() -.trim(), .trimStart(), .trimEnd() -.padStart(n, pad?), .padEnd(n, pad?) -.repeat(n) -.concat(...others) -.normalize() - -// arrays -.length -.map(fn), .filter(fn), .find(fn), .findIndex(fn), .some(fn), .every(fn) -.reduce(fn, init?), .reduceRight(fn, init?) -.forEach(fn), .flatMap(fn), .flat(depth?) -.includes(v), .indexOf(v), .lastIndexOf(v) -.join(sep?), .slice(a, b), .concat(...others) -.sort(cmp?), .reverse() -.push(...v), .pop(), .shift(), .unshift(...v) - -// numbers -.toString(radix?), .toFixed(d), .toPrecision(p) -``` - -Caller-injected globals (per `globals` option) are deep-copied into sandbox value space on entry. Functions injected as globals are wrapped: subset args are unwrapped to host values, the host fn runs, its return is deep-copied back into sandbox space. Throws from host functions become sandbox `Error` values with the host stack stripped. No live host references ever cross the boundary. - -Subset functions (lambdas) passed *into* host calls (e.g. as a callback) are wrapped the other way: invoking them from the host re-enters the interpreter under the same step/time budget. - -### 2.4 Modules - -Capabilities live behind ES module imports, not implicit globals. The runner registers a module registry; `import { x } from "name"` resolves against that registry. Bare specifiers only — no filesystem paths, no node_modules, no relative imports. - -The script's imports are explicit, the linter validates every name, and the harness can't accidentally use a capability that wasn't registered. - -Built-in modules a runner can register: - -```js -// agent — spawn an agent. agentDef is a frontmatter agent definition (or any matching record). -// agentDef.prompt is the system persona; opts.prompt is the user message. -// Returns a Promise. Throws on non-zero exit; wrap in try/catch to handle. -import { spawn } from "agent"; -await spawn(agentDef, { prompt, mcp?, model?, mode?, cwd?, timeoutMs? }); -// -> { exitCode, stdout, stderr, summary, durationMs } - -// harness — frontmatter data and runner metadata -import { tasks, agents, meta } from "harness"; -// `tasks`, `agents` come from frontmatter; `meta` is { kind, version, filepath, ... } - -// git -import { head, checkpoint, commit, revert, diff } from "git"; -await commit({ message, files? }); - -// mcp -import { server, client } from "mcp"; -const search = server({ command, args?, env? }); -const c = await client(search); -const tools = await c.tools(); // [{ name, description, schema }] -const out = await c.tool(name, args); - -// metric (npm scripts named metric:*) -import { run as runMetric } from "metric"; -await runMetric("tests"); // -> number - -// log -import { info, error, event } from "log"; -event("task.done", { id: "fix-auth" }); // dashboards subscribe to events - -// env (curated, not process.env) -import { get } from "env"; -get("BUILDER_AGENT"); - -// fail -import { fail } from "fail"; -fail("setup did not complete"); - -// random / now / uuid -import { random, now, uuid } from "time"; -``` - -Module APIs are async by default for anything that talks to the outside world. Pure-data modules (`harness`, `env`) are sync. - -Custom modules: harness packages register additional modules. Pipeline might add a `tasks` module with helpers; experiment-loop might add a `journal` module if it wants persistent attempt history. Modules are the extension surface. - -Multiple import forms are accepted: - -```js -import { spawn } from "agent"; // named -import * as git from "git"; // namespace — git.commit(...), git.head() -import { run as runMetric } from "metric"; // alias -import fail from "fail"; // default (if module declares one) -``` - -The runner picks which modules to register for a given run. A pipeline runner registers `agent`, `harness`, `mcp`, `log`, `fail`, `time`. An experiment runner adds `git`, `metric`. The linter knows the registered module list and reports unknown imports against that list. - -### 2.5 Async and concurrency - -Subset code uses `async`/`await` and `Promise.*` directly. Sequential, parallel, and racing variants are all expressible. - -```js -// sequential -await spawn(agents.builder, { prompt: "Install deps." }); -await spawn(agents.builder, { prompt: "Run migrations." }); - -// parallel -const reports = await Promise.all( - inspectors.map((insp) => spawn(insp, { prompt: `Inspect: ${builder.summary}` })), -); - -// race — first to finish wins; others continue but their results are dropped -const winner = await Promise.race([ - spawn(agents.fastModel, { prompt }), - spawn(agents.slowModel, { prompt }), -]); - -// allSettled — collect mixed success/failure -const outcomes = await Promise.allSettled(branches); -``` - -Internals: - -1. The interpreter is an `async function` over the AST. -2. Module functions registered by the host are normal `async` host functions; on call, the interpreter `await`s them and returns a subset Promise that resolves to the result. -3. `Promise.all` / `race` / `allSettled` / `any` map onto host `Promise.*` for scheduling, but subset Promises are the values authors see. -4. Step budget counts AST node visits across all live execution contexts. Wall-clock budget covers the whole run. -5. Cancellation: when the runner's `signal` aborts, the next host call throws `SandboxError("aborted")` and any `await` on a pending host promise rejects with the same. Scripts can `try`/`catch` to clean up. - -Closures inside parallel branches share scope — but since closures only capture `const` bindings, there is no read/write race on captured state. Mutation of objects referenced by const bindings is visible across branches; treat shared mutable structures inside a `Promise.all` with the same care as in any concurrent JS. - -### 2.6 File format — markdown + frontmatter + script - -A harness file is markdown with YAML frontmatter and a single fenced ```js block in the body. The frontmatter declares **data** (agents, tasks, MCP servers, metrics); the script orchestrates. - -```md ---- -kind: pipeline -version: 1 - -agents: - builder: - agent: claude-code - model: claude-opus-4-7 - mode: yolo - prompt: | - Implement the task. Write tests first, then the change. - reviewer: - agent: claude-code - mode: read - prompt: | - Review the diff for correctness and tests. - -mcp: - search: - command: npx - args: ["-y", "@modelcontextprotocol/server-everything"] - -tasks: - - id: fix-auth - title: Fix auth timeout - prompt: Fix the auth timeout regression in session refresh. ---- - -# Auth pipeline - -Markdown body — prose for humans, agents that read this file, or future you. - -\```js -import { spawn } from "agent"; -import { tasks, agents } from "harness"; -import { server } from "mcp"; -import { commit } from "git"; -import { event } from "log"; - -const search = server({ command: "npx", args: ["-y", "@modelcontextprotocol/server-everything"] }); - -await spawn(agents.builder, { prompt: "Install deps." }); - -await tasks.reduce(async (previous, task) => { - await previous; - event("task.started", { id: task.id, title: task.title }); - await spawn(agents.builder, { - prompt: `${task.id}: ${task.title}\n\n${task.prompt}`, - mcp: { search } - }); - await spawn(agents.reviewer, { prompt: `Review the changes for ${task.id}.` }); - await commit({ message: `feat: ${task.id} - ${task.title}` }); - event("task.completed", { id: task.id, title: task.title }); -}, (async () => {})()); -\``` -``` - -The runner: - -1. Reads the file, splits frontmatter from body. -2. Parses frontmatter (YAML) into a JS object. -3. Extracts the **first** fenced `js` (or `ajs`) code block from the body. Other code fences are inert prose. -4. Builds the `harness` module from frontmatter (`tasks`, `agents`, `meta`) and registers it alongside the runner's other modules. -5. Lints the script against the registered module set; aborts on any error-severity diagnostic. -6. Runs the script with the module registry available to `import`. - -Inspectors are just agents. There is no `inspectors` schema; you put them under `agents` and the script decides which to call when: - -```yaml -agents: - builder: { agent: claude-code, prompt: "..." } - security: { agent: claude-code, mode: read, prompt: "Review for security." } - perf: { agent: claude-code, mode: read, prompt: "Review for performance." } - judge: { agent: claude-code, prompt: "Approve or reject." } -``` - -```js -import { spawn } from "agent"; -import { agents } from "harness"; - -const inspectors = [agents.security, agents.perf]; -for (const insp of inspectors) { - await spawn(insp, { prompt: `Inspect: ${out.summary}` }); -} -``` - -Pure-script files (no frontmatter, no markdown) use the `.ajs` extension. The `harness` module is unavailable in that case; the script imports only what the runner registers. - -### 2.7 Pause and resume — interpreter snapshot - -Because we own the AST and the interpreter, we can serialize the *live* state of a paused script. No journal, no replay, no determinism constraint — the resumed script picks up at the exact AST node where it stopped, with the exact scope it had. - -What the snapshot contains: - -- **AST identity** — content hash of the parsed source, so a resume against an edited file fails loudly instead of corrupting state. -- **Code pointer** — the AST node ID currently being evaluated (or the `await` it's suspended on). -- **Scope chain** — every active scope frame as `{ parentId, bindings: Record }`. Bindings are JSON-friendly because: - - `const` values are immutable references; the snapshot stores the value at pause time. - - `let` values are local to their block and never escape into closures, so they're always serializable scalars or plain objects. -- **Call stack** — activation records `{ astNodeId, scopeId, awaitingPromiseId? }`. -- **Pending Promises** — each subset Promise has an ID; pending Promises capture which host call they're awaiting. On resume, the host call is *not* re-issued — instead, the runner is responsible for either (a) carrying the in-flight promise across the snapshot (only possible if the host process didn't exit), or (b) re-issuing the host call and letting the script see the new result. The runner picks the policy per primitive — `git.commit` is non-idempotent (re-issue would double-commit) so the runner records a "tentative commit" tag and on resume reads `git.head()` to decide; `spawn` is treated as already-completed if its agent process exited, otherwise re-issued. -- **Closures-as-values** — `{ kind: "fn", astNodeId, capturedScopeId }`. Restored by reattaching to the deserialized scope. -- **Module bindings** — names → module identifiers; module instances are reconstructed by the runner (registry lookup), not serialized. - -When the runner snapshots: - -- Periodically: every N seconds (default 30s). -- On signal: SIGINT/SIGTERM triggers `dump()` at the next yield point. -- On explicit `dump()` from the host: API call returns once the in-flight host operation settles. - -When the runner resumes (`restore`): - -- Reads the snapshot. -- Re-parses the source, hashes the AST. Mismatch → reject: `source changed since snapshot was taken (hash X expected, got Y); pass --reset to discard`. -- Reconstructs scope chain and call stack from JSON. -- Re-attaches modules from the registry. -- Resumes the interpreter at the saved code pointer. - -What this gives us: - -- Plain JS authoring — no special primitives, no determinism rules, no `once`. The script just runs. -- True pause: a hung overnight superintendent run can be `dump`ed, the laptop closed, and `restore`d from the snapshot file the next morning. -- Cheap re-runs: kill mid-execution, resume picks up at the same `await`. No re-spawning agents, no re-committing. - -Limitations: - -- Snapshot resolution is bounded by yield points (`await`s). A snapshot can't land mid-expression in synchronous subset code; it lands at the next yield. For orchestration scripts this is fine — host calls are frequent. -- Editing the source invalidates the snapshot. Author opts to `--reset` and start fresh. -- Snapshot size is roughly proportional to live state. A pipeline holding a `tasks` array of 1000 items keeps that array in the snapshot. - -Opt-out: `run` with no `snapshotPath` does no checkpointing. - -### 2.8 Example — pipeline (`pipeline.md`) - -```yaml ---- -kind: pipeline -version: 1 -agents: - builder: - agent: claude-code - mode: yolo - prompt: | - Implement the assigned task. Follow TDD — write tests first. - reviewer: - agent: claude-code - mode: read - prompt: | - Review the diff for correctness, tests, and obvious regressions. -mcp: - search: - command: npx - args: ["-y", "@modelcontextprotocol/server-everything"] -tasks: - - id: fix-auth - title: Fix auth timeout - prompt: Fix the auth timeout regression in session refresh. - - id: add-retry - title: Add HTTP retry - prompt: Add exponential backoff retry to the HTTP client. ---- -``` - -Body: - -```js -import { spawn } from "agent"; -import { tasks, agents } from "harness"; -import { server } from "mcp"; -import { commit } from "git"; -import { event } from "log"; - -const search = server({ command: "npx", args: ["-y", "@modelcontextprotocol/server-everything"] }); - -await spawn(agents.builder, { prompt: "Install deps and run migrations." }); - -await tasks.reduce(async (previous, task) => { - await previous; - event("task.started", { id: task.id, title: task.title }); - await spawn(agents.builder, { - prompt: `${task.id}: ${task.title}\n\n${task.prompt}`, - mcp: { search } - }); - await spawn(agents.reviewer, { prompt: `Review the changes for ${task.id}.` }); - await commit({ message: `feat: ${task.id} - ${task.title}` }); - event("task.completed", { id: task.id, title: task.title }); -}, (async () => {})()); -``` - -### 2.9 Example — superintendent (`superintendent.md`) - -```yaml ---- -kind: superintendent -version: 1 -agents: - builder: - agent: claude-code - prompt: | - Build the plan referenced in the document body. - security: - agent: claude-code - mode: read - prompt: | - Review for auth, injection, secrets, validation issues. - perf: - agent: claude-code - mode: read - prompt: | - Review for performance regressions and obvious inefficiencies. - tests: - agent: claude-code - mode: read - prompt: | - Verify tests cover the changes and pass. - judge: - agent: claude-code - prompt: | - Given builder summary and inspector reports, approve or reject. - owner: - agent: claude-code - mode: read - prompt: | - Final owner review. Approve or reject. -maxRounds: 50 ---- -``` - -Body: - -```js -import { spawn } from "agent"; -import { agents, meta } from "harness"; -import { fail } from "fail"; - -const inspectors = [agents.security, agents.perf, agents.tests]; -const maxRounds = meta.frontmatter.maxRounds ?? 50; -let lastSummary = null; - -for (let round = 0; round < maxRounds; round++) { - const builder = await spawn(agents.builder, { - prompt: `Continue. Prior summary: ${lastSummary ?? "(none)"}`, - }); - - const reports = await Promise.all( - inspectors.map((insp) => spawn(insp, { prompt: `Inspect:\n\n${builder.summary}` })), - ); - - const verdict = await spawn(agents.judge, { - prompt: `Builder: ${builder.summary}\n\nInspectors:\n${ - reports.map((r, n) => `- ${inspectors[n].agent}: ${r.summary}`).join("\n") - }\n\nApprove or reject.`, - }); - - if (verdict.summary.toLowerCase().includes("approved")) { - const owner = await spawn(agents.owner, { prompt: `Verdict:\n\n${verdict.summary}` }); - if (owner.summary.toLowerCase().includes("approved")) return; - } - - lastSummary = verdict.summary; -} - -fail(`max rounds (${maxRounds}) reached without owner approval`); -``` - -Three inspectors run concurrently via `Promise.all`, cutting wall time roughly to the slowest inspector. A snapshot taken mid-loop captures the round counter, last summary, and any in-flight inspections; restore picks up from the same `await`. - -### 2.10 Example — experiment loop (`experiment.md`) - -```yaml ---- -kind: experiment -version: 1 -agents: - experimenter: - agent: claude-code - prompt: | - Make a single focused change to improve the metric. The journal of prior - attempts is provided in each turn — do not repeat what didn't work. -metric: - name: tests - direction: maximize -maxKept: 5 ---- -``` - -Body: - -```js -import { spawn } from "agent"; -import { agents, meta } from "harness"; -import { checkpoint, commit, revert } from "git"; -import { run as runMetric } from "metric"; - -const baseline = await runMetric("tests"); -const maxKept = meta.frontmatter.maxKept ?? 5; -const attempts = []; -let kept = 0; - -while (kept < maxKept) { - const savepoint = await checkpoint(); - const attempt = attempts.length + 1; - - try { - await spawn(agents.experimenter, { - prompt: `Improve "tests".\n\nLast attempts:\n${ - attempts.slice(-10).map((a) => JSON.stringify(a)).join("\n") - }`, - }); - const score = await runMetric("tests"); - - if (score >= baseline) { - await commit({ message: `experiment ${attempt}: kept (score=${score})` }); - kept += 1; - attempts.push({ event: "kept", attempt, score }); - } else { - await revert(savepoint); - attempts.push({ event: "discarded", attempt, score }); - } - } catch (e) { - await revert(savepoint); - attempts.push({ event: "failed", attempt, error: e.message }); - } -} -``` - -`attempts` is a plain JS array. A snapshot captures it directly — no journal sidecar, no replay. Restore puts the array back as it was at the moment of pause. - -### 2.11 The harness — wiring - -"The script is the harness" means the script owns control flow, but a harness *layer* still exists: it loads the markdown, parses frontmatter, extracts the script block, registers modules, runs the interpreter, owns the snapshot file, and surfaces dashboard / cancellation / signals to the outer process. - -`@poe-code/agent-script` provides: - -- parser, linter, interpreter, snapshot/restore -- `runHarness(filepath, { modules, snapshotPath?, signal? })` — the loader: reads markdown, splits frontmatter, extracts the `js` block, lints, runs with the registered modules, checkpoints to `snapshotPath` -- standard module **factories** that build the registered module record: `makeAgentModule(spawnAgent)`, `makeHarnessModule(frontmatter, meta)`, `makeMcpModule(mcpClient)`, `makeGitModule(cwd)`, `makeMetricModule(npmRunner)`, `makeLogModule(events)`, `makeEnvModule(allowList)`, `makeFailModule()`, `makeTimeModule()` - -Each existing package becomes a thin wrapper that picks the module bundle and registers a CLI: - -```ts -// @poe-code/pipeline -import { runHarness, makeAgentModule, makeHarnessModule, - makeMcpModule, makeLogModule, makeEnvModule, - makeFailModule, makeTimeModule } from "@poe-code/agent-script"; -import { spawnAgent } from "@poe-code/agent-spawn"; -import { connectMcp } from "@poe-code/tiny-mcp-client"; - -export async function runPipeline(filepath: string, signal: AbortSignal) { - return runHarness(filepath, { - signal, - snapshotPath: `${filepath}.snapshot.json`, - modulesFor: (frontmatter, meta) => ({ - agent: makeAgentModule(spawnAgent), - harness: makeHarnessModule(frontmatter, meta), - mcp: makeMcpModule(connectMcp), - log: makeLogModule(), - env: makeEnvModule(["BUILDER_AGENT"]), - fail: makeFailModule(), - time: makeTimeModule(), - }), - }); -} -``` - -That's the whole pipeline package — a CLI command + this wiring. No YAML schema, no status writer, no task selector, no step resolver, no template engine, no `once`/`state` machinery. Roughly an order of magnitude smaller than today's `@poe-code/pipeline`. - -`@poe-code/superintendent` adds a TUI subscriber on the `log` module's event channel. `@poe-code/experiment-loop` adds `makeGitModule` and `makeMetricModule`. The shared CLI scaffolding (file discovery, `--yes`, `--tui`, `--reset` to discard the snapshot) lives in a tiny CLI helper. - -The frontmatter `kind` field is informational — humans and editors use it to know what kind of file this is. The runner doesn't dispatch on it; the user invokes the runner they want (`poe-code pipeline run`, `poe-code experiment run`). - -(Open question: should there be a single `poe-code run ` that dispatches on `kind` and picks the module bundle automatically? Tracked in Level 3.) - -### 2.12 Linter - -A separate, deterministic pass over the parsed AST. Runs before execution by default in `runHarness`; also exposed standalone as `lint(source, { filename, modules })` and as a CLI command: - -```sh -poe-code agent-script lint pipeline.md -``` - -Rules (each carries a stable code so users can suppress with comments if they ever need to): - -| Code | Severity | Description | -| ------ | ---------- | ------------- | -| `AS001` | error | Disallowed syntax: `function`, `class`, `new`, `this`, generators, `var`, `do`/`while`, `switch`, `with`, labels, regex literals, `eval`, `Function`. | -| `AS002` | error | Closure captures mutable binding — lambda closes over a `let`-bound name. Hint: change to `const`, or pass as a parameter. | -| `AS003` | error | Unknown identifier. Lists the declared/imported names in scope; suggests near-matches via Levenshtein. | -| `AS004` | error | Unknown module — `import` from a name not registered in the runner's module list. Lists registered module names. | -| `AS005` | error | Unknown export — `import { x }` where `x` is not exported by the named module. Lists actual exports. | -| `AS006` | warning | Unused import. | -| `AS007` | warning | Unused `const`/`let` binding. | -| `AS008` | error | `await` outside async function or top level. | -| `AS009` | error | Async arrow returning a host promise without `await` (likely the author forgot to await). Hint: add `await` or document that you really want a Promise back. | -| `AS010` | warning | Top-level `let` capturing host-call results that are never read again — likely unintended. | -| `AS011` | error | Prototype access (`__proto__`, `.prototype`, `.constructor`). | -| `AS012` | error | Disallowed property method — e.g. `String.prototype.replace` with a function or RegExp argument; `Array.prototype.sort` with an unsupported comparator pattern. | -| `AS013` | error | Reserved name: a top-level binding shadows a built-in module name (`agent`, `git`, `mcp`, ...). | -| `AS014` | error | Cyclic import. | -| `AS015` | warning | `Promise.race` with a single promise — likely a typo for `await`. | - -Diagnostic shape: - -```ts -type Diagnostic = { - code: string; // "AS002" - severity: "error" | "warning"; - message: string; - filename: string; - line: number; - column: number; - span: { start: { line, column }, end: { line, column } }; - hint?: string; // actionable suggestion -}; -``` - -The runner aborts before execution if any error-severity diagnostic is reported. - -### 2.13 Errors - -Every error carries `filename`, `line`, `column`, a one-line code excerpt with a caret, and a message that names the offending construct. Examples: - -```text -ParseError: harness.ajs:12:8 - - 10 | return { - 11 | builder: { - 12 | prompt: `Build ${plan path}`, - | ^ - 13 | }, - -Unexpected identifier "path" — did you mean "plan.path"? -``` - -```text -SandboxError: harness.ajs:7:14 - - 6 | const inspectors = ["a", "b", "c"]; - 7 | return inspectors.map(fn); - | ^ - -Cannot call undefined value "fn". The identifier "fn" is not defined in this scope. -``` - -```text -SandboxError: harness.ajs:23:3 - - 22 | while (true) { - 23 | tasks.push(makeTask()); - | ^ - -Step budget exceeded (1,000,000 steps). Likely an infinite loop. Increase budget.steps in the runner if intentional. -``` - -```text -DisallowedSyntaxError: harness.ajs:4:1 - - 3 | - 4 | async function build() { - | ^ - -Async functions are not supported in the sandbox subset. Use a synchronous function or a top-level expression. -``` - -Errors are values, not host `Error`s — the runner formats them. Errors thrown from host-injected functions surface as `SandboxError` with the host stack scrubbed and a short summary preserved. - -## 3. Implementation details and technical decisions - -Pending — drafted after Level 2 sign-off. - -## 4. Interfaces and test plan - -Pending — drafted after Level 2 sign-off. - -## 5. Code plan - -Pending — drafted after Level 2 sign-off. diff --git a/docs/plans/24-harness-session-runtime.md.lock b/docs/plans/24-harness-session-runtime.md.lock deleted file mode 100644 index 4e178b037e..0000000000 --- a/docs/plans/24-harness-session-runtime.md.lock +++ /dev/null @@ -1 +0,0 @@ -{"pid":50723,"host":"m5mb-kjopek","acquiredAt":"2026-05-04T16:31:48.004Z"} \ No newline at end of file From d1be5b607734de798ad240c4a757d53dba61d553 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 12:52:43 -0500 Subject: [PATCH 109/111] fix(agent-harness-tools): use plain * for task-list workspace dep npm ci does not support workspace: protocol; align with sibling deps. --- package-lock.json | 4 ++-- packages/agent-harness-tools/package.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index 2945b30f95..347f661730 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7289,9 +7289,9 @@ "@poe-code/agent-defs": "*", "@poe-code/design-system": "*", "@poe-code/file-lock": "*", - "@poe-code/task-list": "workspace:*", "@poe-code/poe-code-config": "*", - "@poe-code/process-runner": "*" + "@poe-code/process-runner": "*", + "@poe-code/task-list": "*" } }, "packages/agent-human-in-loop": { diff --git a/packages/agent-harness-tools/package.json b/packages/agent-harness-tools/package.json index 83161503ca..be4452126e 100644 --- a/packages/agent-harness-tools/package.json +++ b/packages/agent-harness-tools/package.json @@ -23,7 +23,7 @@ "@poe-code/agent-defs": "*", "@poe-code/design-system": "*", "@poe-code/file-lock": "*", - "@poe-code/task-list": "workspace:*", + "@poe-code/task-list": "*", "@poe-code/poe-code-config": "*", "@poe-code/process-runner": "*" } From ef7dffe4520520c9608c7c4221b7d4ed6c5dea64 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 12:57:51 -0500 Subject: [PATCH 110/111] fix(bundle): skip dynamic imports in undeclared-dep check Dynamic imports of optional peer deps (e.g. braintrust, loaded via `await import()` with a friendly catch) must not fail the bundle's declared-dependency audit. The previous `if`/`else-if` both added to the set, defeating the kind check. --- scripts/bundle.mjs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/scripts/bundle.mjs b/scripts/bundle.mjs index 61f189b5fa..48128319c8 100644 --- a/scripts/bundle.mjs +++ b/scripts/bundle.mjs @@ -257,16 +257,16 @@ await Promise.all( }) ); -// Verify every external import in dist/index.js is declared in root +// Verify every external static import in dist/index.js is declared in root // dependencies (or is a Node built-in). Missing deps would only surface // as ERR_MODULE_NOT_FOUND when the published package is installed. +// Dynamic imports are skipped: those are guarded at the call site (e.g. +// optional peerDependencies surfaced via try/catch with a friendly message). const externalImports = new Set(); for (const meta of Object.values(mainBuild.metafile.outputs)) { for (const imp of meta.imports ?? []) { if (imp.external && imp.kind !== "dynamic-import") { externalImports.add(imp.path); - } else if (imp.external) { - externalImports.add(imp.path); } } } From 8a3c4e27995b7dff6c2ce838bf2be37d680fa2bc Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Mon, 4 May 2026 15:49:02 -0500 Subject: [PATCH 111/111] docs: flesh out plan-browser default + reordering implementation --- .../12-plan-browser-default-and-reordering.md | 174 +++++++++++++++++- 1 file changed, 171 insertions(+), 3 deletions(-) diff --git a/docs/plans/12-plan-browser-default-and-reordering.md b/docs/plans/12-plan-browser-default-and-reordering.md index 99cfa76b04..a02915cf09 100644 --- a/docs/plans/12-plan-browser-default-and-reordering.md +++ b/docs/plans/12-plan-browser-default-and-reordering.md @@ -74,12 +74,180 @@ The browser is also available as `poe-code plan browse`. ## 3. Implementation details and technical decisions -_TBD._ +### Root command launches the browser + +Replace the catch-all `.action` in [src/cli/program.ts:536-548](src/cli/program.ts#L536-L548). Branch: + +- positional args present → existing `throwCommandNotFound(...)`. +- `process.stdin.isTTY && process.stdout.isTTY` → call the same code path as `plan browse` (see below). `--yes` propagates and the existing browser short-circuit at [packages/plan-browser/src/browser.ts:51-55](packages/plan-browser/src/browser.ts#L51-L55) renders the first plan. +- non-TTY → `this.outputHelp()` (current behavior). + +The `plan browse` action body already builds the right options object; lift it into `runPlanBrowserFromCli(program, container)` exported from [src/cli/commands/plan.ts](src/cli/commands/plan.ts) and invoke it from both call sites. No duplication. + +### Plan ordering through task-list + +Replace the fs-readdir + mtime sort in `discoverAllPlans` ([packages/plan-browser/src/discovery.ts:191-209](packages/plan-browser/src/discovery.ts#L191-L209)) with the same pattern already used by [packages/agent-harness-tools/src/plans.ts:146-155](packages/agent-harness-tools/src/plans.ts#L146-L155): + +```ts +openTaskList({ + type: "markdown-dir", + path: absoluteDir, + singleList: "plans", + frontmatterMode: "passthrough", + ignoreMalformed: true, + fs +}); +``` + +Iterate `taskList.list("plans").all()` (default order is priority, which for `markdown-dir` is on-disk prefix order). For each `Task`, read the file at `path.join(absoluteDir, ${entry-with-prefix}.md)` and reuse `readPlanMetadata` / `classifyPlanKind` to fill in `kind`, `format`, `title`, `detail`. The task-list backend strips the prefix from the id, so to recover the on-disk filename, list the directory once and build an `id → filename` map (mirrors `activePlanFilePaths` in agent-harness-tools). + +`PlanEntry` gains: + +- `id: string` — the task-list id (filename without `NN-` prefix and without `.md`). +- `displayIndex: number` — 1-based slot in the priority list, used for footer text and tests. + +`updatedAt` stays in the type for the `plan list` table's "Updated" column but is no longer the sort key. The trailing sort in `discoverAllPlans` is removed. + +### Move via shift+arrow + +In the browser loop, after rendering the list, when the prompt resolves with a `reorder` action (see "Reorderable select prompt" below): + +- `Shift+↑` at `i === 0` → ignore (no-op already filtered by the prompt before invoking the callback). +- `Shift+↓` at `i === plans.length - 1` → ignore. +- `Shift+↑` otherwise → `tasks.move(plans[i].id, { before: plans[i - 1].id })`. +- `Shift+↓` otherwise → `tasks.move(plans[i].id, { after: plans[i + 1].id })`. + +`move` rewrites prefixes via `rewriteListPrefixes` ([packages/task-list/src/backends/markdown-dir.ts:995](packages/task-list/src/backends/markdown-dir.ts#L995)). After the call resolves, re-run `discoverAllPlans`, locate the moved plan by `id`, and re-render the prompt with the cursor pinned to that index. The prompt is re-entered (closed and reopened) rather than mutating in-place — avoids state-machine complexity in the prompt and keeps each render a function of fresh discovery output. + +### Reorderable select prompt + +`@clack/prompts` `select` does not expose key bindings, and `@clack/core` is not yet a direct dep. Instead of subclassing clack, build a small standalone prompt in [packages/design-system/src/prompts/primitives/](packages/design-system/src/prompts/primitives/) named `selectReorderable.ts`, modelled on the keypress plumbing already in [packages/design-system/src/dashboard/terminal.ts:70-220](packages/design-system/src/dashboard/terminal.ts#L70-L220): + +- `readline.emitKeypressEvents(stdin)` + `stdin.setRawMode(true)`. +- Render the list using the existing styled output helpers from `text` and `chalk` so the prompt visually matches `select`. +- Key map: + - `up` / `k` → cursor up + - `down` / `j` → cursor down + - `return` → resolve with the highlighted value + - `escape` / `q` / `ctrl+c` → resolve with the cancellation symbol (reuse `isCancel` plumbing from [packages/design-system/src/prompts/primitives/cancel.ts](packages/design-system/src/prompts/primitives/cancel.ts)) + - `up` with `shift === true` → `await onReorder("up", index)`, then re-render with the returned `{ options, cursor }` + - `down` with `shift === true` → `await onReorder("down", index)`, same + +Footer line: `text.muted("↑↓ navigate · ⇧↑ ⇧↓ reorder · enter open · q quit")`, rendered below the list. Hidden when the prompt is non-interactive. + +**Terminal compatibility for shift+arrow.** The prompt uses what Node's `readline` keypress parser already produces. iTerm2, kitty, Alacritty, WezTerm, Ghostty, VS Code's integrated terminal, and Linux gnome-terminal all emit `CSI 1;2A` / `CSI 1;2B` for shift+up/shift+down, which `readline` decodes as `{ name: "up", shift: true }` / `{ name: "down", shift: true }`. macOS Terminal.app does not — there shift+arrow is silently equivalent to plain arrow. We accept that limitation and document it in the package README; users on Terminal.app see the same footer hint, but the keys are no-ops. + +Public API: + +```ts +export type ReorderDirection = "up" | "down"; + +export interface SelectReorderableOption { + value: Value; + label: string; + hint?: string; +} + +export interface SelectReorderableOptions { + message: string; + options: SelectReorderableOption[]; + initialValue?: Value; + footer?: string; + onReorder?: ( + direction: ReorderDirection, + currentIndex: number + ) => Promise<{ options: SelectReorderableOption[]; cursor: number }>; +} + +export async function selectReorderable( + opts: SelectReorderableOptions +): Promise; +``` + +Re-export from [packages/design-system/src/prompts/index.ts](packages/design-system/src/prompts/index.ts) and the package's public index. + +### Archive / delete migrate to task-list + +`archiveBrowserPlan` and `deletePlan` in [packages/plan-browser/src/actions.ts](packages/plan-browser/src/actions.ts) become wrappers that take a `Tasks` handle and call `tasks.fire(id, "archive")` and `tasks.delete(id)` respectively. The task-list `archive` event already repacks via `rewriteListPrefixes` ([packages/task-list/src/backends/markdown-dir.ts:927](packages/task-list/src/backends/markdown-dir.ts#L927)). The CLI subcommands `plan archive` / `plan delete` switch to the same flow. `editPlan` is unchanged (no fs mutation). + +### Out of scope + +- gh-issues / yaml-file backends (the task-list move/archive contract is the same, but those backends are not used for plans today). +- A general-purpose multi-key sortable prompt — `selectReorderable` is plan-browser's only consumer at the moment; lift to a generic helper only if a second consumer appears. +- Search / filter inside the browser. ## 4. Interfaces and test plan -_TBD._ +### Public interfaces touched + +| Surface | Change | +| --- | --- | +| `@poe-code/design-system` | Adds `selectReorderable` (and its types) to public exports. | +| `@poe-code/plan-browser` | `PlanEntry` gains `id: string`, `displayIndex: number`. `runPlanBrowser` signature unchanged. `discoverAllPlans` no longer accepts `updatedAt` as a sort key (no caller passes it; type stays). | +| `poe-code` CLI | New behavior: `poe-code` with no args opens browser when TTY. No new flag. | + +### Test plan (TDD) + +New tests written first. + +1. **`packages/design-system/src/prompts/select-reorderable.test.ts`** (memfs not needed; uses streams): + - drives the prompt via a mocked stdin that emits keypress sequences (mirrors [packages/design-system/src/dashboard/terminal.test.ts](packages/design-system/src/dashboard/terminal.test.ts)) + - asserts: arrow navigation moves cursor; `enter` resolves selected value; `escape` cancels; `q` cancels; `shift+up` calls `onReorder("up", i)` and re-renders with returned cursor; `shift+up` at index 0 does *not* invoke `onReorder`; same for `shift+down` at last index; footer is rendered. + +2. **`packages/plan-browser/src/discovery.test.ts`** (rewrite, uses memfs + task-list with `fs` injected): + - assert prefix-order traversal: `01-…`, `02-…`, `21-…` returned in that order regardless of mtime. + - assert plans missing frontmatter still load (`ignoreMalformed: true`). + - assert each `PlanEntry.id` matches the filename's id-after-prefix. + +3. **`packages/plan-browser/src/browser.move.test.ts`** (new): + - drives the browser with a fake `selectReorderable` that scripts a `shift+down` then `enter`. + - asserts the underlying `tasks.move` was called with `{ after: }` and the file on disk is renamed (memfs + injected `fs`). + - asserts cursor follows the moved plan into its new slot on the second render. + +4. **`packages/plan-browser/src/actions.test.ts`** (update): + - archive now goes through `tasks.fire(id, "archive")`; assert remaining plans' prefixes are repacked (read directory after archive). + - delete goes through `tasks.delete(id)`; assert remaining plans' prefixes are repacked. + +5. **`src/cli/program.test.ts`** — extend `bootstrap`/program tests with: + - no-args + TTY → invokes the lifted `runPlanBrowserFromCli` (mock the function, assert called). + - no-args + non-TTY → prints help (assert the lifted function was *not* called). + - args present (`poe-code totally-not-a-command`) → still hits `throwCommandNotFound`. + +6. **`packages/plan-browser/src/browser.e2e.test.ts`** (extend): + - end-to-end with real `markdown-dir` (memfs): create three plans, run a `shift+down` + `q` script, exit, then read directory and assert prefixes were renamed (`01-a.md`, `02-b.md`, `03-c.md` → `01-b.md`, `02-a.md`, `03-c.md`). + +7. **Visual validation** (manual, not a test): run `npm run screenshot-poe-code --` with no further args on a TTY-emulating wrapper or capture iTerm output; verify list, footer, and that shift+arrow renames a file. Also `npm run screenshot-poe-code -- --help` to confirm help is unchanged on non-TTY. + +### Integration / regression coverage + +- Existing `plan-root-command.test.ts` keeps passing — `plan browse` still works, `--kind`, `--yes` still pass through. +- `agent-harness-tools` plans tests (which already use the same task-list pattern) catch any cross-package regression in the markdown-dir backend. ## 5. Code plan -_TBD._ +Numbered to match the order of TDD red→green slices. + +1. **Add `selectReorderable` (design-system).** + - Files: new [packages/design-system/src/prompts/primitives/select-reorderable.ts](packages/design-system/src/prompts/primitives/select-reorderable.ts), new test `select-reorderable.test.ts` next to it. Re-export from [packages/design-system/src/prompts/index.ts](packages/design-system/src/prompts/index.ts) and [packages/design-system/src/index.ts](packages/design-system/src/index.ts). + - Steps: write tests (mock-stdin keypresses, assert behavior), implement using `readline.emitKeypressEvents` + raw mode + ANSI cursor save/restore for redraw. + +2. **Switch `discoverAllPlans` to task-list.** + - Files: [packages/plan-browser/src/discovery.ts](packages/plan-browser/src/discovery.ts), [packages/plan-browser/src/types.ts](packages/plan-browser/src/types.ts), [packages/plan-browser/src/discovery.test.ts](packages/plan-browser/src/discovery.test.ts). + - Add `id` and `displayIndex` to `PlanEntry`. Replace `discoverSharedPlans` with a task-list-backed implementation that mirrors [packages/agent-harness-tools/src/plans.ts:174-200](packages/agent-harness-tools/src/plans.ts#L174-L200). Drop the `updatedAt` sort. + +3. **Migrate archive / delete to task-list.** + - Files: [packages/plan-browser/src/actions.ts](packages/plan-browser/src/actions.ts), [packages/plan-browser/src/actions.test.ts](packages/plan-browser/src/actions.test.ts), and the CLI sites in [src/cli/commands/plan.ts](src/cli/commands/plan.ts) (`executePlanAction` cases for archive / delete). + - Open the task-list once per CLI call; re-use the same opener helper as discovery (factor `openPlansTaskList` into a small internal helper in plan-browser). + +4. **Wire reorder into the browser.** + - Files: [packages/plan-browser/src/browser.ts](packages/plan-browser/src/browser.ts), new `browser.move.test.ts`, extend `browser.e2e.test.ts`. + - Replace the `select` call with `selectReorderable`, supplying `onReorder` that calls `tasks.move(...)`, re-runs `discoverAllPlans`, and returns `{ options, cursor }` keyed on the moved plan's `id`. Pass through the footer string as a single line. + +5. **Make `poe-code` (no args) launch the browser.** + - Files: [src/cli/program.ts](src/cli/program.ts), [src/cli/commands/plan.ts](src/cli/commands/plan.ts) (export `runPlanBrowserFromCli`), [src/cli/program.test.ts](src/cli/program.test.ts). + - Extract the `plan browse` action body into `runPlanBrowserFromCli(program, container)` and invoke from both. In `program.action`, check `process.stdin.isTTY && process.stdout.isTTY` before invoking; otherwise `outputHelp()`. + +6. **README addition.** + - File: top-level project README. Add the section in §2 of this plan under "Quick start". Per CLAUDE.md, get explicit user sign-off before editing the README. + +7. **Build, lint, type-check, run all package tests, then run the e2e plan-browser test.** Capture screenshots for the new browser footer and the no-args launch path before declaring done.