mirror of
https://github.com/software-mansion/argent.git
synced 2026-09-14 19:27:14 +08:00
afd722924f
## Problem
Only one flow could be recorded at a time, anywhere on the machine.
Recording state was three module globals in `flow-utils.ts` — harmless
in a per-client process, but the tool-server is a **host-wide singleton
per install bundle**. Every MCP client, every subagent sharing a
parent's connection, every `argent` CLI call and every project on the
machine attaches to the same process, the same `Registry`, and those
same three globals. HTTP requests are served concurrently with no
serialization.
Three failures followed, all reproduced against the pre-change code:
1. **A second recording clobbered the first.** `startRecordingSession`
just overwrote, so the first agent's next `flow-add-step` silently
appended into the *other* agent's flow file — in a different project.
2. **Any agent could finish any agent's recording.**
`flow-finish-recording`'s schema was literally `z.object({})`.
3. **Replay stomped recording.** `resolveFlowFilePath` called
`setActiveProjectRoot`, so a `flow-execute` in project B rebound the
global root mid-recording of project A. Already worked around, locally
only, in `flow-add-step`.
## Approach
Recording state is now a `Map` keyed by the resolved flow file path,
`<project_root>/.argent/flows/<name>.yaml` — the identity of the
artifact being built, so "same key" means "same output file" and two
sessions on one key are a genuine collision rather than an accident of
scoping. `flow-add-step`, `flow-add-echo` and `flow-finish-recording`
each take `name` + `project_root`, so every call is self-contained;
required rather than optional-with-fallback, since a fallback would
succeed while an agent is alone and fail only once a second recording
exists.
`resolveFlowFilePath` is pure, which fixes defect 3 and retires
`FLOW_PROJECT_ROOT_REQUIRED` (the state it guarded can no longer exist).
Rejected alternatives — keying by device udid (flows are deliberately
device-portable, and `flow-add-echo`/`flow-finish-recording` have no
device at all), an opaque `recordingId` (an agent that loses the token
cannot recover), and per-caller identity from the transport
(`ToolContext` carries no caller identity, and subagents share their
parent's MCP connection, so it would fail the exact scenario being
fixed).
### Locking, and why readers needed more than a lock
Every mutation of one flow file runs under a lock keyed by that path —
appends, `flow-start-recording`'s truncate-and-register, and
`flow-finish-recording`'s read-summarize-clear. Keyed by file rather
than owned by the session, because a restart *replaces* the session: a
session-owned lock cannot exclude the operation that supersedes it. Per
file, not global, so two recordings never queue behind each other. An
append whose session was finished, restarted or evicted meanwhile fails
with `FLOW_NO_ACTIVE_RECORDING` rather than writing into a different
take.
The lock serializes writers only, and no reader of a flow YAML can join
it — `flow-execute`'s own load, its `run:` fragment load,
`flow-read-prerequisite`, `flow-add-step`'s sibling-fragment check, and
the `argent` CLI reading from another process entirely, where an
in-process lock cannot reach. Both writers used a plain `fs.writeFile`,
which opens `O_TRUNC`, so a reader could land between the truncate and
the write. That case is silent: `parseFlow("")` returns `{ steps: [] }`
with no error and `summarize` derives `ok` from "no failures", so a
`flow-execute` racing an append reports a **top-level PASS having
replayed zero steps**. Both writes now go through a sibling temp file
and a rename, so a reader sees either the whole old file or the whole
new one — and unlike the lock, that also holds cross-process.
### `stop-all-simulator-servers` gets a `devices` scope
Every agent is told to call this at session end, and unscoped it walked
the whole registry — so agent A wrapping up tore down agent B's devtools
mid-recording, degrading B's flow to brittle coordinate taps. It now
takes an optional `devices` scope and reports `unmatched` ids, so a
mistyped id doesn't read as a clean machine.
Which namespaces count as "owned by a device" turned out to be the
load-bearing part, because nothing cascades to most of them and
`unmatched` turns any omission into an actively wrong diagnosis — a
correct device id reported as a typo. The set now covers `AXService`
(the in-sim ax daemon, spawned `--timeout 3600`; an iOS session that
only ran boot/launch/describe owns this and nothing else),
`ScreenRecordingSession` (an ffmpeg child plus the touch-visualizer
overlay it enabled on the device), `NativeProfilerSession` (an xctrace
child, or an on-device perfetto process and its trace file) and
`JsRuntimeDebugger` (a bound loopback server, the CDP socket to Metro, a
log handle). The debugger URNs interpose the Metro port —
`<ns>:<port>:<deviceId>` — so the matcher understands both shapes,
consuming only the first colon so a wireless adb serial after the port
still compares whole.
`stop-simulator-server` shared none of this and had drifted: it looked
URNs up with an exact, case-sensitive `services.get()`, so a lower-cased
UDID silently no-op'd there while the scoped stop-all reaped it. Both
tools now share one matcher. Their namespace *sets* stay deliberately
different, documented where they are defined — `stop-simulator-server`
is also the documented recovery for a wedged transport, and widening it
to devtools/AX would make a routine retry drop the native-devtools
connection another agent's recording depends on, which is the hazard the
`devices` scope exists to prevent.
## Verification
**End-to-end, three devices, one shared tool-server** (iPhone 16 Pro,
iPhone 17 Pro, Pixel 3a): three interleaved recordings, plus an
unrelated `flow-execute` in a fourth project while all three were live.
Both iOS devices held their own live native-devtools concurrently (two
per-UDID sockets, `connected: true`). Each YAML contained exactly its
own steps in order, taps captured as selectors rather than coordinates,
and neither picked up another's or the third root's path. All three
replayed green — also through the **released 0.17.0 CLI** against the
modified server, which checks wire compatibility. A device-scoped
teardown of sim 1 left sim 2 and the emulator running.
Re-run against the final build:
- Two interleaved recordings across two project roots on one device,
with a **separate process** polling one of the flow files as fast as it
could for the duration. Zero empty or truncated observations; each YAML
held exactly its own steps; both replayed green (6/6 and 5/5). Against
the pre-change in-place write the same reader observes zero-step reads
interleaved among the real ones — the silent-PASS input.
- A scoped teardown of the iPhone reaped `AXService` and
`NativeDevtools` for that UDID only, reported no `unmatched`, and left
the second sim and the emulator running. Lower-casing the UDID matched;
a genuinely bogus id was still reported.
- With a screen recording live on the Pixel 3a, a scoped teardown reaped
`ScreenRecordingSession` and the **ffmpeg child actually exited** (1 →
0). Before the fix it survived to the 180 s cap while the tool called
the correct serial a typo.
The pre-change repros were re-run afterwards to confirm observed
behavior changed, not just the tests.
`npx vitest run` in `packages/tool-server` (295 files, 3154 tests) and
`packages/argent-cli` (280), `tsc --build`, `tsc --noEmit` on both test
projects, eslint and prettier — all green.
## Review notes
Several rounds of review found real defects in this change; each was
reproduced before fixing and re-verified after. Worth knowing when
reading the diff, since the tests exist to pin them:
- `flow-start-recording` truncated the `.yaml` outside any lock, so a
step from the take being discarded landed in the freshly reset file and
was reported as success (26-29 of 200 runs).
- `flow-finish-recording` never took the lock; its `await fs.readFile`
was a yield during which a concurrent append committed, leaving the
reported summary disagreeing with disk (11-16 of 200).
- A failed finish destroyed the recording. Hand-editing the `.yaml`
mid-recording is a documented workflow, so `parseFlow` can legitimately
throw — and the error told the agent to call `flow-start-recording`,
which truncates the very take it would recover.
- `unmatched` reported a device this session had just stopped, because
`disposeService` returns a node to IDLE and keeps it.
- A bare IP claimed every wireless-adb device at that address, since an
adb serial is itself `ip:port`.
- The eviction backstop stamped with `Date.now()`; ties at millisecond
resolution let it drop the session that was just used.
- `requireRecordingSession` ended with "Call flow-start-recording first"
— reached for a key that was finished, superseded or evicted as well as
one never started, and on those branches the file on disk is fully
populated while that call truncates it and reports no `restarted`.
- The atomic write regressed twice on its own terms: its scratch name
was derived from the flow file's basename, which has no length cap, so a
long flow name that appended fine before failed `ENAMETOOLONG`; and the
cleanup guard began after the temp file was created, leaking a scratch
file into a committed directory on any write that failed after opening.
- Two tests passed against implementations they claimed to reject: the
`stop-simulator-server` narrowness guard used a udid that classifies as
*android*, where the iOS-only services it guards can never appear, so
widening the iOS branch kept it green; and the client-mode finish
asserted only the *shape* of `savedTo`, never its content, though that
directive is the only thing that lands the file in client mode.
## Notes for reviewers
- Client/remote persist mode is the least-exercised path, and now has
its own concurrency tests (overlapping appends, and a restart
superseding an in-flight one) — it previously had none. The
`project_root` key is byte-stable across the file boundary (`kind:
"probe"` passes it through unchanged), which is what keeps a remote
recording addressable from `flow-add-step`, which declares no file
input.
- Two spellings of one flow file still mint two sessions — and two
independent locks — over one file, which bypasses every guarantee here.
Two ways in: the root spelled two ways (a symlink, or a case variant on
APFS), and the likelier one, the *name* cased two ways on a
case-insensitive volume. Neither is normalized away because the correct
normalization is the filesystem's: case-folding the key would wrongly
merge two distinct flows on ext4, and resolving symlinks is impossible
in client mode, where the root does not exist on this host. Documented
at `getFlowPath`.
- No recording tool can detect that another agent took its key.
`flow-add-step`, `flow-add-echo` and `flow-finish-recording` all
re-resolve the key on every call, so after a takeover they act on
whichever take is now live and report success: an append lands in the
other agent's file, and a finish finishes and clears it. The only case
that fails loudly is the narrow one the liveness check covers - an
append already IN FLIGHT when the restart lands. There is no caller
identity to key ownership on (see the rejected alternatives above), so
this is spelled out for the agent under "Pick a name unique to your
task" in `argent-create-flow` rather than mechanized.
- Skew hazard in one direction only: a *new* client against an *older*
tool-server. Zod strips the undeclared `name`/`project_root`, and the
old server falls back to its module globals — so concurrent recordings
silently collapse onto one session. The other direction (released 0.17.0
CLI against this server) was verified end-to-end.
- `packages/argent-private/docs/reference.md` still describes
`flow-add-step` as appending to "the current recording", and names two
tool ids that do not exist (`flow-insert-echo`/`flow-run` are file
names; the ids are `flow-add-echo`/`flow-execute`). It is a submodule,
so the fix cannot ride on this branch.
- A restart reported `discardedSteps` from the superseded session's
in-memory flow while it truncates the *file*. Hand-editing the `.yaml`
mid-recording is documented, so the two diverge: four steps wiped, one
reported. It now counts the file, and reports no number at all when that
file cannot be read or parsed - 0 is the answer a genuinely empty take
gives. Client mode still counts from memory (this host cannot see the
client's file), and the description now says which mode it is promising.
- `ChromiumJsRuntimeDebugger` cascades from `ChromiumCdp` and was
therefore already being torn down - silently, while `NetworkInspector`
and `ReactProfilerSession` cascade the same way and were named.
`stopped` is documented as the services that were live and got shut
down, so it is listed now too.
- The client-mode case named for a superseded in-flight append restarted
*between* calls, so the next append re-resolved the key and succeeded -
the guard was never reached, and neutering it left the whole file green.
It now parks an append in its live sub-tool call across the restart.
- `stop-tools.test.ts`' mock handed the tool the live service map where
the real `getSnapshot` copies, so a cascade rewrote the state the sweep
was still reading and the answer depended on map insertion order. The
mock copies and recurses like `_teardown` now, and the cascade case runs
under both orders.
- Prose the code contradicted, each verified against source before
rewriting: Vega owns `JsRuntimeDebugger`/`NetworkInspector` once the
debugger has run (and can match anything at all through an ERROR node);
"nothing here cascades" was denied twice in its own file; an iOS
boot/launch/describe session owns `NativeDevtools` too; `:tcp` is
mintable but unreached in production; the tool-server is a singleton
*per install bundle*, not per machine; `argent flow list` does enumerate
`.argent/flows`; the stop-tools comments narrated a "before" that only
existed on this branch.
Found while verifying, out of scope, worth their own issues: a `tool:
flow-execute` self-reference recurses past both cycle guards (`run:` is
guarded, a nested `flow-execute` reseeds the stack); react-profiler
artifacts collide host-wide on a second-resolution filename;
`stop-metro` is port-scoped and kills another agent's bundler;
`debugger-reload-metro`'s HTTP fallback broadcasts to every attached
client. A tool's `capability` is enforced only by the HTTP layer, not by
`registry.invokeTool`, so a call that reaches the registry another way -
`flow-add-step` takes `command` as a bare string - can resolve a service
the tool declares it does not support, leaving an ERROR node behind
(e.g. `SimulatorServer:<vega serial>`).
---------
Co-authored-by: Hubert Gancarczyk <claude-hubert.gancarczyk@swmansion.com>
542 lines
22 KiB
TypeScript
542 lines
22 KiB
TypeScript
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
|
import supertest from "supertest";
|
|
import * as fs from "node:fs/promises";
|
|
import * as os from "node:os";
|
|
import * as path from "node:path";
|
|
import { ArtifactStore, type Registry, type ToolContext } from "@argent/registry";
|
|
import { createHttpApp, type HttpAppHandle } from "../src/http";
|
|
import { createRunFlowTool } from "../src/tools/flows/flow-run";
|
|
import { flowReadPrerequisiteTool } from "../src/tools/flows/flow-read-prerequisite";
|
|
import { serializeFlow } from "../src/tools/flows/flow-utils";
|
|
|
|
vi.mock("../src/utils/update-checker", () => ({
|
|
getUpdateState: vi.fn(() => ({ updateInstallable: false, currentVersion: "1.0.0" })),
|
|
isUpdateNoteSuppressed: vi.fn(() => true),
|
|
suppressUpdateNote: vi.fn(),
|
|
}));
|
|
|
|
const DEVICE = "00000000-0000-0000-0000-0000000000ab";
|
|
|
|
/** The registry flow-execute dispatches its steps through — never the flow source. */
|
|
function stepRegistry(): Registry {
|
|
return {
|
|
invokeTool: vi.fn(async (id: string) => {
|
|
if (id === "list-devices") return { devices: [] };
|
|
return { ok: true };
|
|
}),
|
|
getTool: vi.fn(() => undefined),
|
|
resolveService: vi.fn(async () => ({
|
|
isConnected: () => true,
|
|
listConnectedBundleIds: () => [],
|
|
})),
|
|
} as unknown as Registry;
|
|
}
|
|
|
|
/**
|
|
* A registry exposing the REAL flow-execute and flow-read-prerequisite tools,
|
|
* so a POST exercises the whole chain a forged wrapper must traverse: HTTP
|
|
* file-input resolution → resolveFlowSource's boundary gate → step dispatch /
|
|
* prerequisite read. Both tools are here because they share the pre-flight
|
|
* contract: the file this suite proves flow-execute runs must be the one
|
|
* flow-read-prerequisite answers about.
|
|
*/
|
|
function httpRegistry(steps: Registry): Registry {
|
|
const tools: Record<
|
|
string,
|
|
ReturnType<typeof createRunFlowTool> | typeof flowReadPrerequisiteTool
|
|
> = {
|
|
"flow-execute": createRunFlowTool(steps),
|
|
"flow-read-prerequisite": flowReadPrerequisiteTool,
|
|
};
|
|
return {
|
|
getSnapshot: vi.fn(() => ({
|
|
services: new Map(),
|
|
namespaces: [],
|
|
tools: Object.keys(tools),
|
|
})),
|
|
getTool: vi.fn((id: string) => tools[id]),
|
|
invokeTool: vi.fn(async (id: string, args: unknown, opts?: Partial<ToolContext>) => {
|
|
const tool = tools[id];
|
|
if (!tool) throw new Error(`unexpected tool "${id}"`);
|
|
return tool.execute({}, args as never, {
|
|
artifacts: new ArtifactStore(),
|
|
...opts,
|
|
});
|
|
}),
|
|
} as unknown as Registry;
|
|
}
|
|
|
|
let tmpDir: string;
|
|
let projectRoot: string;
|
|
let flowPath: string;
|
|
let steps: Registry;
|
|
let handle: HttpAppHandle;
|
|
let originalToken: string | undefined;
|
|
|
|
beforeEach(async () => {
|
|
originalToken = process.env.ARGENT_AUTH_TOKEN;
|
|
delete process.env.ARGENT_AUTH_TOKEN; // dev mode — auth is covered elsewhere
|
|
tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "http-flow-path-test-"));
|
|
// The YAML sits outside the declared project root — the reach a forged
|
|
// wrapper would gain over the name/flow_file branch's containment.
|
|
projectRoot = path.join(tmpDir, "project");
|
|
await fs.mkdir(projectRoot);
|
|
flowPath = path.join(tmpDir, "out-of-project.yaml");
|
|
await fs.writeFile(
|
|
flowPath,
|
|
serializeFlow({
|
|
executionPrerequisite: "",
|
|
steps: [
|
|
{ kind: "echo", message: "over the boundary" },
|
|
{ kind: "tool", name: "tap", args: { x: 0.5, y: 0.5 } },
|
|
],
|
|
}),
|
|
"utf8"
|
|
);
|
|
steps = stepRegistry();
|
|
handle = createHttpApp(httpRegistry(steps));
|
|
});
|
|
|
|
afterEach(async () => {
|
|
handle?.dispose();
|
|
await fs.rm(tmpDir, { recursive: true, force: true });
|
|
if (originalToken === undefined) delete process.env.ARGENT_AUTH_TOKEN;
|
|
else process.env.ARGENT_AUTH_TOKEN = originalToken;
|
|
});
|
|
|
|
describe("flow-execute flow_path over HTTP", () => {
|
|
it("rejects a hand-crafted stat-less wrapper without executing the YAML", async () => {
|
|
const res = await supertest(handle.app)
|
|
.post("/tools/flow-execute")
|
|
.send({
|
|
project_root: projectRoot,
|
|
device: DEVICE,
|
|
flow_path: { __argentFileInput: true, path: flowPath },
|
|
});
|
|
|
|
// The server's own stat succeeds (presentOnHost), but no client stat was
|
|
// matched — the gate must refuse before any step dispatches.
|
|
expect(res.status).toBe(500);
|
|
expect(res.body.error).toMatch(/flow_path file-input boundary/);
|
|
expect(steps.invokeTool).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects a size-only wrapper without executing the YAML", async () => {
|
|
const st = await fs.stat(flowPath);
|
|
const res = await supertest(handle.app)
|
|
.post("/tools/flow-execute")
|
|
.send({
|
|
project_root: projectRoot,
|
|
device: DEVICE,
|
|
flow_path: { __argentFileInput: true, path: flowPath, size: st.size },
|
|
});
|
|
|
|
// The size is the real file's, so the wrapper resolves in place — but a
|
|
// size is knowable without ever having statted the file, so half the
|
|
// client stat must not clear the boundary the stat-less wrapper cannot.
|
|
expect(res.status).toBe(500);
|
|
expect(res.body.error).toMatch(/flow_path file-input boundary/);
|
|
expect(steps.invokeTool).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects an mtime-only wrapper without executing the YAML", async () => {
|
|
const st = await fs.stat(flowPath);
|
|
const res = await supertest(handle.app)
|
|
.post("/tools/flow-execute")
|
|
.send({
|
|
project_root: projectRoot,
|
|
device: DEVICE,
|
|
flow_path: { __argentFileInput: true, path: flowPath, mtimeMs: st.mtimeMs },
|
|
});
|
|
|
|
// The mirror-image half: a matching mtime with no size on the wire is
|
|
// still not the both-fields evidence statVerified stands for.
|
|
expect(res.status).toBe(500);
|
|
expect(res.body.error).toMatch(/flow_path file-input boundary/);
|
|
expect(steps.invokeTool).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects a relative flow_path without blaming the boundary it cleared", async () => {
|
|
// The spelling `argent flow list` prints. Running the server from the
|
|
// flow's own directory is what makes this wrapper legitimate: it stats the
|
|
// relative path against this process's cwd, finds the file, and matches the
|
|
// client-recorded stat — presentOnHost and statVerified both hold, so the
|
|
// rejection must name the path's shape rather than the boundary.
|
|
const originalCwd = process.cwd();
|
|
process.chdir(tmpDir);
|
|
try {
|
|
const relPath = path.basename(flowPath);
|
|
const st = await fs.stat(relPath);
|
|
const res = await supertest(handle.app)
|
|
.post("/tools/flow-execute")
|
|
.send({
|
|
project_root: projectRoot,
|
|
device: DEVICE,
|
|
flow_path: { __argentFileInput: true, path: relPath, size: st.size, mtimeMs: st.mtimeMs },
|
|
});
|
|
|
|
expect(res.status).toBe(500);
|
|
expect(res.body.error).toMatch(/must be absolute/);
|
|
expect(res.body.error).not.toMatch(/file-input boundary/);
|
|
expect(steps.invokeTool).not.toHaveBeenCalled();
|
|
} finally {
|
|
process.chdir(originalCwd);
|
|
}
|
|
});
|
|
|
|
it("still validates project_root on the flow_path branch", async () => {
|
|
// `getFlowPath` validates the root, but only the `name` branch reaches it.
|
|
// Deleting `setActiveProjectRoot` — which ran unconditionally, ahead of
|
|
// both branches — left this branch with no check at all, so a relative or
|
|
// ".."-bearing root sailed through. Nothing reads project_root here today,
|
|
// which is exactly why the guardrail has to be pinned rather than assumed.
|
|
const st = await fs.stat(flowPath);
|
|
const wrapper = {
|
|
__argentFileInput: true,
|
|
path: flowPath,
|
|
size: st.size,
|
|
mtimeMs: st.mtimeMs,
|
|
};
|
|
|
|
for (const [root, expected] of [
|
|
["relative/root", /project_root must be an absolute path/],
|
|
[`${projectRoot}/../elsewhere`, /must not contain "\.\." segments/],
|
|
] as const) {
|
|
const res = await supertest(handle.app)
|
|
.post("/tools/flow-execute")
|
|
.send({ project_root: root, device: DEVICE, flow_path: wrapper });
|
|
|
|
expect(res.status).toBe(500);
|
|
expect(res.body.error).toMatch(expected);
|
|
expect(res.body.error_code).toBe("FLOW_PROJECT_ROOT_INVALID");
|
|
expect(steps.invokeTool).not.toHaveBeenCalled();
|
|
}
|
|
});
|
|
|
|
it('rejects a ".." flow_path whose kernel and lexical resolutions disagree', async () => {
|
|
// <tmp>/link -> <tmp>/deep/inner, so the kernel reads <tmp>/deep/flow.yaml
|
|
// while path.dirname keeps "<tmp>/link/.." and path.join collapses it to
|
|
// <tmp> — the run: sibling and __baselines__ would come from the wrong
|
|
// directory. Both siblings exist so the two resolutions are distinguishable.
|
|
await fs.mkdir(path.join(tmpDir, "deep", "inner"), { recursive: true });
|
|
await fs.symlink(path.join(tmpDir, "deep", "inner"), path.join(tmpDir, "link"));
|
|
await fs.writeFile(
|
|
path.join(tmpDir, "deep", "flow.yaml"),
|
|
serializeFlow({ executionPrerequisite: "", steps: [{ kind: "run", flow: "sib" }] }),
|
|
"utf8"
|
|
);
|
|
for (const [dir, marker] of [
|
|
[path.join(tmpDir, "deep"), "true sibling"],
|
|
[tmpDir, "lexical sibling"],
|
|
]) {
|
|
await fs.writeFile(
|
|
path.join(dir, "sib.yaml"),
|
|
serializeFlow({ executionPrerequisite: "", steps: [{ kind: "echo", message: marker }] }),
|
|
"utf8"
|
|
);
|
|
}
|
|
|
|
// The wrapper is legitimate: this stat goes through the kernel, so size and
|
|
// mtime are the real file's and the boundary gate is satisfied.
|
|
const viaSymlink = [tmpDir, "link", "..", "flow.yaml"].join(path.sep);
|
|
const st = await fs.stat(viaSymlink);
|
|
const res = await supertest(handle.app)
|
|
.post("/tools/flow-execute")
|
|
.send({
|
|
project_root: projectRoot,
|
|
device: DEVICE,
|
|
flow_path: {
|
|
__argentFileInput: true,
|
|
path: viaSymlink,
|
|
size: st.size,
|
|
mtimeMs: st.mtimeMs,
|
|
},
|
|
});
|
|
|
|
expect(res.status).toBe(500);
|
|
expect(res.body.error).toMatch(/must not contain "\.\." segments/);
|
|
expect(steps.invokeTool).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("diagnoses name + flow_path with the exactly-one rule when the saved flow does not exist", async () => {
|
|
// The old-client wire for the dual-source misuse: pre-skipWhenSet clients
|
|
// interpolate ${project_root}/.argent/flows/${name}.yaml whenever name is
|
|
// set — even alongside flow_path — and since "checkout" is not saved, the
|
|
// flow_file wrapper is path-only. Without the skip, the boundary 422s on
|
|
// that missing file before zod's exactly-one rule can run, telling the
|
|
// agent to re-create a flow it never asked for.
|
|
const st = await fs.stat(flowPath);
|
|
const res = await supertest(handle.app)
|
|
.post("/tools/flow-execute")
|
|
.send({
|
|
name: "checkout",
|
|
project_root: projectRoot,
|
|
device: DEVICE,
|
|
flow_path: { __argentFileInput: true, path: flowPath, size: st.size, mtimeMs: st.mtimeMs },
|
|
flow_file: {
|
|
__argentFileInput: true,
|
|
path: path.join(projectRoot, ".argent", "flows", "checkout.yaml"),
|
|
},
|
|
});
|
|
|
|
expect(res.status).toBe(400);
|
|
expect(res.body.error).toMatch(/Pass exactly one flow source: name or flow_path\./);
|
|
expect(res.body.error).not.toMatch(/was not found on the tool-server host/);
|
|
expect(steps.invokeTool).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("diagnoses name + flow_path with the exactly-one rule when the saved flow exists", async () => {
|
|
// Same misuse, but the unused saved flow resolves cleanly — the diagnosis
|
|
// must be identical to the nonexistent-name case above.
|
|
const savedPath = path.join(projectRoot, ".argent", "flows", "good.yaml");
|
|
await fs.mkdir(path.dirname(savedPath), { recursive: true });
|
|
await fs.writeFile(
|
|
savedPath,
|
|
serializeFlow({ executionPrerequisite: "", steps: [{ kind: "echo", message: "saved" }] }),
|
|
"utf8"
|
|
);
|
|
const savedSt = await fs.stat(savedPath);
|
|
const st = await fs.stat(flowPath);
|
|
const res = await supertest(handle.app)
|
|
.post("/tools/flow-execute")
|
|
.send({
|
|
name: "good",
|
|
project_root: projectRoot,
|
|
device: DEVICE,
|
|
flow_path: { __argentFileInput: true, path: flowPath, size: st.size, mtimeMs: st.mtimeMs },
|
|
flow_file: {
|
|
__argentFileInput: true,
|
|
path: savedPath,
|
|
size: savedSt.size,
|
|
mtimeMs: savedSt.mtimeMs,
|
|
},
|
|
});
|
|
|
|
expect(res.status).toBe(400);
|
|
expect(res.body.error).toMatch(/Pass exactly one flow source: name or flow_path\./);
|
|
expect(steps.invokeTool).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("diagnoses a dual-source call from a skipWhenSet-aware client the same way", async () => {
|
|
// A current client never derives flow_file alongside flow_path, so the
|
|
// wire carries both sources and no flow_file wrapper at all.
|
|
const st = await fs.stat(flowPath);
|
|
const res = await supertest(handle.app)
|
|
.post("/tools/flow-execute")
|
|
.send({
|
|
name: "checkout",
|
|
project_root: projectRoot,
|
|
device: DEVICE,
|
|
flow_path: { __argentFileInput: true, path: flowPath, size: st.size, mtimeMs: st.mtimeMs },
|
|
});
|
|
|
|
expect(res.status).toBe(400);
|
|
expect(res.body.error).toMatch(/Pass exactly one flow source: name or flow_path\./);
|
|
expect(steps.invokeTool).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("diagnoses name + flow_path with the exactly-one rule when the flow_path file does not resolve", async () => {
|
|
// The reciprocal of the missing-saved-flow case: this time the
|
|
// CALLER-authored source is the one that cannot resolve. The wrapper is
|
|
// path-only — the client cannot stat (let alone inline) a file that never
|
|
// existed. Without the flow_path spec's unwrap the boundary would 422 on
|
|
// it before zod's exactly-one rule runs, telling the agent to re-create a
|
|
// file the call never needed.
|
|
const res = await supertest(handle.app)
|
|
.post("/tools/flow-execute")
|
|
.send({
|
|
name: "checkout",
|
|
project_root: projectRoot,
|
|
device: DEVICE,
|
|
flow_path: { __argentFileInput: true, path: path.join(tmpDir, "nope.yaml") },
|
|
});
|
|
|
|
expect(res.status).toBe(400);
|
|
expect(res.body.error).toMatch(/Pass exactly one flow source: name or flow_path\./);
|
|
expect(res.body.error).not.toMatch(/was not found on the tool-server host/);
|
|
expect(steps.invokeTool).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("diagnoses an old-client dual-source wire where neither wrapper resolves", async () => {
|
|
// Worst case of the skew: a pre-skipWhenSet client derived flow_file for
|
|
// an unsaved name AND the caller mistyped flow_path, so both wrappers are
|
|
// path-only. Whichever spec ran first used to pick the error; the
|
|
// diagnosis must not consult either file.
|
|
const res = await supertest(handle.app)
|
|
.post("/tools/flow-execute")
|
|
.send({
|
|
name: "checkout",
|
|
project_root: projectRoot,
|
|
device: DEVICE,
|
|
flow_path: { __argentFileInput: true, path: path.join(tmpDir, "nope.yaml") },
|
|
flow_file: {
|
|
__argentFileInput: true,
|
|
path: path.join(projectRoot, ".argent", "flows", "checkout.yaml"),
|
|
},
|
|
});
|
|
|
|
expect(res.status).toBe(400);
|
|
expect(res.body.error).toMatch(/Pass exactly one flow source: name or flow_path\./);
|
|
expect(res.body.error).not.toMatch(/was not found on the tool-server host/);
|
|
expect(steps.invokeTool).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("still fails the boundary when a lone flow_path does not resolve", async () => {
|
|
// No name on the wire, so the unwrap must not fire: a flow_path-only call
|
|
// whose file resolves nowhere is a genuine boundary failure, and the 422
|
|
// guidance about the missing file is the right diagnosis.
|
|
const res = await supertest(handle.app)
|
|
.post("/tools/flow-execute")
|
|
.send({
|
|
project_root: projectRoot,
|
|
device: DEVICE,
|
|
flow_path: { __argentFileInput: true, path: path.join(tmpDir, "nope.yaml") },
|
|
});
|
|
|
|
expect(res.status).toBe(422);
|
|
expect(res.body.error).toMatch(/was not found on the tool-server host/);
|
|
expect(steps.invokeTool).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("diagnoses a source-less call with the exactly-one rule at the validation layer", async () => {
|
|
// The other half of exactly-one: no name and no flow_path. Nothing on the
|
|
// wire is a wrapper, so file-input resolution passes through untouched and
|
|
// the schema's superRefine is the only guard left before execute — it must
|
|
// classify the miss as a 400 validation failure, not fall through to
|
|
// resolveFlowSource's in-tool copy and surface as a 500 tool error.
|
|
const res = await supertest(handle.app)
|
|
.post("/tools/flow-execute")
|
|
.send({ project_root: projectRoot, device: DEVICE });
|
|
|
|
expect(res.status).toBe(400);
|
|
expect(res.body.error).toMatch(/Pass exactly one flow source: name or flow_path\./);
|
|
expect(steps.invokeTool).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("accepts the legitimate wrapper carrying the file's real stat and runs the flow", async () => {
|
|
const st = await fs.stat(flowPath);
|
|
const res = await supertest(handle.app)
|
|
.post("/tools/flow-execute")
|
|
.send({
|
|
project_root: projectRoot,
|
|
device: DEVICE,
|
|
flow_path: {
|
|
__argentFileInput: true,
|
|
path: flowPath,
|
|
size: st.size,
|
|
mtimeMs: st.mtimeMs,
|
|
},
|
|
});
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.data).toMatchObject({
|
|
flow: "out-of-project",
|
|
steps: [
|
|
{ kind: "echo", status: "pass" },
|
|
{ kind: "tool", status: "pass", tool: "tap" },
|
|
],
|
|
});
|
|
const dispatched = (steps.invokeTool as ReturnType<typeof vi.fn>).mock.calls.map((c) => c[0]);
|
|
expect(dispatched).toContain("tap");
|
|
});
|
|
});
|
|
|
|
describe("flow-read-prerequisite flow_path over HTTP", () => {
|
|
it("answers about the boundary-verified flow_path, not the saved flow of the same stem", async () => {
|
|
// Two flows share the stem "gate": the saved copy under the project root
|
|
// and the explicit file flow-execute would run for the same params. The
|
|
// documented pre-flight (read the prerequisite, then run) is only sound if
|
|
// this tool addresses the explicit file — answering with the saved copy's
|
|
// contract would have the agent satisfy the wrong prerequisite.
|
|
const savedPath = path.join(projectRoot, ".argent", "flows", "gate.yaml");
|
|
await fs.mkdir(path.dirname(savedPath), { recursive: true });
|
|
await fs.writeFile(
|
|
savedPath,
|
|
serializeFlow({ executionPrerequisite: "SAVED-COPY: HOME screen", steps: [] }),
|
|
"utf8"
|
|
);
|
|
const sharedPath = path.join(tmpDir, "elsewhere", "gate.yaml");
|
|
await fs.mkdir(path.dirname(sharedPath), { recursive: true });
|
|
await fs.writeFile(
|
|
sharedPath,
|
|
serializeFlow({ executionPrerequisite: "SHARED-COPY: DETAIL screen", steps: [] }),
|
|
"utf8"
|
|
);
|
|
|
|
const st = await fs.stat(sharedPath);
|
|
const res = await supertest(handle.app)
|
|
.post("/tools/flow-read-prerequisite")
|
|
.send({
|
|
project_root: projectRoot,
|
|
flow_path: {
|
|
__argentFileInput: true,
|
|
path: sharedPath,
|
|
size: st.size,
|
|
mtimeMs: st.mtimeMs,
|
|
},
|
|
});
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.data).toEqual({
|
|
flow: "gate",
|
|
executionPrerequisite: "SHARED-COPY: DETAIL screen",
|
|
});
|
|
});
|
|
|
|
it("rejects a hand-crafted stat-less wrapper without reading the YAML", async () => {
|
|
// The same gate flow-execute's suite pins above: presence on the host is
|
|
// not boundary evidence, and a read must not be softer than the run — a
|
|
// prerequisite handed out here would vouch for a file the run refuses.
|
|
const res = await supertest(handle.app)
|
|
.post("/tools/flow-read-prerequisite")
|
|
.send({
|
|
project_root: projectRoot,
|
|
flow_path: { __argentFileInput: true, path: flowPath },
|
|
});
|
|
|
|
expect(res.status).toBe(500);
|
|
expect(res.body.error).toMatch(/flow_path file-input boundary/);
|
|
});
|
|
|
|
it("diagnoses name + flow_path with the exactly-one rule when the flow_path file does not resolve", async () => {
|
|
// flow-execute's unwrap case, mirrored: the caller-authored flow_path must
|
|
// reach zod as a plain string so the dual-source misuse is diagnosed by
|
|
// the schema — not by a 422 about a file the call never needed, and not by
|
|
// silently answering for the saved flow.
|
|
const res = await supertest(handle.app)
|
|
.post("/tools/flow-read-prerequisite")
|
|
.send({
|
|
name: "checkout",
|
|
project_root: projectRoot,
|
|
flow_path: { __argentFileInput: true, path: path.join(tmpDir, "nope.yaml") },
|
|
});
|
|
|
|
expect(res.status).toBe(400);
|
|
expect(res.body.error).toMatch(/Pass exactly one flow source: name or flow_path\./);
|
|
expect(res.body.error).not.toMatch(/was not found on the tool-server host/);
|
|
});
|
|
|
|
it("still reads a saved flow by name alone", async () => {
|
|
// name became optional to admit flow_path; a name-only wire (no wrapper at
|
|
// all — the shape a direct HTTP caller sends) must keep resolving to
|
|
// ${project_root}/.argent/flows/${name}.yaml exactly as before.
|
|
const savedPath = path.join(projectRoot, ".argent", "flows", "saved-only.yaml");
|
|
await fs.mkdir(path.dirname(savedPath), { recursive: true });
|
|
await fs.writeFile(
|
|
savedPath,
|
|
serializeFlow({ executionPrerequisite: "App on home screen", steps: [] }),
|
|
"utf8"
|
|
);
|
|
|
|
const res = await supertest(handle.app)
|
|
.post("/tools/flow-read-prerequisite")
|
|
.send({ name: "saved-only", project_root: projectRoot });
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.data).toEqual({
|
|
flow: "saved-only",
|
|
executionPrerequisite: "App on home screen",
|
|
});
|
|
});
|
|
});
|