diff --git a/pm-stack/README.md b/pm-stack/README.md index 706c052e09..dfac41fadb 100644 --- a/pm-stack/README.md +++ b/pm-stack/README.md @@ -218,20 +218,26 @@ cd ready-for-agent ./install.sh clone # one-time: clone the repos it serves into ./repos/ ``` -- **Register a repo** through the harness's GraphQL API (loopback - `http://127.0.0.1:6056/graphql`): mutation - `addLocalRepository(path: "")`. - Do **not** use the `ready-for-agent add` CLI from an interactive - SSH shell on this host — its in-process git inspection returns +- **Register + configure repos declaratively (#1203):** + [`ready-for-agent/config.json`](ready-for-agent/config.json) names + every served repository (clone URL, local dir, `mergePolicy`, + `defaultModel`, `includeAllIssueAuthors`, paused). `./install.sh + clone` clones/fetches them all into `ready-for-agent/repos/`, and + every `./install.sh` run finishes by applying the config through + the harness's GraphQL API via + [`ready-for-agent/apply-config.sh`](ready-for-agent/apply-config.sh) + (addLocalRepository for unregistered clones, a full-object + updateRepositorySettings built from the live settings with only + the config-owned fields overridden, pause/unpause to match; a + converged harness receives no mutations, so re-runs are no-ops; + `DRY_RUN=1 ./apply-config.sh` previews). Fleet posture: + `mergePolicy: OFF` (human merge) on every repo. Do **not** use the + `ready-for-agent add` CLI from an interactive SSH shell on this + host - its in-process git inspection returns `NOT_A_GIT_REPOSITORY` for valid repos there (it succeeds from - the service's clean environment, which is what GraphQL uses). -- **Configure a repo** with `updateRepositorySettings` (a - full-object input — every field is required, so read the current - settings first) and `unpauseRepository`. Fleet posture for - `developing-today/code`: `mergePolicy: OFF` (human merge), - `includeAllIssueAuthors: true`, `defaultModel: -opencode-go/kimi-k3.1-pro` on the OpenCode backend. A repo with - no build model set refuses Implement ("No build model set"). + the service's clean environment, which is what GraphQL uses). A + repo with no build model set refuses Implement ("No build model + set") - the config's `defaultModel` is what prevents that. - **Dispatch:** label an issue `ready-for-agent`, then Implement from the UI, via GraphQL `implementNow(repositoryId, nativeId: "")`, or via the CLI `ready-for-agent intake diff --git a/pm-stack/aggregator/src/health.ts b/pm-stack/aggregator/src/health.ts index 6a2b9eee1f..4747477c19 100644 --- a/pm-stack/aggregator/src/health.ts +++ b/pm-stack/aggregator/src/health.ts @@ -30,6 +30,7 @@ import { import type { GhItem, ProvenanceDetail, RefKey } from "./model.ts"; import { PAGES } from "./pages.ts"; import { buildServices, type ServiceDef } from "./topology.ts"; +import { fetchRfaState, rfaHealthDown, rfaHealthFacet, type RfaHealthFacet, type RfaState } from "./sources/ready-for-agent.ts"; /** Orchestration cadence: hourly; next run is an expectation, not a promise. */ const ORCHESTRATION_CADENCE_MS = 3_600_000; @@ -192,6 +193,12 @@ export interface HealthView { /** Dashboard comment loops (#1145): pending triage/posting counts, * so an unworked comment queue is visible on /health. */ comments: PendingCommentCounts; + /** ready-for-agent harness facet (#1203): live GraphQL state — + * registered repositories, backend readiness, work-item counts — + * from src/sources/ready-for-agent.ts, not just the topology + * probe's HTTP 200. "down" with the error when the harness cannot + * be read; never an invented state. */ + rfa: RfaHealthFacet; } // --- Render registry ------------------------------------------------------- @@ -313,6 +320,8 @@ export interface HealthDeps { fetcher?: ProbeFetch; cache?: ProbeCache; now?: number; + /** #1203 test seam: replace the live harness read. */ + rfaState?: () => Promise; } export function resolveBuildVersion(env: Record = process.env): string { @@ -408,6 +417,21 @@ export async function buildHealth(inputs: HealthInputs, deps: HealthDeps = {}): }); } + // #1203: the harness facet — a real GraphQL read of the dispatch + // layer (cached 60 s inside fetchRfaState), reported down with its + // error rather than hidden when the harness cannot be read. + let rfa: RfaHealthFacet; + if (inputs.mode === "fixtures") { + rfa = { state: "fixtures", detail: "fixtures mode — no live harness read", repositories: [], backends: [] }; + } else { + try { + const state = deps.rfaState ? await deps.rfaState() : await fetchRfaState(cfg.readyForAgent.baseUrl); + rfa = rfaHealthFacet(state); + } catch (err) { + rfa = rfaHealthDown(`harness read failed: ${err instanceof Error ? err.message : String(err)}`); + } + } + const checkout = feed?.checkout ?? unreportedCheckoutDrift(); const sectionHealth = feedSections(feed, now); const degraded = @@ -415,6 +439,9 @@ export async function buildHealth(inputs: HealthInputs, deps: HealthDeps = {}): (services.some((s) => s.ok === false) || (feedAgeMs !== null && feedAgeMs >= FEED_STALE_MS) || checkout.state === "behind" || + // #1203: a harness whose GraphQL cannot be read (or whose backend + // is not READY) is a degraded dependency, not an invisible one. + rfa.state === "down" || sectionHealth.some((section) => section.status === "error")); return { @@ -450,6 +477,7 @@ export async function buildHealth(inputs: HealthInputs, deps: HealthDeps = {}): }, }, pages: pageHealth(now), + rfa, facets: inputs.detail ?? null, itemsCoverage: inputs.itemsCoverage ?? null, comments: inputs.comments ?? { pendingMessages: 0, pendingGithub: 0, total: 0 }, diff --git a/pm-stack/aggregator/src/render.ts b/pm-stack/aggregator/src/render.ts index d753c48127..a899de858e 100644 --- a/pm-stack/aggregator/src/render.ts +++ b/pm-stack/aggregator/src/render.ts @@ -6236,6 +6236,32 @@ export function renderHealth(view: HealthView, provenance: Provenance): string { return `${esc(p.title)}${esc(p.route)}${last}`; }) .join(""); + // #1203: the ready-for-agent facet — the harness's real dispatch-layer + // state, not just whether its UI answers 200. "down" means the GraphQL + // read failed (detail names the error) or a backend is not READY; the + // repositories table still shows what the harness reports when it can + // be read at all. + const rfa = view.rfa; + const rfaState = + rfa.state === "up" + ? 'up' + : rfa.state === "fixtures" + ? 'fixtures' + : 'down'; + const rfaRepoRows = rfa.repositories.length + ? rfa.repositories + .map( + (r) => + `${esc(r.projectPath)}${r.paused ? "paused" : "running"}${esc(r.mergePolicy ?? "—")}${r.workItems}`, + ) + .join("") + : `No harness repositories reported — the harness could not be read, or none are registered.`; + const rfaBackendLine = rfa.backends.length + ? `Backends: ${rfa.backends.map((b) => `${esc(b.id)} ${esc(b.kind)}${b.reason ? ` — ${esc(b.reason)}` : ""}`).join(" · ")}` + : "Backends: none reported."; + const rfaSection = `

