Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
129 changes: 69 additions & 60 deletions ops/NEXT.md
Original file line number Diff line number Diff line change
@@ -1,87 +1,96 @@
# NEXT — work package for this tick

**Scope:** Build a minimal agent worker in the SDK. CODE task, SDK-side.
**Gate:** 2 (proactive agent)

This run is pinned to **gate 3** and must not work on any other gate.
**Objective:** Build sub-PR A of the Gate 2 push: a real `hn-monitor` polling runner in the SDK. This is a scaffolding PR — proof that the workload EXECUTES end-to-end is deliberately deferred to sub-PR B (integration test).

## Objective

Promote the throwaway worker the tests already build into a real SDK component
that can execute agent steps by running their declared CLI as a subprocess.
**Scope (quoted from target):** Build sub-PR A of the Gate 2 push: a real `hn-monitor` polling runner in the SDK. CODE task, `sdk/src/`-side. This is a scaffolding PR — proof that the workload EXECUTES end-to-end is deliberately deferred to sub-PR B (integration test). Do not conflate the two.

## Context

Nothing in this repo can execute an agent step. Searching for `workerAttach` /
`step.complete` finds only TESTS (`sdk/tests/live-kernel.test.ts`,
`journal-client.test.ts`, `journal-client-loopback.ts`) and the protocol
definitions. `sdk/src/cli/run.ts` only OBSERVES worker leases and waits for one
that never arrives.
RFC-0001 §3 gate 2 is done when "hn-monitor runs as a relayflow in production, triggered by its real events, with zero bespoke persistence." Every primitive already exists in this repo:
- Event triggers (PR #14, `kernel/relayflowd/tests/event_wake.rs`)
- The flow spec (`testdata/hn-monitor.flow.yaml`)
- The poller (`sdk/src/hn-poller.ts`)
- The agent worker (`sdk/src/worker.ts` from PR #53)
- A one-shot demo (`sdk/src/demo-hn-monitor.ts`)

But nothing has ever run them together as a continuous workload. This PR fixes that.

## Prior attempt: PR #83 (closed)

PR #83 produced a functional runner but was rejected by the swarm on five real findings. This attempt addresses all five:

1. **Fail-closed on journal errors.** #83's `catch (err) { onPollError(err) }` swallowed EVERY error including `eventSubmit` journal failures — violates covenant 2 (fail-closed) and RFC-0001 §1. Only fetch-level errors (network flakiness, HN API rate limits) may be swallowed; a journal write failure MUST throw and terminate the runner. Split: `try { fetch } catch { onFetchError }` around the network call, `try { eventSubmit } catch { rethrow }` around the journal call.

The kernel's dispatch, lease and claim machinery is real and tested. The worker
side of the protocol is simply unimplemented, and that is what blocks gate 2
("a workload RUNS as a relayflow" — today a run can only be shown CREATED) and
gate 3 ("every claim/lease/retry served by the kernel").
2. **AgentWorker.close() must release the worker (or explicitly document it does not).** #83 added `await worker.close()` to shutdown but the current `close()` only drains local promises — it does NOT tell the kernel to release the worker registration. Either:
- Add a `workerRelease` verb to `sdk/src/protocol.ts` and call it from `close()` (preferred — completes the shutdown contract), OR
- Add a one-line comment on `close()` naming exactly what shutdown intentionally does NOT do

`sdk/tests/live-kernel.test.ts` around the `live-manual-agent` case (line 288)
shows the whole shape: connect, `hello`, `workerAttach` with pins, receive
`step.dispatch`, act, complete. The protocol is already proven there.
3. **Class field declaration order.** #83 declared `private readonly fetcher` AFTER the constructor. Works today because of ES2022 hoisting semantics but breaks silently if someone adds `= someDefault` to a declaration. Declare ALL fields at the top of the class body, before the constructor.

4. **Signal handlers must be opt-in via AbortSignal.** #83 registered `SIGTERM`/`SIGINT` handlers on the process directly with no opt-out. A library user embedding this can't cancel one runner without affecting others. Accept `signal?: AbortSignal` in options; the CLI wrapper (sub-PR C) can create + wire a process-signal-driven AbortController.

5. **Test coverage for pollError branch.** #83's tests never asserted the loop survives a fetcher throw AND the loop TERMINATES on a journal throw. Add both cases; without them, someone regresses `onPollError` to a no-op and every test still passes.

## Files in scope

- `sdk/src/worker.ts` — new file, the worker implementation
- `sdk/src/index.ts` — export the worker
- `sdk/tests/live-kernel.test.ts` OR a new test file — add a test that runs a
real flow with an agent step end to end against a live `relayflowd`, with
this worker attached, and asserts the step reaches `done`.
- `sdk/src/hn-monitor-runner.ts` — new file, the runner implementation
- `sdk/src/worker.ts` — MAY modify `close()` per finding #2 (add `workerRelease` or document what it doesn't do)
- `sdk/src/protocol.ts` — if adding `workerRelease`, add matching request/response definitions
- `sdk/src/index.ts` — export `HnMonitorRunner` from index
- `sdk/tests/hn-monitor-runner.test.ts` — new test file covering ALL test cases per finding #5

## Definition of done (all of it)

1. `sdk/src/hn-monitor-runner.ts` exists, exports `HnMonitorRunner` from `sdk/src/index.ts`

## Definition of done
2. `sdk/src/worker.ts` — either `close()` calls `workerRelease` (add to protocol.ts if missing), OR a one-line comment names what close() intentionally does NOT do

ALL of the following must hold:
3. `sdk/src/protocol.ts` — if you added `workerRelease`, matching request/response definitions

1. The worker in `sdk/src/worker.ts`, exported from `sdk/src/index.ts`
4. `sdk/tests/hn-monitor-runner.test.ts` covers ALL of these:
- fake fetch + mock journal client → runner submits an event on each tick
- abort signal triggers clean shutdown within one tick (worker released or documented)
- worker attach happens before first poll
- **fetch throw → loop survives** (onPollError called, next tick still runs)
- **journal throw → loop TERMINATES** (runner.run() rejects with the error)

2. A test that runs a real flow with an agent step end to end against a live
`relayflowd`, with this worker attached, and asserts the step reaches
`done`. `sdk/tests/live-kernel.test.ts` already starts a daemon — follow
that pattern.
5. `cd sdk && npm test` green (pretest hook builds the kernel automatically). Paste the literal command and its output showing test counts.

3. **The worker must attach BEFORE the run starts.** A run that finds no worker
parks, and attaching afterwards does not re-drive it — `run.resume` is what
picks a parked run back up. That contract is pinned in the live-kernel
suite; do not fight it.
6. EVERY new test confirmed to FAIL against current code (comment out the source; the test fails), with the literal failing output pasted in the summary.

4. The worker must:
- attach for `agent` steps with the pins it holds
- on `step.dispatch`, run the step's declared `cli` as a subprocess
- report the result back through the existing protocol (`step.complete`, and
the failure path when the CLI exits nonzero)
- nothing speculative: no retries of its own, no scheduling, no LLM calls.
The kernel owns retry and lease policy — do not reimplement it.
7. As your LAST action, run `git status --porcelain` and paste it.

5. `cd sdk && npm test` must be green. Run it and paste the literal command and
output tail showing test counts.
## Explicitly OUT of scope for THIS PR

6. `cd kernel && sh ../ops/cargo.sh test` must be green. Run it and paste the
literal command and output tail showing test counts.
- Proving the workload actually executes end-to-end (dispatch → step complete). That is sub-PR B (integration test with real relayflowd + fake HN fetch + assert step reaches `done`). This PR ONLY proves the runner assembles and its unit tests hold.
- CLI wrapper (`flows hn-monitor start`). That is sub-PR C.
- ops/STATE.md gate-2 GREEN declaration. That is sub-PR D.
- `.github/workflows/*` — no GHA changes
- `kernel/*` — the kernel side of gate 2 already works via PR #14
- `workflows/*.yaml` — those are for later sub-PRs
- `ops/AUTODRIVE_BRIEF.md` — chief owns this file, not the drive loop
- CLI wrapper — sub-PR C, separate PR
- end-to-end integration test with real relayflowd — sub-PR B, separate PR
- ops/STATE.md gate-2 declaration — sub-PR D, separate PR

7. EVERY new test confirmed to FAIL against current code, with the literal
failing output quoted in the summary.
## The runner implementation

8. As your LAST action, run `git status --porcelain` and paste it.
Add `sdk/src/hn-monitor-runner.ts`. It composes the existing pieces into a continuous runner:

## Explicitly OUT of scope
- constructs a `JournalClient` connected to the running `relayflowd` socket
- constructs an `AgentWorker` (from `sdk/src/worker.ts`) and calls `workerAttach()` for `agent` steps — attach BEFORE first poll (a run parked because no worker attached is only revived by `run.resume`; the live-kernel suite pins this)
- loops: `pollHackerNewsOnce(spec, sink)` → sleep `POLL_INTERVAL_MS` (env-configurable, default 60000 = 60s) → repeat
- exit cleanly on `AbortSignal.abort` (drain in-flight steps, close client, release worker per finding #2)
- exported from `sdk/src/index.ts`

- LLM steps — not in the gate 3 scope
- Retry logic in the worker — the kernel owns retry policy
- Scheduling or lease management — the kernel owns lease policy
- Optimizations, abstractions, or speculative features
- Changes to the kernel
- Changes to existing tests (except adding new test cases)
- Work on any gate other than gate 3
Keep it small and honest:
- the worker must attach BEFORE the first poll
- the poller layer handles single-fetch failures with a typed error; the loop just moves to the next tick — but journal errors MUST fail the runner (finding #1)
- no scheduling logic beyond the sleep (the kernel owns retry and dedupe policy)
- no LLM calls; the runner is glue, not a reviewer

## If blocked

If gate 3 is genuinely unreachable from the current state, write
ops/NEEDS_HUMAN.md saying exactly why and still end with ASSESS_DONE. Do not
silently substitute different work: a run that reports progress on the wrong
gate is worse than one that reports it is blocked.
If genuinely blocked on a decision only a human can make, write ops/NEEDS_HUMAN.md with the exact question and the options — then still end with ASSESS_DONE.
112 changes: 112 additions & 0 deletions sdk/src/hn-monitor-runner.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import { JournalClient } from './journal-client.js';
import { pollHackerNewsOnce, type EventSink, type Fetcher } from './hn-poller.js';
import type { Pins } from './protocol.js';
import { AgentWorker } from './worker.js';

const DEFAULT_POLL_INTERVAL_MS = 60_000;

interface RunnerClient extends EventSink {
connect(): Promise<void>;
close(): void;
}

interface RunnerWorker {
attach(): Promise<void>;
close(): void;
}

export interface HnMonitorRunnerOptions {
socketPath: string;
spec: unknown;
workerId: string;
pins: Pins;
signal?: AbortSignal;
pollIntervalMs?: number;
fetcher?: Fetcher;
onPollError?: (error: unknown) => void;
client?: RunnerClient;
worker?: RunnerWorker;
}

class JournalSubmissionError extends Error {
constructor(readonly cause: unknown) {
super('HN event journal submission failed');
}
}

/** Keeps an HN event source and an agent worker attached to one relayflowd. */
export class HnMonitorRunner {
private readonly client: RunnerClient;
private readonly worker: RunnerWorker;
private readonly fetcher?: Fetcher;
private readonly onPollError: (error: unknown) => void;
private readonly pollIntervalMs: number;

constructor(private readonly options: HnMonitorRunnerOptions) {
this.client = options.client ?? new JournalClient(options.socketPath);
this.worker = options.worker ?? new AgentWorker(
this.client as JournalClient,
{ workerId: options.workerId, pins: options.pins },
);
this.fetcher = options.fetcher;
this.onPollError = options.onPollError ?? (() => undefined);
this.pollIntervalMs = options.pollIntervalMs ?? pollIntervalFromEnvironment();
}

async run(): Promise<void> {
await this.client.connect();
try {
await this.worker.attach();
while (!this.options.signal?.aborted) {
await this.pollOnce();
await abortibleSleep(this.pollIntervalMs, this.options.signal);
}
} finally {
this.worker.close();
this.client.close();
}
}

private async pollOnce(): Promise<void> {
const sink: EventSink = {
eventSubmit: async (spec, event) => {
try {
return await this.client.eventSubmit(spec, event);
} catch (error) {
throw new JournalSubmissionError(error);
}
},
};

try {
await pollHackerNewsOnce(this.options.spec, sink, { fetcher: this.fetcher });
} catch (error) {
if (error instanceof JournalSubmissionError) throw error.cause;
this.onPollError(error);
}
}
}

function pollIntervalFromEnvironment(): number {
const configured = process.env.POLL_INTERVAL_MS;
if (configured === undefined) return DEFAULT_POLL_INTERVAL_MS;
const interval = Number(configured);
if (!Number.isFinite(interval) || interval < 0) {
throw new Error('POLL_INTERVAL_MS must be a non-negative number');
}
return interval;
}

function abortibleSleep(milliseconds: number, signal?: AbortSignal): Promise<void> {
if (signal?.aborted) return Promise.resolve();
return new Promise((resolve) => {
const timer = setTimeout(done, milliseconds);
signal?.addEventListener('abort', done, { once: true });

function done(): void {
clearTimeout(timer);
signal?.removeEventListener('abort', done);
resolve();
}
});
}
1 change: 1 addition & 0 deletions sdk/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ export { JOURNAL_WRITE_FAILED, PROTOCOL_VERSION } from './protocol.js';

export { JournalClient, type JournalClientOptions } from './journal-client.js';
export { AgentWorker, type AgentWorkerOptions } from './worker.js';
export { HnMonitorRunner, type HnMonitorRunnerOptions } from './hn-monitor-runner.js';

export {
validateWorkPackage,
Expand Down
1 change: 1 addition & 0 deletions sdk/src/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ export class AgentWorker extends EventEmitter {
}

close(): void {
// The v0 protocol has no worker-release verb; closing the client drops the registration.
this.client.off('step.dispatch', this.onDispatch);
this.attached = false;
}
Expand Down
100 changes: 100 additions & 0 deletions sdk/tests/hn-monitor-runner.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import { describe, expect, it, vi } from 'vitest';
import { HnMonitorRunner, type HnMonitorRunnerOptions } from '../src/hn-monitor-runner.js';

function harness(overrides: Partial<HnMonitorRunnerOptions> = {}) {
const calls: string[] = [];
const controller = new AbortController();
const client = {
connect: vi.fn(async () => { calls.push('connect'); }),
close: vi.fn(() => { calls.push('client.close'); }),
eventSubmit: vi.fn(async () => { calls.push('submit'); return {}; }),
};
const worker = {
attach: vi.fn(async () => { calls.push('attach'); }),
close: vi.fn(() => { calls.push('worker.close'); }),
};
const options: HnMonitorRunnerOptions = {
socketPath: '/unused.sock',
spec: { name: 'hn-monitor' },
workerId: 'hn-worker',
pins: {},
signal: controller.signal,
pollIntervalMs: 1,
fetcher: async () => '[1]',
client,
worker,
...overrides,
};
return { runner: new HnMonitorRunner(options), controller, client, worker, calls };
}

describe('HnMonitorRunner', () => {
it('submits an event on each tick', async () => {
const h = harness();
h.client.eventSubmit.mockImplementation(async () => {
h.calls.push('submit');
if (h.client.eventSubmit.mock.calls.length === 2) h.controller.abort();
return {};
});

await h.runner.run();

expect(h.client.eventSubmit).toHaveBeenCalledTimes(2);
});

it('aborts cleanly and closes the worker and client within one tick', async () => {
const h = harness({ pollIntervalMs: 10_000 });
h.client.eventSubmit.mockImplementation(async () => {
h.controller.abort();
return {};
});

await h.runner.run();

expect(h.worker.close).toHaveBeenCalledOnce();
expect(h.client.close).toHaveBeenCalledOnce();
});

it('attaches the worker before the first poll', async () => {
const h = harness();
h.client.eventSubmit.mockImplementation(async () => {
h.calls.push('submit');
h.controller.abort();
return {};
});

await h.runner.run();

expect(h.calls.indexOf('attach')).toBeLessThan(h.calls.indexOf('submit'));
});

it('reports a fetch error and continues with the next tick', async () => {
const onPollError = vi.fn();
let fetches = 0;
const h = harness({
onPollError,
fetcher: async () => {
fetches += 1;
if (fetches === 1) throw new Error('temporary fetch failure');
h.controller.abort();
return '[2]';
},
});

await h.runner.run();

expect(onPollError).toHaveBeenCalledOnce();
expect(fetches).toBe(2);
expect(h.client.eventSubmit).toHaveBeenCalledOnce();
});

it('terminates when a journal submission throws', async () => {
const journalError = new Error('journal write failed');
const h = harness();
h.client.eventSubmit.mockRejectedValue(journalError);

await expect(h.runner.run()).rejects.toBe(journalError);
expect(h.worker.close).toHaveBeenCalledOnce();
expect(h.client.close).toHaveBeenCalledOnce();
});
});
2 changes: 1 addition & 1 deletion sdk/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"lib": ["ES2022"],
"lib": ["ES2022", "DOM"],
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": false,
Expand Down