mirror of
https://github.com/garrytan/gbrain.git
synced 2026-07-27 22:15:33 +00:00
* fix(reindex-frontmatter): connect engine before query (#1225) `createEngine()` from src/core/engine-factory.ts only constructs the engine; callers MUST call connect() before any executeRaw. The reindex-frontmatter CLI was constructing the engine and going straight to countAffected, which crashed on PGLite with "PGLite not connected. Call connect() first." even on --dry-run. Fix follows the existing-command pattern (src/commands/auth.ts, src/commands/backfill.ts, src/commands/integrity.ts all do the same): pass toEngineConfig(cfg) into both createEngine() AND engine.connect(), then engine.initSchema() (idempotent on a current schema, ~1ms cost). Pre-fix verification: codex outside-voice CF5 flagged the related "can't import connectEngine from cli.ts" misdirection in the original fix plan. This implementation uses the canonical sibling pattern instead. Regression test pinned at test/reindex-frontmatter-connect.test.ts. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * chore: bump VERSION to 0.37.7.0 + stub CHANGELOG v0.37.5.0 claimed by #1229 (warsaw-v4); v0.37.6.0 by #1246 (OpenRouter recipe). v0.37.7.0 is the next free slot for this fix wave. CHANGELOG entry stubbed in user-facing voice per CLAUDE.md "CHANGELOG voice + release-summary format" — ELI10 lead-first, real fix details below. The "## To take advantage of v0.37.7.0" block follows the v0.13+ self-repair pattern from CLAUDE.md. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(subagent): short-circuit terminal-on-resume (#1151) Bug: when the worker resumed a subagent job whose persisted last message was an assistant turn with text-only content (no tool_use blocks), the replay reconciler at subagent.ts:241-247 had no branch for that case. The main loop then called messages.create against a conversation ending in assistant role, which Sonnet 4.6+ rejects with HTTP 400 "This model does not support assistant message prefill." 3 retries later → dead-letter, despite all the job's work having committed in earlier turns. @zscgeek's bug report pinned this exactly: dream-cycle Otter corpus runs hit ~7% dead-letter rate, every dead job's last subagent_messages row was a text-only synthesis summary listing slugs that already existed in `pages`. Their proposed fix mirrors this implementation. Fix: add an else branch to the assistant-tail check that mirrors the live-loop terminal logic at subagent.ts:440-447 — reconstruct finalText from the persisted text blocks, return stop_reason='end_turn' immediately. No LLM call, no schema change. Two new regression cases: - text-only terminal on resume returns immediately with zero messages.create calls - tool-use replay path unchanged (existing behavior preserved) Codex outside-voice (CF13) initially flagged this fix as mis-targeted, claiming subagent.ts already handled the case. /investigate run revealed the live-loop terminal at :440-447 was covered but the REPLAY-path terminal at :241-247 was missing — both branches need symmetric handling. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(autopilot): scope lockfile to GBRAIN_HOME (#1226) The autopilot lockfile was hardcoded at `~/.gbrain/autopilot.lock` (via `process.env.HOME`), bypassing GBRAIN_HOME. Two brains pointed at different GBRAIN_HOME directories still wrote to the same global lockfile; one would silently take over the other on each restart. Fix: route through `gbrainPath('autopilot.lock')` from src/core/config.ts (imported aliased as gbrainHomePath since the local `gbrainPath` var in installAutopilot references the CLI binary path). The mkdirSync(`~/.gbrain`) call also routes through the helper so the directory is created in the right place too. Co-authored with @rafaelreis-r — same fix shape as PR #1227, re-implemented against current master per the wave's "re-implement, credit, close" workflow. Tests cover: one GBRAIN_HOME → one canonical lock; two GBRAIN_HOME values → two distinct locks; default fall-through still works. Co-Authored-By: rafaelreis-r <noreply@github.com> Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(graph-query): foreign-edge footer + --include-foreign (#1153) The graph-query CLI silently dropped edges to pages in other sources on federated brains. Users had no signal those edges existed unless they read the source code. Fix: - New --include-foreign flag (off by default, preserves the existing scoping contract; on = explicit cross-source traversal). - After every traversal, count edges from rootSlug whose target page lives in a different source. When count > 0 AND user didn't opt in, emit a stderr footer: `(N edge(s) to foreign-source pages hidden; pass --include-foreign to include them)` - The "no edges found" path also runs the count + footer so users discover foreign edges even when scoped traversal returned nothing. - Thin-client path skips the count (engine query not available); future T1 work threads source resolution through MCP for that path. - Single quotation correctness in count SQL: page_links table is `links` (not `page_links`); JOIN both endpoints to pages and compare source_id, NULL-safe via `IS NOT NULL` guards on both sides. - Fail-open on missing source_id column for pre-v0.18 brains: return 0 (no foreign edges to report) instead of throwing. 4 new test cases: footer fires on scoped query with foreign edge, --include-foreign suppresses footer, zero-foreign no-footer case, pluralization regression guard. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(sources): `gbrain sources current` + tier attribution (#1222) Federated-brain users running destructive ops (extract, import, purge) need a way to verify which source they're targeting BEFORE the op runs. Pre-fix, the only way was to grep config files or run the op with --dry-run and inspect output. New command: gbrain sources current # human output gbrain sources current --json # machine-readable gbrain sources current --source X # show what an explicit --source # X would resolve to (validates # X exists in the sources table) Output names BOTH the resolved source id AND which tier of the 6-tier resolution chain won (flag / env / dotfile / local_path / brain_default / seed_default), plus a `detail` line naming the winning signal (e.g. "GBRAIN_SOURCE=dept-x" or ".gbrain-source" or "/work/gstack/src"). Implementation: - New `resolveSourceWithTier()` in source-resolver.ts as an additive variant of `resolveSourceId()`. Walks the same 6 steps in the same order; just returns `{ source_id, tier, detail? }` instead of bare string. Existing `resolveSourceId()` unchanged — all callers continue working. - New `SOURCE_TIER_NAMES` const + `SourceTier` type export so the CLI, doctor (Tier 5 follow-up), and future MCP consumers share one vocabulary instead of inlining strings. - Help text updated; `current` subcommand registered in dispatcher. 11 new tests pin the 6-tier ladder + priority semantics. Existing 19 source-resolver tests still pass (regression preserved). Per codex CF3 (the existing src/core/source-resolver.ts was missed in the original plan). Re-uses the existing helper instead of inventing a duplicate. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(extract): --source-id scopes extraction to one brain source (#1204) Federated brain users running `gbrain extract` had no way to scope extraction to one source. The DB path walks all sources together via listAllPageRefs(), which is correct for cross-source resolution but sometimes the user wants to extract per-source explicitly (e.g. re-running extract on a specific source after a manual import). The pre-existing `--source` flag is the data-source axis (fs|db) and can't be repurposed. New flag `--source-id <id>` joins it on the brain-source-id axis: gbrain extract all --source db --source-id alpha -> walks only alpha-source pages; extracts links + timeline from those, into the alpha source Important: the resolver maps (allSlugs + slugToSources) stay built from the FULL listAllPageRefs result, not the scoped subset. This ensures qualified cross-source wikilinks like `[[other-src:slug]]` still resolve correctly even when the extract walk is scoped — the filter is on which pages we extract FROM, not what we can resolve TO. Threaded through both `extractLinksFromDB` and `extractTimelineFromDB` with backward-compat: callers passing no opts get the old behavior. 4 new test cases pin: walks-all-without-flag baseline, alpha-only-when-scoped-to-alpha, beta-only-when-scoped-to-beta, empty-set-on-unknown-source. Note: #1204's wider "silent 0 links" report on federated brains has additional facets beyond this flag (resolver path edge cases on overlapping slugs). The scoped-walk fix gives users an explicit workaround AND closes the per-source extraction gap. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * chore(todos): file v0.37.7.0 follow-ups (#1173, #1204, T5N) Three items deferred from v0.37.7.0: 1. #1173 .sql indexing — verify-first gate found tree-sitter-sql.wasm missing from src/assets/wasm/grammars/. Dedicated wave needed: vendor the wasm, add .sql to walker filter, address slug-shape collision with #1172. 2. #1204 deeper investigation — wave added --source-id flag as workaround. Underlying silent-zero-links bug on unscoped federated extracts needs its own /investigate pass against a cross-source-duplicate-slug fixture. 3. Tier 5N doctor sweep for dead-lettered subagent jobs matching the #1151 fingerprint. Deferred to v0.37.8+ behind the islamabad doctor.ts conflict resolution. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(sync): walker skips git submodule directories (#1169) Sync walker descended into git submodules and indexed their markdown content as if it belonged to the parent brain. Users with submodules in their brain repo saw foreign content in their pages table. Fix: pruneDir gains an optional `parentDir` arg. When set, the helper stats `<parentDir>/<name>/.git` and skips the directory if `.git` exists as a FILE (gitfile pointer — the canonical submodule shape). Directories containing `.git` as a DIRECTORY (a real nested repo, not a submodule) are descended into; the inner `.git` dir itself is then dot-prefix-excluded. Callers updated to pass parentDir: - src/commands/extract.ts walkMarkdownFiles - src/core/cycle/transcript-discovery.ts walker Back-compat preserved: existing pruneDir(name) callers without parentDir get the pre-v0.37.7.0 behavior unchanged. Companion `.gitignore`-respect feature from PR #1159 (@jetsetterfl) NOT in this wave — it would require adding the `ignore` npm package as a dep, which the plan's "no new deps in this PR" gate excludes. Filed as follow-up TODO for a dedicated wave. 5 new test cases pin the submodule shape + back-compat + nested-repo ambiguity. Existing extract-fs / extract-db tests unchanged. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * docs(brain-routing): document 6-tier source resolution chain (#1222) The convention skill didn't have a tier-by-tier reference for how gbrain resolves the active source. Users running federated brains had to read the source code to know which signal wins. Added: - Canonical 6-tier table (flag → env → dotfile → local_path → brain_default → seed_default) matching src/core/source-resolver.ts. - Pointer to `gbrain sources current` (new in v0.37.7.0) as the verification command. - The CLI-layer trust boundary note: operations.ts handlers don't read env/dotfile (preserves v0.34.1.0 source-isolation work for MCP callers). - Per-command flag map: --source, --source-id (extract), and --include-foreign (graph-query). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(import): --source-id flag routes pages to a brain source (#1167) `gbrain import --source dept-x ./pages` silently fell back to the default source because the CLI parser never consumed --source. PR #707's design intent excluded the flag explicitly; users had no signal their pages were going to the wrong place. #1167 + #1222 filed the regression. Fix: parse `--source-id <id>` (matching v0.37.7.0 extract.ts T2's naming convention — --source-id stays out of conflict with future axes that may want --source). When set, the flag value wins over any programmatic opts.sourceId; back-compat preserved for callers that pass sourceId via opts only. Also threaded into the positional-dir arg parser's flagValues set so `--source-id <value> <dir>` doesn't treat <value> as the dir. Note on related surfaces: - `gbrain query "X" --source_id dept-x` already routed correctly via the operations.ts query op (added in v0.34) — no fix needed. - `gbrain extract --source-id <id>` shipped in T2. - `gbrain sync --source <id>` already worked (pre-existing). - `gbrain sources current` (shipped in T4) is the verification tool — run it before destructive ops to confirm routing. Closes the silent-fallback for the import path. Co-authored with @tyad67-netizen (#1168), @hnshah (#1124, #1120), whose patches informed the shape; re-implemented against current master per the wave's "re-implement, credit, close" workflow. 3 new test cases pin: default-without-flag, --source-id-routes-correctly, flag-value-not-treated-as-dirArg. Co-Authored-By: tyad67-netizen <noreply@github.com> Co-Authored-By: hnshah <noreply@github.com> Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(autopilot): reconnect classifier + launchd ThrottleInterval (#1162) Pre-fix: when database_url was unset/malformed, the DB-health-check reconnect loop logged `config.database_url undefined` forever because the catch swallowed every error type uniformly. launchd's KeepAlive=true respawned immediately on any exit, so even when the process did exit, it came right back into the same bad state. @colin477 reported the daemon-thrash pattern. Two-part fix: 1. In-process error classifier — `classifyReconnectError(err)`: - `unrecoverable` (database_url missing/empty/malformed, auth failure, no-brain-configured): exit immediately with a clear stderr line. Pattern-matched against postgres / config-loader error shapes. Tests pin the matcher against the #1162 fingerprint exactly. - `recoverable` (network blip, pool saturated, connection refused on a port coming up, Supabase 503): retry. Up to GBRAIN_AUTOPILOT_MAX_RECONNECT_FAILS (default 30 = ~5min) before finally giving up with `max_reconnect_fails_exceeded`. - Counter resets on every successful health probe or reconnect. 2. launchd plist gains `ThrottleInterval=60`. Combined with the in-process exit, launchd waits 60s before relaunching instead of immediate respawn. Pure-function `generateLaunchdPlist()` exported for tests. 16 new test cases: - 11 classifier cases (database_url shapes, malformed URL, auth, role-does-not-exist with quoted name, network blip, pool saturated, 503, non-Error inputs, case-insensitivity) - 5 plist generator cases (ThrottleInterval=60, KeepAlive preserved, wrapper path, XML escaping, StandardErrorPath). Pre-existing autopilot-lock-path tests unchanged — both fixes land cleanly side-by-side. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(oauth): confidential clients via custom /token middleware (#1166) v0.34.1.0 (#909) fixed PUBLIC PKCE clients (client_secret=undefined) by normalizing NULL → undefined in getClient. Confidential clients regressed: the MCP SDK's clientAuth middleware does plaintext `client.client_secret !== presented_secret` compare, but gbrain stores SHA-256 hashes, so the SDK's compare always failed for authorization_code and refresh_token grants on confidential clients. Result: /token returned `invalid_client` for every confidential exchange. Fix shape per locked-decision-5: custom /token middleware BEFORE the SDK's authRouter, similar to the pre-existing client_credentials handler. The middleware: 1. Detects confidential auth via `client_secret` in body (client_secret_post) OR `Authorization: Basic` header (client_secret_basic per RFC 6749 §2.3.1). 2. Falls through to the SDK when neither is present (public PKCE path stays canonical, preserves v0.34.1.0 behavior). 3. Calls new `verifyConfidentialClientSecret(clientId, presented)` on the provider which does SHA-256 hash compare ourselves (same shape as exchangeClientCredentials' existing hash check). 4. On verification success, calls existing `exchangeAuthorizationCode` / `exchangeRefreshToken` directly with the validated client. 5. RFC 6749 §5.2 error semantics: 401 invalid_client for auth failures, 400 invalid_grant for code/token problems. Per CLAUDE.md "GBRAIN:RLS_EXEMPT" annotation contract: this surface sits in front of the SDK's clientAuth and doesn't depend on the SDK's plaintext compare working — the SDK's middleware never fires for confidential paths the new middleware claims. 7 new test cases pin: correct-secret-returns-client, wrong-secret opaque rejection, non-existent client, public-client refuses the confidential path, case-sensitivity, soft-deleted revocation, verify-then-exchange-refresh round-trip with second-use rejection. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(doctor): 3 new checks — source routing + oauth + autopilot lock (T12/T13/T14) Three v0.37.7.0 doctor checks landing in one atomic commit (single file, shared merge-conflict surface with garrytan/islamabad-v3 per locked decision 1): 1. source_routing_health (T12 / #1167): Sample non-default sources for pages; warn when a registered source has zero pages (silent-collapse-to-default fingerprint). D5 lock: total-sample cap of 200 pages across all sources, with per-source cap = min(50, ceil(200/N)) so a 20-source CEO brain pays 200 selects, not 1000. Fix hint paste-ready to `gbrain sources current --json` for verification. 2. oauth_confidential_client_health (T13 / #1166): Probe every oauth_clients row. Confidential clients (auth_method != 'none') must have a non-NULL client_secret_hash; if any row claims confidential auth but stores NULL hash, that's the pre-v0.37.7.0 regression. Public clients (auth_method='none') correctly keep NULL hash per v0.34.1.0 #909. Fix hint: `gbrain auth revoke-client + register-client` OR `gbrain upgrade`. Pre-OAuth schemas (missing oauth_clients table) skip gracefully. 3. autopilot_lock_scope (T14 / #1226): Detect stale ~/.gbrain/autopilot.lock outside the current GBRAIN_HOME. Codex CF11: dangerous to paste-ready `rm` without verifying the owning PID isn't a live process. Hint reads the PID file and gives the user a `ps -p <pid>` check before any delete — matches sshd-style stale-lock recovery hints. 9 new test cases pin the canonical paths. Pre-existing 80+ doctor checks unchanged. Expected to conflict with garrytan/islamabad-v3 at merge time. The 3 new check functions live in their own block far from the islamabad skill_brain_first check; the conflict surface should be limited to the `checks.push(...)` call site near the end of runDoctor's DB-checks phase (~10 lines). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(test): withEnv wrapper in source-resolver-with-tier (test-isolation lint) The new source-resolver-with-tier.test.ts from T4 mutated process.env.GBRAIN_SOURCE directly in two cases, which violates scripts/check-test-isolation.sh R1 (env mutations leak across parallel-loaded test files in the same shard process). Fix: wrap both mutation sites in withEnv() from test/helpers/with-env.ts, which saves+restores via try/finally per the canonical pattern in CLAUDE.md. Pure refactor — all 11 cases still green. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * docs: update project documentation for v0.37.7.0 CHANGELOG.md — populated the "What landed" stub with the 18-commit brisbane wave (source-id flag threading, sources current subcommand, graph-query foreign-edge footer, autopilot lockfile scope + reconnect classifier + launchd ThrottleInterval, OAuth confidential client middleware, reindex-frontmatter connect fix, subagent terminal-on-resume fix, sync walker submodule skip, 3 new doctor checks, brain-routing.md convention skill). Voice: ELI10 lead, capability table, paste-ready verification, "what's safe to know" + "what we caught" sections. CLAUDE.md — extended Key Files annotations for the v0.37.7.0 changes: import/extract --source-id flags, sources current subcommand, graph-query --include-foreign, resolveSourceWithTier() additive helper, autopilot classifyReconnectError + generateLaunchdPlist exports, OAuth confidential client middleware, pruneDir submodule detection, subagent terminal short-circuit, 3 new doctor checks. Pinned by their test files. llms-full.txt — regenerated via `bun run build:llms` (CI guard at test/build-llms.test.ts will fail otherwise). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> Co-authored-by: rafaelreis-r <noreply@github.com>
556 lines
22 KiB
TypeScript
556 lines
22 KiB
TypeScript
/**
|
|
* Subagent handler tests with a mocked Anthropic Messages client.
|
|
*
|
|
* Strategy: every test scripts a sequence of Messages API responses, hands
|
|
* them to a FakeMessagesClient, and inspects (a) the SubagentResult the
|
|
* handler returns and (b) the persisted rows in subagent_messages +
|
|
* subagent_tool_executions. Replay tests simulate a crash by constructing
|
|
* a fresh handler bound to the same job row with partial state already
|
|
* written.
|
|
*
|
|
* PGLite in-memory so the schema, ON CONFLICT, and two-phase persistence
|
|
* all exercise real SQL.
|
|
*/
|
|
|
|
import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
|
|
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
|
|
import { MinionQueue } from '../src/core/minions/queue.ts';
|
|
import {
|
|
makeSubagentHandler,
|
|
RateLeaseUnavailableError,
|
|
type MessagesClient,
|
|
} from '../src/core/minions/handlers/subagent.ts';
|
|
import type { ToolDef, MinionJobContext } from '../src/core/minions/types.ts';
|
|
import type Anthropic from '@anthropic-ai/sdk';
|
|
|
|
let engine: PGLiteEngine;
|
|
let queue: MinionQueue;
|
|
|
|
beforeAll(async () => {
|
|
engine = new PGLiteEngine();
|
|
await engine.connect({ database_url: '' });
|
|
await engine.initSchema();
|
|
queue = new MinionQueue(engine);
|
|
}, 60_000);
|
|
|
|
afterAll(async () => {
|
|
await engine.disconnect();
|
|
});
|
|
|
|
beforeEach(async () => {
|
|
await engine.executeRaw('DELETE FROM subagent_tool_executions');
|
|
await engine.executeRaw('DELETE FROM subagent_messages');
|
|
await engine.executeRaw('DELETE FROM subagent_rate_leases');
|
|
await engine.executeRaw('DELETE FROM minion_jobs');
|
|
});
|
|
|
|
// ── FakeMessagesClient ──────────────────────────────────────
|
|
|
|
type FakeResponse = Partial<Anthropic.Message> & { content: Anthropic.Message['content'] };
|
|
|
|
class FakeMessagesClient implements MessagesClient {
|
|
public calls: Anthropic.MessageCreateParamsNonStreaming[] = [];
|
|
constructor(private responses: FakeResponse[]) {}
|
|
async create(
|
|
params: Anthropic.MessageCreateParamsNonStreaming,
|
|
): Promise<Anthropic.Message> {
|
|
this.calls.push(params);
|
|
if (this.responses.length === 0) throw new Error('FakeMessagesClient: out of scripted responses');
|
|
const r = this.responses.shift()!;
|
|
return {
|
|
id: `msg_${this.calls.length}`,
|
|
type: 'message',
|
|
role: 'assistant',
|
|
model: params.model,
|
|
stop_reason: 'end_turn',
|
|
stop_sequence: null,
|
|
usage: { input_tokens: 10, output_tokens: 5, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 } as any,
|
|
...r,
|
|
} as Anthropic.Message;
|
|
}
|
|
}
|
|
|
|
// Build a synthetic MinionJobContext around a real minion_jobs row. The
|
|
// handler only reads data/id/signal/shutdownSignal/updateTokens — we stub
|
|
// the rest. `subagent` is a protected job name (Lane 4H) so tests submit
|
|
// under the trusted-submit flag.
|
|
async function makeCtx(input: unknown): Promise<MinionJobContext> {
|
|
const job = await queue.add(
|
|
'subagent',
|
|
input as Record<string, unknown>,
|
|
{},
|
|
{ allowProtectedSubmit: true },
|
|
);
|
|
const ac = new AbortController();
|
|
const shutdown = new AbortController();
|
|
return {
|
|
id: job.id,
|
|
name: job.name,
|
|
data: (input as Record<string, unknown>) ?? {},
|
|
attempts_made: 0,
|
|
signal: ac.signal,
|
|
shutdownSignal: shutdown.signal,
|
|
async updateProgress() {},
|
|
async updateTokens() {},
|
|
async log() {},
|
|
async isActive() { return true; },
|
|
async readInbox() { return []; },
|
|
};
|
|
}
|
|
|
|
// ── Tiny tool registry for tests ────────────────────────────
|
|
|
|
function makeEchoTool(name = 'echo', idempotent = true): ToolDef {
|
|
return {
|
|
name,
|
|
description: 'echo input',
|
|
input_schema: { type: 'object', properties: { value: { type: 'string' } }, required: [] },
|
|
idempotent,
|
|
async execute(input) { return { echoed: input }; },
|
|
};
|
|
}
|
|
|
|
function makeThrowingTool(name = 'broken'): ToolDef {
|
|
return {
|
|
name,
|
|
description: 'always throws',
|
|
input_schema: { type: 'object', properties: {}, required: [] },
|
|
idempotent: true,
|
|
async execute() { throw new Error('tool broken'); },
|
|
};
|
|
}
|
|
|
|
// ── Tests ───────────────────────────────────────────────────
|
|
|
|
describe('subagent handler happy path', () => {
|
|
test('no-tool end_turn: returns text response + persists user + assistant rows', async () => {
|
|
const client = new FakeMessagesClient([
|
|
{ content: [{ type: 'text', text: 'hello world' }] as any, stop_reason: 'end_turn' },
|
|
]);
|
|
const handler = makeSubagentHandler({ engine, client, toolRegistry: [] });
|
|
const ctx = await makeCtx({ prompt: 'hi' });
|
|
|
|
const result = await handler(ctx);
|
|
|
|
expect(result.result).toBe('hello world');
|
|
expect(result.turns_count).toBe(1);
|
|
expect(result.stop_reason).toBe('end_turn');
|
|
expect(result.tokens.in).toBe(10);
|
|
expect(result.tokens.out).toBe(5);
|
|
|
|
const msgs = await engine.executeRaw<{ count: string }>(
|
|
`SELECT count(*)::text AS count FROM subagent_messages WHERE job_id = $1`,
|
|
[ctx.id],
|
|
);
|
|
expect(parseInt(msgs[0]!.count, 10)).toBe(2); // user seed + assistant
|
|
});
|
|
|
|
test('single tool_use turn: tool executes, two-phase row goes complete', async () => {
|
|
const tool = makeEchoTool();
|
|
const client = new FakeMessagesClient([
|
|
{
|
|
content: [
|
|
{ type: 'tool_use', id: 'tu_1', name: 'echo', input: { value: 'v1' } } as any,
|
|
],
|
|
stop_reason: 'tool_use' as any,
|
|
},
|
|
{
|
|
content: [{ type: 'text', text: 'done' }] as any,
|
|
stop_reason: 'end_turn',
|
|
},
|
|
]);
|
|
const handler = makeSubagentHandler({ engine, client, toolRegistry: [tool] });
|
|
const ctx = await makeCtx({ prompt: 'go' });
|
|
|
|
const result = await handler(ctx);
|
|
expect(result.stop_reason).toBe('end_turn');
|
|
expect(result.result).toBe('done');
|
|
expect(client.calls.length).toBe(2);
|
|
|
|
// tool_executions row complete with echoed output
|
|
const rows = await engine.executeRaw<{ status: string; output: unknown }>(
|
|
`SELECT status, output FROM subagent_tool_executions WHERE job_id = $1`,
|
|
[ctx.id],
|
|
);
|
|
expect(rows.length).toBe(1);
|
|
expect(rows[0]!.status).toBe('complete');
|
|
const out = typeof rows[0]!.output === 'string' ? JSON.parse(rows[0]!.output as string) : rows[0]!.output;
|
|
expect(out).toEqual({ echoed: { value: 'v1' } });
|
|
});
|
|
|
|
test('tool throws: row goes failed, model sees error, loop continues', async () => {
|
|
const tool = makeThrowingTool();
|
|
const client = new FakeMessagesClient([
|
|
{
|
|
content: [{ type: 'tool_use', id: 'tu_1', name: 'broken', input: {} } as any],
|
|
stop_reason: 'tool_use' as any,
|
|
},
|
|
{
|
|
content: [{ type: 'text', text: 'recovered' }] as any,
|
|
stop_reason: 'end_turn',
|
|
},
|
|
]);
|
|
const handler = makeSubagentHandler({ engine, client, toolRegistry: [tool] });
|
|
const ctx = await makeCtx({ prompt: 'try' });
|
|
|
|
const result = await handler(ctx);
|
|
expect(result.stop_reason).toBe('end_turn');
|
|
expect(result.result).toBe('recovered');
|
|
|
|
const rows = await engine.executeRaw<{ status: string; error: string | null }>(
|
|
`SELECT status, error FROM subagent_tool_executions WHERE job_id = $1`,
|
|
[ctx.id],
|
|
);
|
|
expect(rows[0]!.status).toBe('failed');
|
|
expect(rows[0]!.error).toContain('tool broken');
|
|
});
|
|
|
|
test('unknown tool name fails execution but loop continues', async () => {
|
|
const client = new FakeMessagesClient([
|
|
{
|
|
content: [{ type: 'tool_use', id: 'tu_nope', name: 'no_such_tool', input: {} } as any],
|
|
stop_reason: 'tool_use' as any,
|
|
},
|
|
{ content: [{ type: 'text', text: 'ok' }] as any, stop_reason: 'end_turn' },
|
|
]);
|
|
const handler = makeSubagentHandler({ engine, client, toolRegistry: [] });
|
|
const ctx = await makeCtx({ prompt: 'x' });
|
|
|
|
const result = await handler(ctx);
|
|
expect(result.stop_reason).toBe('end_turn');
|
|
|
|
const rows = await engine.executeRaw<{ status: string; error: string | null }>(
|
|
`SELECT status, error FROM subagent_tool_executions WHERE job_id = $1`,
|
|
[ctx.id],
|
|
);
|
|
expect(rows[0]!.status).toBe('failed');
|
|
expect(rows[0]!.error).toContain('not in the registry');
|
|
});
|
|
|
|
test('max_turns exceeded returns stop_reason=max_turns', async () => {
|
|
// Model keeps calling tool_use forever; we cap at 2 turns.
|
|
const echoing: FakeResponse[] = Array.from({ length: 5 }).map((_, i) => ({
|
|
content: [{ type: 'tool_use', id: `tu_${i}`, name: 'echo', input: {} } as any],
|
|
stop_reason: 'tool_use' as any,
|
|
}));
|
|
const client = new FakeMessagesClient(echoing);
|
|
const tool = makeEchoTool();
|
|
const handler = makeSubagentHandler({ engine, client, toolRegistry: [tool] });
|
|
const ctx = await makeCtx({ prompt: 'loop', max_turns: 2 });
|
|
|
|
const result = await handler(ctx);
|
|
expect(result.stop_reason).toBe('max_turns');
|
|
expect(result.turns_count).toBe(2);
|
|
});
|
|
});
|
|
|
|
describe('subagent handler replay (crash recovery)', () => {
|
|
test('resumes from persisted messages when prior rows exist', async () => {
|
|
// Seed an in-progress conversation by running the first client, then
|
|
// running a second handler on the SAME job with responses starting at
|
|
// turn 2. No duplicate user-seed row (ON CONFLICT DO NOTHING).
|
|
const tool = makeEchoTool();
|
|
const client1 = new FakeMessagesClient([
|
|
{
|
|
content: [{ type: 'tool_use', id: 'tu_1', name: 'echo', input: { v: 1 } } as any],
|
|
stop_reason: 'tool_use' as any,
|
|
},
|
|
]);
|
|
const handler1 = makeSubagentHandler({ engine, client: client1, toolRegistry: [tool] });
|
|
const ctx = await makeCtx({ prompt: 'start' });
|
|
|
|
// Run handler1 until it WOULD make a second LLM call — force that
|
|
// second call to error so we persist only the first assistant message.
|
|
try {
|
|
const client1b = new FakeMessagesClient([
|
|
{
|
|
content: [{ type: 'tool_use', id: 'tu_1', name: 'echo', input: { v: 1 } } as any],
|
|
stop_reason: 'tool_use' as any,
|
|
},
|
|
]);
|
|
const interrupted = makeSubagentHandler({ engine, client: client1b, toolRegistry: [tool] });
|
|
await interrupted(ctx);
|
|
} catch {
|
|
// Out-of-scripted-responses — simulates worker kill before turn 2.
|
|
}
|
|
|
|
// Confirm partial state: 1 user + 1 assistant + 1 synthesized user
|
|
// (tool_result) + 1 tool_exec complete.
|
|
const preRows = await engine.executeRaw<{ c: string }>(
|
|
`SELECT count(*)::text AS c FROM subagent_messages WHERE job_id = $1`,
|
|
[ctx.id],
|
|
);
|
|
const preCount = parseInt(preRows[0]!.c, 10);
|
|
expect(preCount).toBeGreaterThanOrEqual(1);
|
|
|
|
// Resume with a fresh handler + client that supplies ONE more response.
|
|
const client2 = new FakeMessagesClient([
|
|
{ content: [{ type: 'text', text: 'resumed ok' }] as any, stop_reason: 'end_turn' },
|
|
]);
|
|
const handler2 = makeSubagentHandler({ engine, client: client2, toolRegistry: [tool] });
|
|
const result = await handler2(ctx);
|
|
|
|
expect(result.result).toBe('resumed ok');
|
|
expect(result.stop_reason).toBe('end_turn');
|
|
// Second client should see the prior conversation in the messages
|
|
// array — at minimum the user seed + prior assistant + tool_result.
|
|
expect(client2.calls[0]!.messages.length).toBeGreaterThan(1);
|
|
});
|
|
|
|
test('prior completed tool exec is replayed without re-invoking execute', async () => {
|
|
// Prior state: a completed tool row. We assert the tool's execute is
|
|
// NOT called on resume. Use a tool that throws if invoked — passing
|
|
// means we used the replay path.
|
|
const throwingTool = makeThrowingTool('pre_done');
|
|
const ctx = await makeCtx({ prompt: 'start' });
|
|
|
|
// Seed prior state manually: user, assistant with tool_use, tool_exec complete.
|
|
await engine.executeRaw(
|
|
`INSERT INTO subagent_messages (job_id, message_idx, role, content_blocks)
|
|
VALUES ($1, 0, 'user', $2::jsonb)`,
|
|
[ctx.id, JSON.stringify([{ type: 'text', text: 'start' }])],
|
|
);
|
|
await engine.executeRaw(
|
|
`INSERT INTO subagent_messages (job_id, message_idx, role, content_blocks, model)
|
|
VALUES ($1, 1, 'assistant', $2::jsonb, 'claude-sonnet-4-6')`,
|
|
[
|
|
ctx.id,
|
|
JSON.stringify([
|
|
{ type: 'tool_use', id: 'tu_seeded', name: 'pre_done', input: {} },
|
|
]),
|
|
],
|
|
);
|
|
await engine.executeRaw(
|
|
`INSERT INTO subagent_tool_executions (job_id, message_idx, tool_use_id, tool_name, input, status, output)
|
|
VALUES ($1, 1, 'tu_seeded', 'pre_done', '{}'::jsonb, 'complete', $2::jsonb)`,
|
|
[ctx.id, JSON.stringify({ replayed: true })],
|
|
);
|
|
|
|
// Handler MUST NOT call the throwing execute and MUST end the loop on
|
|
// the next LLM response.
|
|
const client = new FakeMessagesClient([
|
|
{ content: [{ type: 'text', text: 'finished after replay' }] as any, stop_reason: 'end_turn' },
|
|
]);
|
|
const handler = makeSubagentHandler({ engine, client, toolRegistry: [throwingTool] });
|
|
const result = await handler(ctx);
|
|
|
|
expect(result.stop_reason).toBe('end_turn');
|
|
expect(result.result).toBe('finished after replay');
|
|
// Only one LLM call made on this resume (we had 2 persisted messages +
|
|
// the tool result synthesis happened when resuming, then model spoke).
|
|
expect(client.calls.length).toBe(1);
|
|
});
|
|
|
|
// v0.37.7.0 #1151 regression — terminal-on-resume.
|
|
// Pre-fix, this scenario dead-lettered the job: replay reconciler saw
|
|
// last=assistant with zero tool_uses, did nothing, main loop called
|
|
// messages.create against a conversation ending in assistant → Sonnet
|
|
// 4.6+ rejects assistant-prefill with HTTP 400 → 3 retries → dead.
|
|
// Post-fix, the reconciler short-circuits: reconstructs finalText from
|
|
// the persisted text blocks and returns stop_reason='end_turn' without
|
|
// any LLM call.
|
|
test('text-only assistant tail on resume returns terminal without LLM call (#1151)', async () => {
|
|
const ctx = await makeCtx({ prompt: 'start' });
|
|
// Seed prior state: user prompt, then a TERMINAL assistant turn
|
|
// (text-only, no tool_use blocks). This is the exact shape the
|
|
// #1151 reporter found in their dead jobs (job 190's last message
|
|
// was a synthesis summary listing 3 written slugs).
|
|
await engine.executeRaw(
|
|
`INSERT INTO subagent_messages (job_id, message_idx, role, content_blocks)
|
|
VALUES ($1, 0, 'user', $2::jsonb)`,
|
|
[ctx.id, JSON.stringify([{ type: 'text', text: 'start' }])],
|
|
);
|
|
await engine.executeRaw(
|
|
`INSERT INTO subagent_messages (job_id, message_idx, role, content_blocks, model, tokens_in, tokens_out)
|
|
VALUES ($1, 1, 'assistant', $2::jsonb, 'claude-sonnet-4-6', 100, 50)`,
|
|
[
|
|
ctx.id,
|
|
JSON.stringify([
|
|
{ type: 'text', text: 'wrote 3 pages: wiki/notes/a, wiki/notes/b, wiki/notes/c' },
|
|
]),
|
|
],
|
|
);
|
|
|
|
// The FakeMessagesClient has ZERO scripted responses. If the handler
|
|
// tries to call messages.create, it throws. The fix guarantees we
|
|
// never reach that path.
|
|
const client = new FakeMessagesClient([]);
|
|
const handler = makeSubagentHandler({ engine, client, toolRegistry: [] });
|
|
const result = await handler(ctx);
|
|
|
|
expect(result.stop_reason).toBe('end_turn');
|
|
expect(result.result).toBe('wrote 3 pages: wiki/notes/a, wiki/notes/b, wiki/notes/c');
|
|
// Crucial assertion: no messages.create call was made on resume.
|
|
expect(client.calls.length).toBe(0);
|
|
// Token totals from the persisted assistant message rolled up.
|
|
expect(result.tokens.in).toBe(100);
|
|
expect(result.tokens.out).toBe(50);
|
|
});
|
|
|
|
// Companion: the existing tool-use replay path is unchanged.
|
|
test('text-only terminal short-circuit does NOT affect tool-use replay path', async () => {
|
|
// This is a smoke test that the new else-branch doesn't accidentally
|
|
// swallow the pending-tool-use case. If we have a persisted assistant
|
|
// with a tool_use block (no synthesized user turn yet), the existing
|
|
// tool-synthesis path must still fire.
|
|
const echoTool = makeEchoTool('echo_x');
|
|
const ctx = await makeCtx({ prompt: 'start' });
|
|
await engine.executeRaw(
|
|
`INSERT INTO subagent_messages (job_id, message_idx, role, content_blocks)
|
|
VALUES ($1, 0, 'user', $2::jsonb)`,
|
|
[ctx.id, JSON.stringify([{ type: 'text', text: 'start' }])],
|
|
);
|
|
await engine.executeRaw(
|
|
`INSERT INTO subagent_messages (job_id, message_idx, role, content_blocks, model)
|
|
VALUES ($1, 1, 'assistant', $2::jsonb, 'claude-sonnet-4-6')`,
|
|
[
|
|
ctx.id,
|
|
JSON.stringify([
|
|
{ type: 'tool_use', id: 'tu_pending', name: 'echo_x', input: { v: 'r' } },
|
|
]),
|
|
],
|
|
);
|
|
// No prior tool_exec row — replay reconciler will dispatch.
|
|
const client = new FakeMessagesClient([
|
|
{ content: [{ type: 'text', text: 'done after tool' }] as any, stop_reason: 'end_turn' },
|
|
]);
|
|
const handler = makeSubagentHandler({ engine, client, toolRegistry: [echoTool] });
|
|
const result = await handler(ctx);
|
|
expect(result.stop_reason).toBe('end_turn');
|
|
expect(result.result).toBe('done after tool');
|
|
// The handler DID call messages.create (one call) after synthesizing
|
|
// the tool_result wrapper.
|
|
expect(client.calls.length).toBe(1);
|
|
});
|
|
|
|
test('pending non-idempotent tool exec rejects on resume', async () => {
|
|
const nonIdempotent = { ...makeEchoTool('do_once'), idempotent: false };
|
|
const ctx = await makeCtx({ prompt: 'start' });
|
|
await engine.executeRaw(
|
|
`INSERT INTO subagent_messages (job_id, message_idx, role, content_blocks)
|
|
VALUES ($1, 0, 'user', $2::jsonb)`,
|
|
[ctx.id, JSON.stringify([{ type: 'text', text: 'start' }])],
|
|
);
|
|
await engine.executeRaw(
|
|
`INSERT INTO subagent_messages (job_id, message_idx, role, content_blocks)
|
|
VALUES ($1, 1, 'assistant', $2::jsonb)`,
|
|
[
|
|
ctx.id,
|
|
JSON.stringify([{ type: 'tool_use', id: 'tu_x', name: 'do_once', input: {} }]),
|
|
],
|
|
);
|
|
await engine.executeRaw(
|
|
`INSERT INTO subagent_tool_executions (job_id, message_idx, tool_use_id, tool_name, input, status)
|
|
VALUES ($1, 1, 'tu_x', 'do_once', '{}'::jsonb, 'pending')`,
|
|
[ctx.id],
|
|
);
|
|
|
|
const client = new FakeMessagesClient([]);
|
|
const handler = makeSubagentHandler({ engine, client, toolRegistry: [nonIdempotent] });
|
|
await expect(handler(ctx)).rejects.toThrow(/non-idempotent/);
|
|
});
|
|
});
|
|
|
|
describe('subagent handler lease behavior', () => {
|
|
test('acquires + releases a lease around the LLM call', async () => {
|
|
const client = new FakeMessagesClient([
|
|
{ content: [{ type: 'text', text: 'ok' }] as any, stop_reason: 'end_turn' },
|
|
]);
|
|
const handler = makeSubagentHandler({
|
|
engine, client, toolRegistry: [], maxConcurrent: 1, rateLeaseKey: 'k1',
|
|
});
|
|
const ctx = await makeCtx({ prompt: 'hi' });
|
|
await handler(ctx);
|
|
// No leases should remain after completion.
|
|
const rows = await engine.executeRaw<{ c: string }>(
|
|
`SELECT count(*)::text AS c FROM subagent_rate_leases`,
|
|
);
|
|
expect(parseInt(rows[0]!.c, 10)).toBe(0);
|
|
});
|
|
|
|
test('throws RateLeaseUnavailableError when cap full', async () => {
|
|
// Preload the cap with a stale-looking-but-live lease owned by a
|
|
// different job.
|
|
const owner = await queue.add('holder', {});
|
|
await engine.executeRaw(
|
|
`INSERT INTO subagent_rate_leases (key, owner_job_id, expires_at)
|
|
VALUES ('k_cap', $1, now() + interval '1 minute')`,
|
|
[owner.id],
|
|
);
|
|
const client = new FakeMessagesClient([]);
|
|
const handler = makeSubagentHandler({
|
|
engine, client, toolRegistry: [], maxConcurrent: 1, rateLeaseKey: 'k_cap',
|
|
});
|
|
const ctx = await makeCtx({ prompt: 'blocked' });
|
|
await expect(handler(ctx)).rejects.toBeInstanceOf(RateLeaseUnavailableError);
|
|
});
|
|
});
|
|
|
|
describe('subagent handler input validation', () => {
|
|
test('missing prompt throws', async () => {
|
|
const client = new FakeMessagesClient([]);
|
|
const handler = makeSubagentHandler({ engine, client, toolRegistry: [] });
|
|
const ctx = await makeCtx({});
|
|
await expect(handler(ctx)).rejects.toThrow(/prompt/);
|
|
});
|
|
|
|
test('allowed_tools unknown name rejected at dispatch', async () => {
|
|
const tool = makeEchoTool('real');
|
|
const client = new FakeMessagesClient([]);
|
|
const handler = makeSubagentHandler({ engine, client, toolRegistry: [tool] });
|
|
const ctx = await makeCtx({ prompt: 'x', allowed_tools: ['real', 'ghost_tool'] });
|
|
await expect(handler(ctx)).rejects.toThrow(/unknown tool/);
|
|
});
|
|
});
|
|
|
|
describe('makeSubagentHandler default client construction', () => {
|
|
test('factory default wires sdk.messages through to the handler', async () => {
|
|
// Regression guard for the v0.16.0 shipped bug: makeSubagentHandler
|
|
// was casting `new Anthropic()` (top-level SDK class) to MessagesClient,
|
|
// but `.create()` lives at sdk.messages.create. Every subagent job in
|
|
// production died with "client.create is not a function" on first LLM
|
|
// call. This test exercises the default-client path (no `deps.client`
|
|
// injected) via the makeAnthropic dep-injection seam, so the exact
|
|
// default-branch construction is covered without a real API call.
|
|
const calls: Anthropic.MessageCreateParamsNonStreaming[] = [];
|
|
const fakeSdk = {
|
|
messages: {
|
|
async create(
|
|
params: Anthropic.MessageCreateParamsNonStreaming,
|
|
): Promise<Anthropic.Message> {
|
|
calls.push(params);
|
|
return {
|
|
id: 'msg_regression',
|
|
type: 'message',
|
|
role: 'assistant',
|
|
model: params.model,
|
|
stop_reason: 'end_turn',
|
|
stop_sequence: null,
|
|
content: [{ type: 'text', text: 'ok' }],
|
|
usage: {
|
|
input_tokens: 1,
|
|
output_tokens: 1,
|
|
cache_read_input_tokens: 0,
|
|
cache_creation_input_tokens: 0,
|
|
},
|
|
} as unknown as Anthropic.Message;
|
|
},
|
|
},
|
|
} as unknown as Anthropic;
|
|
|
|
// Crucial: do NOT pass `client`. Only `makeAnthropic`. This forces the
|
|
// factory to hit the default-client branch (`deps.client ?? makeAnthropic().messages`).
|
|
const handler = makeSubagentHandler({
|
|
engine,
|
|
makeAnthropic: () => fakeSdk,
|
|
toolRegistry: [],
|
|
});
|
|
const ctx = await makeCtx({ prompt: 'hello' });
|
|
const result = await handler(ctx);
|
|
|
|
expect(calls.length).toBe(1);
|
|
expect(result.stop_reason).toBe('end_turn');
|
|
expect(result.result).toBe('ok');
|
|
});
|
|
});
|