ready-for-agent harness

+
${rfaState} — ${esc(rfa.detail)}
${rfaBackendLine}
+
${rfaRepoRows}
ready-for-agent repositories — settings and dispatch work items
RepositoryPausedMerge policyWork items
`; const cov = view.itemsCoverage; const coverageLine = cov && cov.total > 0 @@ -6269,6 +6295,7 @@ ${degraded}${modeNote}

Services & topology

What runs where: the component, its port and bind as actually deployed, what consumes it, and what breaks without it. State is probed, never assumed.

${serviceRows}
Services, ports, and topology
ServicePortBindRuns asStateConsumed byIf it is down
+${rfaSection}

Feed sections

${sectionRows}
Feed sections — presence and age
SectionPresentAgeNote

Jobs

diff --git a/pm-stack/aggregator/src/server.ts b/pm-stack/aggregator/src/server.ts index 9aff1272ba..58d789745a 100644 --- a/pm-stack/aggregator/src/server.ts +++ b/pm-stack/aggregator/src/server.ts @@ -1729,6 +1729,10 @@ async function handler(req: Request): Promise { body.pages = view.pages.map((p) => ({ route: p.route, lastRenderedAt: p.lastRenderedAt, ok: p.ok })); body.jobs = view.jobs; body.comments = view.comments; + // #1203: the ready-for-agent harness facet — backend readiness, + // repository settings, work-item counts and GraphQL errors reach the + // machine surface too, not only the rendered page. + body.rfa = view.rfa; body.degraded = view.degraded; return json(body); } diff --git a/pm-stack/aggregator/src/sources/ready-for-agent.ts b/pm-stack/aggregator/src/sources/ready-for-agent.ts new file mode 100644 index 0000000000..9e3801c230 --- /dev/null +++ b/pm-stack/aggregator/src/sources/ready-for-agent.ts @@ -0,0 +1,228 @@ +// Live ready-for-agent harness source (#1203): the aggregator's first +// reader for the dispatch layer. Until now config.readyForAgent.baseUrl +// fed only a static topology row, derive.ts treated the +// `ready-for-agent` label itself as "implementing", and a labelled +// issue could claim dispatch that never happened. This module queries +// the harness GraphQL API (loopback :6056/graphql — schema verified +// live 2026-11-01: repositories, agentBackendStatuses, +// workItems(repositoryId:)) and answers, per issue, the honest +// dispatch state: the work item's real state, or the explicit +// "not picked up" when the harness has no work item for it. +// +// Pure parsing is split from fetching so the unit tests never need a +// running harness; fetchRfaState caches for 60 s like the health +// probes, so a refreshing dashboard never fans out per hit. + +export interface RfaRepository { + id: string; + projectPath: string; + localPath: string | null; + paused: boolean; + mergePolicy: string | null; + defaultModel: string | null; +} + +export interface RfaBackend { + id: string; + /** Harness readiness, e.g. "READY". */ + kind: string; + reason: string | null; +} + +export interface RfaWorkItem { + repositoryId: string; + issueNumber: number; + state: string; + statusLabel: string | null; + pullRequestNumber: number | null; +} + +export interface RfaState { + repositories: RfaRepository[]; + backends: RfaBackend[]; + workItems: RfaWorkItem[]; +} + +/** The explicit fallback when the harness has no work item for an issue. */ +export const RFA_NOT_PICKED_UP = "not picked up"; + +interface GraphqlResponse { + data?: T; + errors?: { message: string }[]; +} + +function checked(payload: GraphqlResponse, what: string): T { + if (payload.errors?.length) { + throw new Error(`ready-for-agent GraphQL ${what}: ${payload.errors[0].message}`); + } + if (!payload.data) throw new Error(`ready-for-agent GraphQL ${what}: empty response`); + return payload.data; +} + +/** Parse the repositories query payload into the read model. */ +export function parseRfaRepositories(payload: GraphqlResponse<{ repositories: Record[] }>): RfaRepository[] { + const data = checked(payload, "repositories"); + return data.repositories.map((r) => ({ + id: String(r.id), + projectPath: String(r.projectPath), + localPath: typeof r.localPath === "string" ? r.localPath : null, + paused: r.paused === true, + mergePolicy: typeof r.mergePolicy === "string" ? r.mergePolicy : null, + defaultModel: typeof r.defaultModel === "string" ? r.defaultModel : null, + })); +} + +/** Parse the agentBackendStatuses query payload. */ +export function parseRfaBackends(payload: GraphqlResponse<{ agentBackendStatuses: Record[] }>): RfaBackend[] { + const data = checked(payload, "agentBackendStatuses"); + return data.agentBackendStatuses.map((b) => { + const backend = (b.backend ?? {}) as Record; + return { + id: typeof backend.id === "string" ? backend.id : "unknown", + kind: typeof b.kind === "string" ? b.kind : "UNKNOWN", + reason: typeof b.reason === "string" ? b.reason : null, + }; + }); +} + +/** Parse one repository's workItems query payload. */ +export function parseRfaWorkItems( + payload: GraphqlResponse<{ workItems: Record[] }>, + repositoryId: string, +): RfaWorkItem[] { + const data = checked(payload, "workItems"); + return data.workItems.map((w) => ({ + repositoryId, + issueNumber: Number(w.issueNumber), + state: typeof w.state === "string" ? w.state : "UNKNOWN", + statusLabel: typeof w.statusLabel === "string" ? w.statusLabel : null, + pullRequestNumber: typeof w.pullRequestNumber === "number" ? w.pullRequestNumber : null, + })); +} + +/** Assemble the full read model from the three query payloads. */ +export function parseRfaState( + repositoriesPayload: GraphqlResponse<{ repositories: Record[] }>, + backendsPayload: GraphqlResponse<{ agentBackendStatuses: Record[] }>, + workItemPayloads: { repositoryId: string; payload: GraphqlResponse<{ workItems: Record[] }> }[], +): RfaState { + return { + repositories: parseRfaRepositories(repositoriesPayload), + backends: parseRfaBackends(backendsPayload), + workItems: workItemPayloads.flatMap(({ repositoryId, payload }) => parseRfaWorkItems(payload, repositoryId)), + }; +} + +/** + * The dispatch state of one issue: the harness work item's label (or + * raw state) when the harness has picked the issue up, and the + * explicit "not picked up" otherwise — never an inferred "implementing" + * from the label alone. + */ +export function dispatchStateFor(state: RfaState, projectPath: string, issueNumber: number): string { + const repo = state.repositories.find((r) => r.projectPath === projectPath); + if (!repo) return RFA_NOT_PICKED_UP; + const item = state.workItems.find((w) => w.repositoryId === repo.id && w.issueNumber === issueNumber); + if (!item) return RFA_NOT_PICKED_UP; + return item.statusLabel ?? item.state; +} + +/** The /health facet shape for the harness. */ +export interface RfaHealthFacet { + state: "up" | "down" | "fixtures"; + detail: string; + repositories: { projectPath: string; paused: boolean; mergePolicy: string | null; workItems: number }[]; + backends: RfaBackend[]; +} + +export function rfaHealthFacet(state: RfaState): RfaHealthFacet { + const down = state.backends.find((b) => b.kind !== "READY"); + return { + state: down ? "down" : "up", + detail: down + ? `backend ${down.id} is ${down.kind}${down.reason ? `: ${down.reason}` : ""}` + : `${state.repositories.length} repositories, ${state.workItems.length} work items`, + repositories: state.repositories.map((r) => ({ + projectPath: r.projectPath, + paused: r.paused, + mergePolicy: r.mergePolicy, + workItems: state.workItems.filter((w) => w.repositoryId === r.id).length, + })), + backends: state.backends, + }; +} + +export function rfaHealthDown(detail: string): RfaHealthFacet { + return { state: "down", detail, repositories: [], backends: [] }; +} + +/** The minimal fetch shape this source needs — injectable for tests. */ +export type RfaFetch = ( + url: string, + init: { method: string; headers: Record; body: string; signal: AbortSignal }, +) => Promise<{ json(): Promise }>; + +const defaultFetch: RfaFetch = async (url, init) => fetch(url, init); + +const REPOSITORIES_QUERY = + "{ repositories { id projectPath localPath paused mergePolicy defaultModel } }"; +const BACKENDS_QUERY = "{ agentBackendStatuses { kind reason backend { id } } }"; +const workItemsQuery = (repositoryId: string) => + `{ workItems(repositoryId: ${JSON.stringify(repositoryId)}) { issueNumber state statusLabel pullRequestNumber } }`; + +async function gql(fetcher: RfaFetch, graphqlUrl: string, query: string): Promise> { + const res = await fetcher(graphqlUrl, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ query }), + signal: AbortSignal.timeout(2_500), + }); + return (await res.json()) as GraphqlResponse; +} + +export const RFA_CACHE_MS = 60_000; +/** Failures are cached too, for the same bounded window: a stalled + * harness must not add its timeout to every dashboard request that + * reads this facet (Codex P2 on PR #3311). The caller still receives + * the error and reports the facet down. */ +export const RFA_FAILURE_CACHE_MS = 60_000; +let cached: { at: number; state: RfaState } | null = null; +let cachedFailure: { at: number; error: Error } | null = null; + +/** Fetch the harness state live, cached 60 s across callers — failures + * included, so an outage costs one read per window, not one per hit. */ +export async function fetchRfaState( + baseUrl: string, + fetcher: RfaFetch = defaultFetch, + now: number = Date.now(), +): Promise { + if (cached && now - cached.at < RFA_CACHE_MS) return cached.state; + if (cachedFailure && now - cachedFailure.at < RFA_FAILURE_CACHE_MS) throw cachedFailure.error; + try { + const graphqlUrl = `${baseUrl.replace(/\/$/, "")}/graphql`; + const repositoriesPayload = await gql<{ repositories: Record[] }>(fetcher, graphqlUrl, REPOSITORIES_QUERY); + const repositories = parseRfaRepositories(repositoriesPayload); + const backendsPayload = await gql<{ agentBackendStatuses: Record[] }>(fetcher, graphqlUrl, BACKENDS_QUERY); + const workItemPayloads = []; + for (const repo of repositories) { + workItemPayloads.push({ + repositoryId: repo.id, + payload: await gql<{ workItems: Record[] }>(fetcher, graphqlUrl, workItemsQuery(repo.id)), + }); + } + const state = parseRfaState(repositoriesPayload, backendsPayload, workItemPayloads); + cached = { at: now, state }; + cachedFailure = null; + return state; + } catch (err) { + const error = err instanceof Error ? err : new Error(String(err)); + cachedFailure = { at: now, error }; + throw error; + } +} + +/** Test seam: drop the shared cache (success and failure). */ +export function resetRfaCache(): void { + cached = null; + cachedFailure = null; +} diff --git a/pm-stack/aggregator/test/health.test.ts b/pm-stack/aggregator/test/health.test.ts index 2674811773..a9269f63df 100644 --- a/pm-stack/aggregator/test/health.test.ts +++ b/pm-stack/aggregator/test/health.test.ts @@ -16,6 +16,7 @@ import { import { pendingCommentCounts } from "../src/comments.ts"; import type { DashComment } from "../src/model.ts"; import { renderHealth } from "../src/render.ts"; +import type { RfaState } from "../src/sources/ready-for-agent.ts"; // #1147/#1137: health assembly — service probes (injectable fetcher, // 60 s cache), feed section ages, job runs, the render registry, and @@ -78,6 +79,26 @@ function fakeFetcher(handler: (url: string) => { status: number } | Error) { return { fetcher, calls }; } +/** #1203: an injectable harness read so buildHealth never depends on a + * live :6056 in tests. Mirrors the ready-for-agent source's read model. */ +const RFA_STATE: RfaState = { + repositories: [ + { + id: "repo-1", + projectPath: "developing-today/code", + localPath: "/home/user/pm-stack/ready-for-agent/repos/code", + paused: false, + mergePolicy: "OFF", + defaultModel: "opencode-go/kimi-k3.1-pro", + }, + ], + backends: [{ id: "opencode", kind: "READY", reason: null }], + workItems: [ + { repositoryId: "repo-1", issueNumber: 762, state: "RUNNING", statusLabel: "In progress", pullRequestNumber: null }, + ], +}; +const rfaUp = async (): Promise => RFA_STATE; + const allUp = () => ({ status: 200 }); function service(view: Awaited>, id: string) { @@ -120,7 +141,7 @@ describe("buildHealth probes", () => { const { fetcher, calls } = fakeFetcher((url) => url.startsWith("http://127.0.0.1:8484") ? { status: 302 } : allUp(), ); - const view = await buildHealth(inputs(), { fetcher, cache: createProbeCache(), now: NOW }); + const view = await buildHealth(inputs(), { fetcher, cache: createProbeCache(), now: NOW, rfaState: rfaUp }); expect(service(view, "kaneo").state).toBe("up"); expect(service(view, "grist").state).toBe("up"); expect(service(view, "grist").statusCode).toBe(302); @@ -137,6 +158,60 @@ describe("buildHealth probes", () => { expect(view.degraded).toBe(false); }); + test("the ready-for-agent facet is carried by the view and rendered on /health (#1203)", async () => { + const { fetcher } = fakeFetcher(allUp); + const view = await buildHealth(inputs(), { fetcher, cache: createProbeCache(), now: NOW, rfaState: rfaUp }); + expect(view.rfa.state).toBe("up"); + expect(view.rfa.repositories).toEqual([ + { projectPath: "developing-today/code", paused: false, mergePolicy: "OFF", workItems: 1 }, + ]); + expect(view.rfa.backends).toEqual([{ id: "opencode", kind: "READY", reason: null }]); + expect(view.degraded).toBe(false); + const html = renderHealth(view, {} as Parameters[1]); + expect(html).toContain('id="ready-for-agent"'); + expect(html).toContain("developing-today/code"); + expect(html).toContain("Work items"); + // Settings, work-item counts, and backend readiness all reach the page. + expect(html).toContain("opencode"); + }); + + test("a failed harness read is reported down and degrades health (#1203)", async () => { + const { fetcher } = fakeFetcher(allUp); + const view = await buildHealth(inputs(), { + fetcher, + cache: createProbeCache(), + now: NOW, + rfaState: async () => { + throw new Error("connect ECONNREFUSED 127.0.0.1:6056"); + }, + }); + expect(view.rfa.state).toBe("down"); + expect(view.rfa.detail).toContain("ECONNREFUSED"); + expect(view.rfa.repositories).toEqual([]); + // The new facet is not decoration: a harness that cannot be read + // is part of the aggregate degraded state. + expect(view.degraded).toBe(true); + const html = renderHealth(view, {} as Parameters[1]); + expect(html).toContain("ECONNREFUSED"); + expect(html).toContain("could not be read"); + }); + + test("a harness backend that is not READY reports the facet down", async () => { + const { fetcher } = fakeFetcher(allUp); + const view = await buildHealth(inputs(), { + fetcher, + cache: createProbeCache(), + now: NOW, + rfaState: async () => ({ + ...RFA_STATE, + backends: [{ id: "opencode", kind: "UNAVAILABLE", reason: "opencode not found" }], + }), + }); + expect(view.rfa.state).toBe("down"); + expect(view.rfa.detail).toContain("opencode not found"); + expect(view.degraded).toBe(true); + }); + test("a throwing probe renders down with its error; the inferred service says unknown, not down", async () => { const { fetcher } = fakeFetcher((url) => url.startsWith("http://127.0.0.1:5173") ? new Error("connect ECONNREFUSED") : allUp(), @@ -427,6 +502,7 @@ describe("health page + extended /api/health (fixtures boot)", () => { feed: { generatedAt: unknown; sections: unknown[] }; pages: { route: string; lastRenderedAt: unknown }[]; jobs: { orchestration: { state: string } }; + rfa: { state: string; detail: string; repositories: unknown[]; backends: unknown[] }; }; expect(body.status).toBe("ok"); expect(body.source.board).toBe("fixtures"); @@ -436,6 +512,11 @@ describe("health page + extended /api/health (fixtures boot)", () => { expect(Array.isArray(body.feed.sections)).toBe(true); expect(body.pages.some((p) => p.route === "/health")).toBe(true); expect(body.jobs.orchestration.state).toBeDefined(); + // #1203: the harness facet reaches the machine surface, not only + // the rendered page — fixtures mode says so honestly. + expect(body.rfa.state).toBe("fixtures"); + expect(Array.isArray(body.rfa.repositories)).toBe(true); + expect(Array.isArray(body.rfa.backends)).toBe(true); }); test("/pages lists the health page from the manifest", async () => { diff --git a/pm-stack/aggregator/test/ready-for-agent.test.ts b/pm-stack/aggregator/test/ready-for-agent.test.ts new file mode 100644 index 0000000000..9b645e29f3 --- /dev/null +++ b/pm-stack/aggregator/test/ready-for-agent.test.ts @@ -0,0 +1,157 @@ +import { describe, expect, test } from "bun:test"; +import { + dispatchStateFor, + fetchRfaState, + parseRfaState, + resetRfaCache, + rfaHealthFacet, + RFA_NOT_PICKED_UP, + type RfaFetch, +} from "../src/sources/ready-for-agent.ts"; + +// #1203: the aggregator's ready-for-agent source — dispatch-state +// parsing, the explicit "not picked up" fallback, and the /health +// facet's up/down rule. Payloads mirror the live harness schema +// (verified 2026-11-01 against :6056/graphql introspection). + +const repositoriesPayload = { + data: { + repositories: [ + { + id: "repo-1", + projectPath: "developing-today/code", + localPath: "/home/user/pm-stack/ready-for-agent/repos/code", + paused: false, + mergePolicy: "OFF", + defaultModel: "opencode-go/kimi-k3.1-pro", + }, + { + id: "repo-2", + projectPath: "dezren39/nix", + localPath: null, + paused: true, + mergePolicy: null, + defaultModel: null, + }, + ], + }, +}; + +const backendsPayload = { + data: { agentBackendStatuses: [{ kind: "READY", reason: null, backend: { id: "opencode" } }] }, +}; + +const workItemsPayload = { + data: { + workItems: [{ issueNumber: 762, state: "COMPLETE", statusLabel: "Complete", pullRequestNumber: 763 }], + }, +}; + +function state() { + return parseRfaState(repositoriesPayload, backendsPayload, [{ repositoryId: "repo-1", payload: workItemsPayload }]); +} + +describe("ready-for-agent source parsing", () => { + test("parses repositories, backends, and work items", () => { + const s = state(); + expect(s.repositories).toHaveLength(2); + expect(s.repositories[0].mergePolicy).toBe("OFF"); + expect(s.repositories[1].paused).toBe(true); + expect(s.backends).toEqual([{ id: "opencode", kind: "READY", reason: null }]); + expect(s.workItems[0]).toMatchObject({ repositoryId: "repo-1", issueNumber: 762, pullRequestNumber: 763 }); + }); + + test("GraphQL errors throw instead of parsing as empty", () => { + expect(() => parseRfaState({ errors: [{ message: "boom" }] }, backendsPayload, [])).toThrow("boom"); + }); +}); + +describe("dispatchStateFor", () => { + test("returns the work item's real state for a picked-up issue", () => { + expect(dispatchStateFor(state(), "developing-today/code", 762)).toBe("Complete"); + }); + + test("returns explicit 'not picked up' for a labelled issue with no work item", () => { + expect(dispatchStateFor(state(), "developing-today/code", 1203)).toBe(RFA_NOT_PICKED_UP); + }); + + test("returns 'not picked up' for an unregistered repository", () => { + expect(dispatchStateFor(state(), "developing-today/opencode", 1)).toBe(RFA_NOT_PICKED_UP); + }); +}); + +describe("rfaHealthFacet", () => { + test("up when every backend is READY, with per-repo work item counts", () => { + const facet = rfaHealthFacet(state()); + expect(facet.state).toBe("up"); + expect(facet.repositories[0]).toMatchObject({ projectPath: "developing-today/code", workItems: 1 }); + expect(facet.repositories[1].workItems).toBe(0); + }); + + test("down when a backend is not READY, naming the reason", () => { + const s = parseRfaState(repositoriesPayload, { + data: { agentBackendStatuses: [{ kind: "UNAVAILABLE", reason: "opencode not found", backend: { id: "opencode" } }] }, + }, []); + const facet = rfaHealthFacet(s); + expect(facet.state).toBe("down"); + expect(facet.detail).toContain("opencode not found"); + }); +}); + +describe("fetchRfaState", () => { + test("queries repositories, backends, and per-repo work items over GraphQL", async () => { + resetRfaCache(); + const queries: string[] = []; + const fetcher: RfaFetch = async (_url, init) => { + const { query } = JSON.parse(init.body) as { query: string }; + queries.push(query); + const payload = query.includes("agentBackendStatuses") + ? backendsPayload + : query.includes("workItems") + ? workItemsPayload + : repositoriesPayload; + return { json: async () => payload }; + }; + const s = await fetchRfaState("http://127.0.0.1:6056", fetcher, 1_000); + expect(queries.some((q) => q.includes("repositories"))).toBe(true); + expect(queries.some((q) => q.includes("agentBackendStatuses"))).toBe(true); + // One workItems query per registered repository. + expect(queries.filter((q) => q.includes("workItems"))).toHaveLength(2); + expect(s.workItems).toHaveLength(2); + // Cached: a second call inside the window sends no new queries. + const again = await fetchRfaState("http://127.0.0.1:6056", fetcher, 2_000); + expect(again).toBe(s); + expect(queries).toHaveLength(4); + resetRfaCache(); + }); + + test("a failed read is cached for the window, then retried (no per-hit retry storm)", async () => { + resetRfaCache(); + let calls = 0; + const fetcher: RfaFetch = async () => { + calls++; + throw new Error("harness stalled"); + }; + // First failure hits the network once. + await expect(fetchRfaState("http://127.0.0.1:6056", fetcher, 1_000)).rejects.toThrow("harness stalled"); + expect(calls).toBe(1); + // Inside the window the cached failure is re-thrown without a new read. + await expect(fetchRfaState("http://127.0.0.1:6056", fetcher, 2_000)).rejects.toThrow("harness stalled"); + expect(calls).toBe(1); + // Past the window the source retries — and a success clears the failure. + const ok: RfaFetch = async (_url, init) => { + calls++; + const { query } = JSON.parse(init.body) as { query: string }; + const payload = query.includes("agentBackendStatuses") + ? backendsPayload + : query.includes("workItems") + ? workItemsPayload + : repositoriesPayload; + return { json: async () => payload }; + }; + const s = await fetchRfaState("http://127.0.0.1:6056", ok, 1_000 + 60_000); + expect(s.repositories).toHaveLength(2); + expect(calls).toBe(5); + resetRfaCache(); + }); +}); diff --git a/pm-stack/ready-for-agent/apply-config.sh b/pm-stack/ready-for-agent/apply-config.sh new file mode 100755 index 0000000000..81ccfd6693 --- /dev/null +++ b/pm-stack/ready-for-agent/apply-config.sh @@ -0,0 +1,153 @@ +#!/usr/bin/env bash +# Apply the declarative ready-for-agent configuration (config.json, +# #1203) to the running harness, idempotently: +# +# 1. register every configured repository clone that the harness +# does not know yet (mutation addLocalRepository), +# 2. apply the configured settings (mergePolicy, defaultModel, +# includeAllIssueAuthors) with updateRepositorySettings — a +# full-object input, so the current settings are read first and +# every field the config does not name is carried over unchanged, +# 3. pause/unpause each repository to match the config. +# +# A repository whose live settings already match the config receives +# NO mutation — running this script twice is a no-op the second time. +# +# ./apply-config.sh apply config.json next to this script +# DRY_RUN=1 ./apply-config.sh print the mutations it would send +# +# Overrides: RFA_CONFIG (config path), RFA_GRAPHQL_URL (endpoint), +# RFA_REPOS_DIR (clone root, default ./repos next to the config). +set -euo pipefail + +cd "$(dirname "$0")" +CONFIG="${RFA_CONFIG:-$PWD/config.json}" +GRAPHQL_URL="${RFA_GRAPHQL_URL:-}" +REPOS_DIR="${RFA_REPOS_DIR:-$PWD/repos}" +export CONFIG GRAPHQL_URL REPOS_DIR +export DRY_RUN="${DRY_RUN:-}" + +python3 - <<'PYEOF' +import json, os, sys, urllib.request + +config_path = os.environ["CONFIG"] +with open(config_path) as f: + config = json.load(f) +url = os.environ.get("GRAPHQL_URL") or config.get("graphqlUrl") or "http://127.0.0.1:6056/graphql" +repos_dir = os.environ["REPOS_DIR"] +dry_run = bool(os.environ.get("DRY_RUN")) + +def gql(query, variables=None): + body = {"query": query} + if variables is not None: + body["variables"] = variables + req = urllib.request.Request( + url, + data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(req, timeout=15) as res: + payload = json.load(res) + if payload.get("errors"): + raise SystemExit(f"GraphQL error: {json.dumps(payload['errors'])[:400]}") + return payload["data"] + +REPO_FIELDS = ( + "id projectPath localPath paused mergePolicy defaultModel " + "selectedAgentBackend defaultThinkingLevel reviewModel " + "reviewThinkingLevel includeAllIssueAuthors " + "waitForReadyForReviewChecks automaticCiRepair forge forgeHost " + "issueTracker linearProjectId linearProjectName" +) + +def list_repositories(): + return gql("{ repositories { %s } }" % REPO_FIELDS)["repositories"] + +# Config-owned fields: config key -> settings-input key. +OWNED = [ + ("mergePolicy", "mergePolicy"), + ("defaultModel", "defaultModel"), + ("includeAllIssueAuthors", "includeAllIssueAuthors"), + ("selectedAgentBackend", "selectedAgentBackend"), +] + +by_path = {r["projectPath"]: r for r in list_repositories()} + +for entry in config["repositories"]: + project = entry["projectPath"] + repo = by_path.get(project) + if repo is None: + local_path = os.path.join(repos_dir, entry["localDir"]) + if dry_run: + print(f"DRY-RUN would register {project}: addLocalRepository(path={local_path})") + continue + if not os.path.isdir(local_path): + print( + f"skip {project}: clone missing at {local_path} " + "(run ./install.sh clone first)", + file=sys.stderr, + ) + continue + gql( + "mutation($path: String!) { addLocalRepository(path: $path) { id } }", + {"path": local_path}, + ) + by_path = {r["projectPath"]: r for r in list_repositories()} + repo = by_path.get(project) + if repo is None: + raise SystemExit(f"addLocalRepository did not register {project}") + print(f"registered {project} ({repo['id']})") + + # Settings: full-object input built from the live settings, with + # only the config-owned fields overridden. + settings = { + "repositoryId": repo["id"], + "forge": repo.get("forge"), + "forgeHost": repo.get("forgeHost"), + "projectPath": repo.get("projectPath"), + "paused": repo.get("paused"), + "selectedAgentBackend": repo.get("selectedAgentBackend"), + "defaultModel": repo.get("defaultModel"), + "defaultThinkingLevel": repo.get("defaultThinkingLevel"), + "reviewModel": repo.get("reviewModel"), + "reviewThinkingLevel": repo.get("reviewThinkingLevel"), + "mergePolicy": repo.get("mergePolicy"), + "includeAllIssueAuthors": repo.get("includeAllIssueAuthors"), + "waitForReadyForReviewChecks": repo.get("waitForReadyForReviewChecks"), + "automaticCiRepair": repo.get("automaticCiRepair"), + "issueTracker": repo.get("issueTracker"), + "linearProjectId": repo.get("linearProjectId"), + "linearProjectName": repo.get("linearProjectName"), + } + drift = [] + for config_key, input_key in OWNED: + if config_key in entry and entry[config_key] != settings[input_key]: + settings[input_key] = entry[config_key] + drift.append(input_key) + if drift: + if dry_run: + print(f"DRY-RUN would update {project} settings: {', '.join(drift)}") + else: + gql( + "mutation($input: UpdateRepositorySettingsInput!) " + "{ updateRepositorySettings(input: $input) { id } }", + {"input": settings}, + ) + print(f"updated {project} settings: {', '.join(drift)}") + else: + print(f"{project} settings already match config") + + want_paused = bool(entry.get("paused", False)) + if want_paused != bool(repo.get("paused")): + mutation = "pauseRepository" if want_paused else "unpauseRepository" + if dry_run: + print(f"DRY-RUN would {mutation} {project}") + else: + gql( + "mutation($id: ID!) { %s(repositoryId: $id) { id } }" % mutation, + {"id": repo["id"]}, + ) + print(f"{mutation} applied to {project}") + +print("ready-for-agent config applied" + (" (dry run)" if dry_run else "")) +PYEOF diff --git a/pm-stack/ready-for-agent/config.json b/pm-stack/ready-for-agent/config.json new file mode 100644 index 0000000000..21a37de557 --- /dev/null +++ b/pm-stack/ready-for-agent/config.json @@ -0,0 +1 @@ +{"comment":"Declarative ready-for-agent configuration (#1203). install.sh clones every repository listed here into ./repos/; apply-config.sh registers each clone with the harness and applies these settings idempotently via its GraphQL API. Fleet posture: human merge always (mergePolicy OFF) — never enable auto-merge here.","graphqlUrl":"http://127.0.0.1:6056/graphql","repositories":[{"cloneUrl":"https://github.com/developing-today/code.git","defaultModel":"opencode-go/kimi-k3.1-pro","includeAllIssueAuthors":true,"localDir":"code","mergePolicy":"OFF","paused":false,"projectPath":"developing-today/code"},{"cloneUrl":"https://github.com/developing-today/opencode.git","defaultModel":"opencode-go/kimi-k3.1-pro","includeAllIssueAuthors":true,"localDir":"opencode","mergePolicy":"OFF","paused":false,"projectPath":"developing-today/opencode"},{"cloneUrl":"https://github.com/developing-today/openchamber.git","defaultModel":"opencode-go/kimi-k3.1-pro","includeAllIssueAuthors":true,"localDir":"openchamber","mergePolicy":"OFF","paused":false,"projectPath":"developing-today/openchamber"},{"cloneUrl":"https://github.com/dezren39/nix.git","defaultModel":"opencode-go/kimi-k3.1-pro","includeAllIssueAuthors":true,"localDir":"nix","mergePolicy":"OFF","paused":false,"projectPath":"dezren39/nix"}],"version":1} \ No newline at end of file diff --git a/pm-stack/ready-for-agent/install.sh b/pm-stack/ready-for-agent/install.sh index 87038e0d52..983830ce44 100644 --- a/pm-stack/ready-for-agent/install.sh +++ b/pm-stack/ready-for-agent/install.sh @@ -3,9 +3,11 @@ # on this host. # # ./install.sh install pinned package + unit, restart on -# change (or start when inactive), wait for the UI -# ./install.sh clone additionally clone (or fetch) the -# repositories the harness serves into +# change (or start when inactive), wait for the +# UI, apply config.json (./apply-config.sh, +# #1203), print status +# ./install.sh clone additionally clone (or fetch) every +# repository config.json serves into # ./repos/ # # Registration note (learned 2026-10-24, first deployment): register @@ -74,15 +76,25 @@ fi # Only with the explicit `clone` argument — cloning is a one-time, # network-heavy step. if [[ ${1:-} == clone ]]; then - mkdir -p "${DEPLOY_DIR}/repos" - if [[ -d ${DEPLOY_DIR}/repos/code ]]; then - git -C "${DEPLOY_DIR}/repos/code" fetch --all --prune - echo "fetched code" - else - GIT_TERMINAL_PROMPT=0 git clone \ - https://github.com/developing-today/code.git "${DEPLOY_DIR}/repos/code" - echo "cloned code" - fi + mkdir -p "$DEPLOY_DIR/repos" + # Every repository the declarative config serves (#1203) — not + # only developing-today/code. Rows are localDircloneUrl. + while IFS=$'\t' read -r local_dir clone_url; do + [[ -n $local_dir ]] || continue + if [[ -d $DEPLOY_DIR/repos/$local_dir ]]; then + git -C "$DEPLOY_DIR/repos/$local_dir" fetch --all --prune + echo "fetched $local_dir" + else + GIT_TERMINAL_PROMPT=0 git clone "$clone_url" "$DEPLOY_DIR/repos/$local_dir" + echo "cloned $local_dir" + fi + done < <(python3 -c ' +import json +with open("config.json") as f: + cfg = json.load(f) +for repo in cfg["repositories"]: + print(repo["localDir"] + "\t" + repo["cloneUrl"]) +') fi # 3. systemd user unit. @@ -174,6 +186,10 @@ for ((i = 1; i <= 30; i++)); do if [[ ${service_action} == restarted || ${service_action} == started ]]; then rm -f "${PENDING_RESTART_FILE}" fi + # Apply the declarative configuration (#1203) once the new process is + # verified serving: register the clones and converge the harness + # settings on config.json, idempotently. + ./apply-config.sh systemctl --user --no-pager status ready-for-agent.service | head -5 exit 0 fi diff --git a/pm-stack/ready-for-agent/test-apply-config.sh b/pm-stack/ready-for-agent/test-apply-config.sh new file mode 100755 index 0000000000..b6349a4ba3 --- /dev/null +++ b/pm-stack/ready-for-agent/test-apply-config.sh @@ -0,0 +1,122 @@ +#!/usr/bin/env bash +# Stubbed-GraphQL test for apply-config.sh (#1203): an in-memory fake +# harness records every mutation; the first apply must register + +# configure the repo, the second apply must send NO mutations +# (idempotence), and DRY_RUN must send nothing at all. +set -euo pipefail + +cd "$(dirname "$0")" +WORK="$(mktemp -d)" +trap 'rm -rf "$WORK"; kill "${STUB_PID:-}" 2>/dev/null || true' EXIT + +mkdir -p "$WORK/repos/code" +cat > "$WORK/config.json" <<'JSON' +{ + "version": 1, + "graphqlUrl": "http://127.0.0.1:16056/graphql", + "repositories": [ + { + "projectPath": "developing-today/code", + "cloneUrl": "https://github.com/developing-today/code.git", + "localDir": "code", + "mergePolicy": "OFF", + "defaultModel": "opencode-go/kimi-k3.1-pro", + "includeAllIssueAuthors": true, + "paused": false + } + ] +} +JSON + +STUB_LOG="$WORK/mutations.log" STUB_PORT=16056 python3 - <<'PYEOF' & +import json, os +from http.server import BaseHTTPRequestHandler, HTTPServer + +LOG = os.environ["STUB_LOG"] +state = {"repositories": []} + +class Handler(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_POST(self): + body = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) + query = body.get("query", "") + variables = body.get("variables") or {} + data = {} + if "addLocalRepository" in query: + with open(LOG, "a") as f: + f.write("addLocalRepository\n") + state["repositories"] = [{ + "id": "repo-stub-1", + "projectPath": "developing-today/code", + "localPath": variables["path"], + "paused": True, + "mergePolicy": None, + "defaultModel": None, + "selectedAgentBackend": None, + "defaultThinkingLevel": None, + "reviewModel": None, + "reviewThinkingLevel": None, + "includeAllIssueAuthors": False, + "waitForReadyForReviewChecks": None, + "automaticCiRepair": None, + "forge": "github", + "forgeHost": "github.com", + "issueTracker": "github", + "linearProjectId": None, + "linearProjectName": None, + }] + data = {"addLocalRepository": {"id": "repo-stub-1"}} + elif "updateRepositorySettings" in query: + with open(LOG, "a") as f: + f.write("updateRepositorySettings\n") + incoming = variables["input"] + repo = state["repositories"][0] + for key, value in incoming.items(): + if key != "repositoryId": + repo[key] = value + data = {"updateRepositorySettings": {"id": repo["id"]}} + elif "unpauseRepository" in query or "pauseRepository" in query: + name = "unpauseRepository" if "unpauseRepository" in query else "pauseRepository" + with open(LOG, "a") as f: + f.write(name + "\n") + state["repositories"][0]["paused"] = name == "pauseRepository" + data = {name: {"id": "repo-stub-1"}} + elif "repositories" in query: + data = {"repositories": state["repositories"]} + payload = json.dumps({"data": data}).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(payload))) + self.end_headers() + self.wfile.write(payload) + +HTTPServer(("127.0.0.1", int(os.environ["STUB_PORT"])), Handler).serve_forever() +PYEOF +STUB_PID=$! +sleep 1 + +export RFA_CONFIG="$WORK/config.json" +export RFA_REPOS_DIR="$WORK/repos" +export RFA_GRAPHQL_URL="http://127.0.0.1:16056/graphql" + +: > "$WORK/mutations.log" +DRY_RUN=1 ./apply-config.sh > "$WORK/dry-run.out" +grep -q "would register" "$WORK/dry-run.out" +[[ ! -s "$WORK/mutations.log" ]] || { echo "FAIL: dry run mutated the harness"; exit 1; } +echo "ok: dry run plans registration and mutates nothing" + +./apply-config.sh > "$WORK/first.out" +grep -q "addLocalRepository" "$WORK/mutations.log" +grep -q "updateRepositorySettings" "$WORK/mutations.log" +grep -q "unpauseRepository" "$WORK/mutations.log" +echo "ok: first apply registers, configures, unpauses" + +: > "$WORK/mutations.log" +./apply-config.sh > "$WORK/second.out" +grep -q "already match config" "$WORK/second.out" +[[ ! -s "$WORK/mutations.log" ]] || { echo "FAIL: second apply was not a no-op:"; cat "$WORK/mutations.log"; exit 1; } +echo "ok: second apply is a no-op (idempotent)" + +echo "apply-config.test: PASS"