Skip to content
2 changes: 1 addition & 1 deletion apps/brunch-agent/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ HASH root guidance applies. Agents, their layout and how to add a candidate are

This application composes the Flue runtime, HTTP routes, and Brunch agents. It must remain independent of Petrinaut UI (`@hashintel/petrinaut`); it may import published catalogs from `@hashintel/petrinaut-core`. `apps/petrinaut-website` meets the editor through the AI SDK/HTTP transport.

When diagnosing a slow, failed or stalled chat, start with `yarn workspace @apps/brunch-agent diagnose`, not raw logs or hand-written LogQL. For each model request it reports the provider and model, the time until the response started, retries, failures and idle timeouts, along with the request's span. The [`README.md`](README.md) gives its sources and flags.
When diagnosing a slow, failed or stalled chat, start with `yarn workspace @apps/brunch-agent diagnose`, not raw logs or hand-written LogQL. For each model request it reports the provider and model, when the provider's HTTP response arrived, retries, failures and idle timeouts, along with the request's span. For each step it shows where the time went (reasoning blocks, reply text, tool arguments), its tokens and estimated cost, and how long its tools took to run. The [`README.md`](README.md) gives its sources and flags.

Before changing Flue or Pi versions or patches, read [`docs/dependency-patches.md`](docs/dependency-patches.md) for the retained contracts, removed interventions and removal proofs. Upgrade the pair together and verify the built application; package-definition tests alone do not prove native validation, projection or crash recovery.

Expand Down
8 changes: 6 additions & 2 deletions apps/brunch-agent/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ Print a human-readable transcript of one conversation from that same Flue histor
yarn workspace @apps/brunch-agent transcript -- --actor-key <key> --id <conversationId>
```

Read the provider telemetry back with `diagnose`. For each model request it shows the provider and model, the time until the response started, retries, failures and idle timeouts, and the request's span with the HTTP requests under it. It shows metadata only, never prompts or output. It reads Loki and Tempo through Grafana, by default the local stack's at `http://localhost:3001`. Locally, the server exports only when started with `HASH_OTLP_ENDPOINT=http://localhost:4317 yarn dev:brunch`. Another Grafana takes `--grafana <url>` with a token in `GRAFANA_TOKEN`; the token is only sent over HTTPS or to `localhost`. To read a saved server log or piped output instead, pass `--log <file>` or `--log -`; that has no spans. Unreadable lines, and reads cut off at Loki's or Tempo's limit, are reported on stderr so a short count is not taken for a complete one.
Read the provider telemetry back with `diagnose`. For each model request it shows the provider and model, when the provider's HTTP response arrived (Pi's first event comes with the response headers, before any output), retries, failures and idle timeouts, and the request's span with the HTTP requests under it. For each step it shows where the time went: the time spent in reasoning blocks and how many there were, when the reply text and the tool arguments started and stopped streaming, which tools the step called, the tokens in with cache reads and cache writes apart, the tokens out with the reasoning tokens among them, and Pi's catalogue estimate of the step's cost. Under each step it shows how long its tools took to run, from their spans; calls of a step whose spans overlap ran as one batch, so a batch shows once with its call count, timed from its earliest start to its latest end. Lines logged before a field existed show it as `–`. It shows metadata only, never prompts or output. It reads Loki and Tempo through Grafana, by default the local stack's at `http://localhost:3001`. Locally, the server exports only when started with `HASH_OTLP_ENDPOINT=http://localhost:4317 yarn dev:brunch`. Another Grafana takes `--grafana <url>` with a token in `GRAFANA_TOKEN`; the token is only sent over HTTPS or to `localhost`. To read a saved server log or piped output instead, pass `--log <file>` or `--log -`; that has no spans. Spans are searched from the submission's first step to its settlement, so `--since` can reach back further than Tempo's 168-hour search limit; without a chronology line that places them, the search covers the whole window, and over 168 hours `diagnose` says so and exits with an error, asking for `--since 7d` or less. When Tempo no longer holds a submission's spans, the chronology is still shown and the output says the spans are out of reach; when only some steps lack their `chat` span, it names them. Unreadable lines and reads cut off at Loki's or Tempo's limit are reported on stderr so a short count is not taken for a complete one.

```sh
yarn workspace @apps/brunch-agent diagnose # settled submissions in the last hour
Expand Down Expand Up @@ -168,7 +168,11 @@ The application exports Flue traces, logs, and metrics through HASH's shared Ope
tool payloads, and credentials are not recorded, and the app's own failure spans carry an error code
rather than a message. On SIGTERM Flue drains active work for up to 30 seconds, then closes the
Postgres runner, whose close hook shuts the OpenTelemetry providers down; a 60-second outer timer
force-exits. Give the ECS task a stop timeout above 60 seconds.
force-exits. Give the ECS task a stop timeout above 60 seconds. The local SQLite store's close
sends the spans and metrics already recorded without shutting the providers down, because a source
change under `vite dev` closes the store while the server and its exporters run on. Log records are
not sent on that close: those from the last second before a stop can still be lost, and only a flush
exposed by the shared setup would cover them.

Brunch does not mount the retired `/api/chat` path; requests to it return 404.
`/agents/petrinaut/:instanceId` is the product door required by Petrinaut; `/agents/chat/:instanceId`
Expand Down
2 changes: 2 additions & 0 deletions apps/brunch-agent/evals/persona/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,8 @@ The persona stops by its own rule: when the person has what they came for, when

**Persona runs have no automatic accounting cutoff.** The launcher disables the campaign accounting wrapper for Brunch even if `BRUNCH_STEP_A_ACCOUNTING` was inherited. `--max-messages <n>` stops the run once Brunch has replied to the persona's nth message; the case's opening is not counted, and the run packet is written as on any other stop. With `--hold`, the persona stopping, whether at that limit, by `persona end` or by its agent exiting, closes nothing: the bridge refuses any further persona messages and you carry on in the same Chrome window and conversation. Ctrl-C in the launcher (once a foreground agent has exited) or closing Chrome then stops the run as usual. A live-provider run requires explicit model and spend authorization; the existence of this command grants none.

Stopping a run sends SIGTERM to the `yarn` process that leads each service it started, and each yarn layer passes it on, so the dev server receives it once and closes: Flue stops, and the store's close sends the spans and metrics already recorded. A service still running 10 seconds after the signal is killed with its whole process group. For that case the launcher also starts the services with `OTEL_BSP_SCHEDULE_DELAY=200`, so a settled turn's spans leave for the collector within 200 ms. Log records are not sent on the close, so those from the last second before the stop can still be lost.

## Guidance provenance

`run.json` records a fingerprint of the agent's guidance and Ledger sources (`guidance-manifest.ts`), the case hash and the model settings. Guidance drift is checked before each subsequent persona turn, and a resume refuses changed guidance. These are source fingerprints, not a complete environment snapshot.
Expand Down
64 changes: 63 additions & 1 deletion apps/brunch-agent/evals/persona/launch.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { execFile } from "node:child_process";
import { execFile, spawn } from "node:child_process";
import { once } from "node:events";
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, relative } from "node:path";
Expand All @@ -21,6 +22,7 @@ import {
recordingReadySummary,
responds,
settlePersonaLauncherStop,
stopServiceGroups,
} from "./launch.ts";
import { appendAdmittedUtterance } from "./launch/bridge-log.ts";
import { resolvePersonaDriver } from "./launch/driver.ts";
Expand Down Expand Up @@ -84,6 +86,60 @@ test("launcher Stop bounds an unobserved settlement", async () => {
});
});

// A server that closes on its first SIGTERM, as Vite does, behind a parent that
// forwards every SIGTERM it receives to it, as each yarn layer does.
const closingServer = `
process.once("SIGTERM", () => {
// The close takes a moment, as Vite's does while Flue stops.
setTimeout(() => {
process.stdout.write("closed\\n");
process.exit(143);
}, 200);
});
process.stdout.write("ready\\n");
setInterval(() => {}, 1000);
`;
const forwardingParent = `
const { spawn } = require("node:child_process");
const server = spawn(process.execPath, ["-e", ${JSON.stringify(closingServer)}], {
stdio: ["ignore", "inherit", "inherit"],
});
process.on("SIGTERM", () => server.kill());
server.on("exit", (code) => process.exit(code ?? 129));
`;

test("stopping a service lets its server finish closing", async () => {
const leader = spawn(process.execPath, ["-e", forwardingParent], {
detached: true,
stdio: ["ignore", "pipe", "inherit"],
});
let output = "";
leader.stdout.setEncoding("utf8");
const ready = new Promise<void>((resolve) => {
leader.stdout.on("data", (chunk: string) => {
output += chunk;
if (output.includes("ready")) resolve();
});
});
const exited = once(leader, "exit");
const { pid } = leader;
if (pid === undefined) throw new Error("The test service did not start");
try {
await ready;

await stopServiceGroups([pid]);

expect(await exited).toEqual([143, null]);
expect(output).toContain("closed");
} finally {
try {
process.kill(-pid, "SIGKILL");
} catch {
// The group has already exited.
}
}
});

const loadingRuntimeUnavailable = {
error: { type: "runtime_unavailable", meta: { state: "loading" } },
};
Expand All @@ -105,6 +161,12 @@ test("both launcher children override inherited campaign accounting", () => {
).toBeUndefined();
});

test("services export finished spans well inside the launcher's stop gap", () => {
vi.stubEnv("DEBUG", "");
vi.stubEnv("OTEL_BSP_SCHEDULE_DELAY", "5000");
expect(personaEnvironment().OTEL_BSP_SCHEDULE_DELAY).toBe("200");
});

test.each([false, true])(
"resume reads original stores without consulting accounting (legacy: %s)",
async (legacy) => {
Expand Down
82 changes: 50 additions & 32 deletions apps/brunch-agent/evals/persona/launch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,9 +150,54 @@ export const personaEnvironment = (
// An explicit empty value also overrides Vite env files on backend startup.
// Historical campaign ledgers must not gate persona requests or resumed runs.
loaded[brunchEnv.stepAAccounting] = "";
// The dev server sends waiting spans when its store closes on stop. A server
// that does not close in time is killed, and then only spans already sent
// arrive: the SDK's default 5 s span delay is longer than the seconds
// between a run's last turn settling and the stop; 200 ms sends them inside
// that gap.
loaded.OTEL_BSP_SCHEDULE_DELAY = "200";
return loaded;
};

/** Whether the signal reached the process or group; false once it has gone. */
const signalProcess = (pid: number, signal: NodeJS.Signals | 0) => {
try {
process.kill(pid, signal);
return true;
} catch (error) {
if (
!(error instanceof Error) ||
!("code" in error) ||
error.code !== "ESRCH"
) {
throw error;
}
return false;
}
};

/**
* Stops each service started as its own process group, led by `yarn`, and
* settles once every group has exited.
*
* Only the leader is signalled: each yarn layer forwards SIGTERM to its child,
* so the dev server receives it once. Vite handles only the first SIGTERM;
* a second, which signalling the whole group adds, kills it before its close,
* Flue's stop with it, has finished. A group still alive after the wait is
* killed so the launcher can finish.
*/
export const stopServiceGroups = async (leaders: readonly number[]) => {
const groups = leaders.filter((pid) => signalProcess(pid, "SIGTERM"));
const deadline = Date.now() + 10_000;
while (groups.some((pid) => signalProcess(-pid, 0))) {
if (Date.now() > deadline) {
for (const pid of groups) signalProcess(-pid, "SIGKILL");
return;
}
await delay(100);
}
};

export const recordingReadySummary = ({
title,
url,
Expand Down Expand Up @@ -389,45 +434,18 @@ const launchPersona = async ({
if (!resume) await save(join(run, "run.json"), record);
report(`Run: ${run}`);
const started: ChildProcess[] = [];
/** Whether the signal reached the process group; false once it has gone. */
const signalGroup = (pid: number, signal: NodeJS.Signals | 0) => {
try {
process.kill(-pid, signal);
return true;
} catch (error) {
if (
!(error instanceof Error) ||
!("code" in error) ||
error.code !== "ESRCH"
) {
throw error;
}
return false;
}
};
let servicesStopped: Promise<void> | undefined;
/** Ends the owned process groups and settles once every one has exited. */
const stopStartedServices = () => {
servicesStopped ??= (async () => {
const groups = started.flatMap((child) =>
servicesStopped ??= stopServiceGroups(
started.flatMap((child) =>
child.pid !== undefined &&
child.exitCode === null &&
child.signalCode === null &&
signalGroup(child.pid, "SIGTERM")
child.signalCode === null
? [child.pid]
: [],
);
// Services flush their logs and the conversation store on SIGTERM;
// one that has not exited by then is killed so the launcher can finish.
const deadline = Date.now() + 10_000;
while (groups.some((pid) => signalGroup(pid, 0))) {
if (Date.now() > deadline) {
for (const pid of groups) signalGroup(pid, "SIGKILL");
return;
}
await delay(100);
}
})();
),
);
return servicesStopped;
};
let browser:
Expand Down
3 changes: 2 additions & 1 deletion apps/brunch-agent/evals/petrinaut/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ The arguments are the case, the `provider/id` model and the thinking level; they
Every persona run and probe ends by writing `evidence/packet.json` and `evidence/packet.md` into its directory. The packet accounts for each exchange's time, which is what a change to turn time is judged by:

- active time (wall time less approval waits) and time until the first reply text;
- model steps, each split into time before first output (hidden reasoning), tool-argument streaming and reply text, and tool phases;
- model steps, each split into time before first output, tool-argument streaming and reply text, and tool phases;
- the time before first output split in two: time inside reasoning blocks before the output, and the rest of the wait (time to the provider's first event, and generating tool arguments the provider then delivers in one burst). A call whose first and last argument delta come under 50 ms apart is marked as a burst, and each step, exchange and the summary total the burst calls' argument characters; like argument streaming, bursts are unknown without a chronology;
- each step's shape (its tool categories, in order);
- the tool mix, skill activations, Ledger commit sizes, net growth, tokens and cost;
- each model request's provider and model, and which requests failed and which were retries, including failed requests that left no step;
Expand Down
Loading
Loading