From 574c45bd966b382dbf35de5210ee3cabd7d26403 Mon Sep 17 00:00:00 2001 From: lex00 <121451605+lex00@users.noreply.github.com> Date: Wed, 7 Oct 2026 23:44:59 -0600 Subject: [PATCH] test(workspace): run chant's reader conformance suite over behold's workspace reader (#468) Every workspace read (ls, graph --member, status) now goes through one module, src/workspace-reader.ts. A read is one chant call of the contract command, over a transport that never hands the reader the workspace's path. The document comes back as chant printed it, and any contract but 1 is refused whole. src/workspace-reader-conformance.test.ts runs @intentius/chant/workspace/conformance against that module in npm test, so in CI. Each read also runs behold's own parser over the document and fails when behold couldn't use it. A second test fails when any other module in src/ names a read-contract command to chant. No chant bump: the suite and these three commands are in 0.95.0. Co-Authored-By: Claude Opus 5.5 (1M context) --- AGENTS.md | 8 ++ src/workspace-gates.ts | 29 +++-- src/workspace-reader-conformance.test.ts | 68 ++++++++++ src/workspace-reader.ts | 151 +++++++++++++++++++++++ src/workspace.test.ts | 3 +- src/workspace.ts | 78 ++++++------ 6 files changed, 279 insertions(+), 58 deletions(-) create mode 100644 src/workspace-reader-conformance.test.ts create mode 100644 src/workspace-reader.ts diff --git a/AGENTS.md b/AGENTS.md index 1b3a9b61..bce8d3fa 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -31,6 +31,14 @@ draws nothing. `.behold.json`'s `members` are ignored beside a declaration; Several directories on the command line (`behold serve a b c`) stay the loose view behold composes itself. +Every workspace read goes through one module, `src/workspace-reader.ts`: one +chant call per read, the document handed back as chant printed it, any +contract but 1 refused. chant's reader conformance suite +(`@intentius/chant/workspace/conformance`) runs against that module in `npm +test` (`src/workspace-reader-conformance.test.ts`, #468), so a new workspace +read is added to the reader and to the suite's `commands`, never shelled from +somewhere else. + ## Getting a server ```sh diff --git a/src/workspace-gates.ts b/src/workspace-gates.ts index 3e9798b5..6afec026 100644 --- a/src/workspace-gates.ts +++ b/src/workspace-gates.ts @@ -15,8 +15,8 @@ * looking (#476). */ import { resolve } from "node:path"; -import { runChantRaw } from "./chant.ts"; -import { contractRefusal, type Workspace, type WorkspaceRefusal } from "./workspace.ts"; +import type { Workspace } from "./workspace.ts"; +import { contractRefusal, rootReader, WorkspaceReadError, type WorkspaceDocument, type WorkspaceReader, type WorkspaceRefusal } from "./workspace-reader.ts"; export const STATUS_SCHEMA_ID = "https://intentius.io/chant/schemas/workspace/status/v1/status.schema.json"; @@ -73,6 +73,11 @@ export function parseWorkspaceStatus(text: string, root: string): GatesRead { return { ok: false, refusal: { error: "chant workspace status printed something that is not JSON.", code: "workspace-status", remedy: "Run `chant workspace status --json` in the workspace root to see what it says." } }; } if (!isRecord(doc)) return { ok: false, refusal: { error: "chant workspace status printed JSON that is not an object.", code: "workspace-status", remedy: "Run `chant workspace status --json` in the workspace root." } }; + return gatesFromStatus(doc, root); +} + +/** The waiting gates in a status document the reader returned. */ +export function gatesFromStatus(doc: WorkspaceDocument, root: string): GatesRead { const contract = contractRefusal(doc, "status"); if (contract) return { ok: false, refusal: contract }; if (isRecord(doc.error)) { @@ -118,20 +123,14 @@ export function parseWorkspaceStatus(text: string, root: string): GatesRead { return { ok: true, env: String(doc.env ?? ""), gates }; } -/** Ask the workspace's chant for its status in `env`. */ -export async function readWorkspaceGates(ws: Workspace, env: string): Promise { - const run = await runChantRaw(["workspace", "status", env, "--json"], ws.root); - if (!run.stdout.trim()) { - return { - ok: false, - refusal: { - error: `chant workspace status ${env} failed in ${ws.root} (exit ${run.code}): ${run.stderr.trim().split("\n").slice(-3).join(" ")}`, - code: "workspace-status", - remedy: "Run `chant workspace status ` in the workspace root.", - }, - }; +/** Ask the workspace's chant for its status in `env`, through the reader (#468). */ +export async function readWorkspaceGates(ws: Workspace, env: string, reader: WorkspaceReader = rootReader(ws.root)): Promise { + try { + return gatesFromStatus(await reader.read("status", [env]), ws.root); + } catch (e) { + if (e instanceof WorkspaceReadError) return { ok: false, refusal: e.refusal }; + throw e; } - return parseWorkspaceStatus(run.stdout, ws.root); } /** An env name chant can take as a positional argument: never a flag. */ diff --git a/src/workspace-reader-conformance.test.ts b/src/workspace-reader-conformance.test.ts new file mode 100644 index 00000000..bb510141 --- /dev/null +++ b/src/workspace-reader-conformance.test.ts @@ -0,0 +1,68 @@ +// #468: chant's reader conformance suite (ws-052) over behold's workspace +// reader, src/workspace-reader.ts, the one module every workspace read goes +// through. +// +// The suite generates a workspace from the fixture the installed +// @intentius/chant ships, builds the reader over a recording transport (never +// the path), and for each command checks that the read was exactly one chant +// call of the contract command with its JSON flag, that the document returned +// is the one chant printed, that it validates against chant's schema at this +// contract version, and that no file in the workspace changed. +// +// The reader returns chant's document unchanged, so the suite can compare it. +// What behold makes of that document is checked here too: each read also runs +// the parser behold uses on it, and a document behold could not use fails the +// read, as hud's adapter does (arugula-salad/hud reader-conformance.test.ts). +import { describe, expect, it } from "vitest"; +import { describeWorkspaceReaderConformance, type ChantTransport, type ReadContractCommand } from "@intentius/chant/workspace/conformance/vitest"; +import { readFileSync, readdirSync } from "node:fs"; +import { join } from "node:path"; +import { workspaceFromLs, memberIrFromGraphDocument } from "./workspace.ts"; +import { gatesFromStatus } from "./workspace-gates.ts"; +import { BEHOLD_READS, workspaceReader, type WorkspaceDocument, type WorkspaceReadCommand } from "./workspace-reader.ts"; + +/** The suite fixture's chant member, the one `graph --member` reads. */ +const FIXTURE_MEMBER = "delivery"; + +/** Run behold's own parser for `command` over the document, and throw when it can't use it. */ +function use(command: WorkspaceReadCommand, doc: WorkspaceDocument): void { + if (command === "ls") { + const read = workspaceFromLs(doc, "/conformance"); + if (!read.ok) throw new Error(`behold could not use the ls document: ${read.refusal.error}`); + } else if (command === "graph") { + memberIrFromGraphDocument(doc, FIXTURE_MEMBER); + } else if (command === "status") { + const read = gatesFromStatus(doc, "/conformance"); + if (!read.ok) throw new Error(`behold could not use the status document: ${read.refusal.error}`); + } +} + +describeWorkspaceReaderConformance({ + name: "behold", + commands: BEHOLD_READS.filter((c) => c !== "graph --intent") as ReadContractCommand[], + reader: (chant: ChantTransport) => { + const reader = workspaceReader({ run: (argv) => chant.run(argv) }); + return { + async read(command: ReadContractCommand, args: string[]) { + const doc = await reader.read(command as WorkspaceReadCommand, args); + use(command as WorkspaceReadCommand, doc); + return doc; + }, + }; + }, +}); + +// The suite holds what goes through the reader. This holds the rest of src/ +// to going through it: no other module names a workspace command to chant. +describe("every workspace read goes through the reader (#468)", () => { + it("no module but the reader runs a read-contract command (doctor --fix runs check, a write's own validation)", () => { + const src = join(import.meta.dirname, "."); + const offenders: string[] = []; + for (const f of readdirSync(src)) { + if (!f.endsWith(".ts") || f.endsWith(".test.ts") || f === "workspace-reader.ts") continue; + const text = readFileSync(join(src, f), "utf8"); + if (/\[\s*"workspace"\s*,\s*"(ls|graph|status|records|runs|wip)"/.test(text)) offenders.push(f); + } + expect(offenders).toEqual([]); + }); +}); diff --git a/src/workspace-reader.ts b/src/workspace-reader.ts new file mode 100644 index 00000000..3ceee357 --- /dev/null +++ b/src/workspace-reader.ts @@ -0,0 +1,151 @@ +/** + * #468: the one module behold reads a declared workspace through. + * + * ws-052 says a reader reads only through chant's read contract: it runs a + * contract command, takes the document chant prints, and computes no join + * chant can do itself. Every workspace read behold makes (`ls`, `graph + * --member`, `status`, `graph --intent`) goes through {@link workspaceReader}, + * and chant's reader conformance suite (`@intentius/chant/workspace/ + * conformance`) runs against this same function in behold's tests + * (src/workspace-reader-conformance.test.ts). The suite checks that each read + * is exactly one chant call of the contract command, that the document handed + * back is the one chant printed, that it validates against chant's schema, and + * that no file in the workspace changed. + * + * The reader is built over a {@link ChantTransport}, so it never learns the + * workspace's path: the transport is its only way in. In behold that + * transport is {@link rootTransport}, which runs the workspace root's own chant + * through `runChantRaw`, so a read takes a slot in behold's read budget and is + * cancelled when the page that asked for it goes away (src/read-scheduler.ts). + * + * A document written to any contract but {@link WORKSPACE_CONTRACT} is + * refused whole, as {@link WorkspaceReadError}: within a version chant only + * adds fields, and a new version can change what one means. + */ +import { runChantRaw } from "./chant.ts"; + +/** The read contract version behold reads (chant's `reference/workspace-read-contract`). */ +export const WORKSPACE_CONTRACT = 1; +/** The first chant that writes contract 1. An older one has no `workspace` command at all. */ +export const WORKSPACE_CHANT_FLOOR = "0.81.0"; + +/** The read-contract commands behold reads, named the way chant's conformance suite names them. */ +export const BEHOLD_READS = ["ls", "graph", "status", "graph --intent"] as const; +export type WorkspaceReadCommand = (typeof BEHOLD_READS)[number]; + +/** + * The flag each command takes to print its document. `graph` always prints + * JSON (the contract's table says "always"), so it gets none, as it had none + * before this module. + */ +export const JSON_FLAGS: Record = { + ls: ["--json"], + graph: [], + status: ["--json"], + "graph --intent": ["--json"], +}; + +/** Why behold will not use a workspace document, in the #193 refusal shape. */ +export interface WorkspaceRefusal { + error: string; + code: string; + remedy: string; +} + +/** A read behold refuses: chant printed nothing, something that isn't a JSON object, or another contract. */ +export class WorkspaceReadError extends Error { + constructor(readonly refusal: WorkspaceRefusal) { + super(`${refusal.error} ${refusal.remedy}`); + } +} + +/** One chant run, as the conformance suite's transport reports it. */ +export interface TransportRun { + status: number | null; + stdout: string; + stderr: string; +} + +/** How the reader reaches chant. Shaped like the conformance suite's `ChantTransport`. */ +export interface ChantTransport { + run(argv: string[]): Promise; +} + +export type WorkspaceDocument = Record; + +export interface WorkspaceReader { + /** Run one contract command with `args`, and return the document chant printed, unchanged. */ + read(command: WorkspaceReadCommand, args: string[]): Promise; +} + +const isRecord = (v: unknown): v is Record => v !== null && typeof v === "object" && !Array.isArray(v); + +/** The argv one read runs: `workspace `. */ +export function readArgv(command: WorkspaceReadCommand, args: readonly string[]): string[] { + return ["workspace", ...command.split(" "), ...args, ...JSON_FLAGS[command]]; +} + +/** + * The contract check every workspace document gets, or undefined when the + * document is written to the contract behold reads. + */ +export function contractRefusal(doc: Record, command: string): WorkspaceRefusal | undefined { + if (doc.contract === WORKSPACE_CONTRACT) return undefined; + const said = doc.contract === undefined ? "no contract version" : `contract ${JSON.stringify(doc.contract)}`; + return { + error: `chant workspace ${command} wrote a document with ${said}; behold reads contract ${WORKSPACE_CONTRACT}.`, + code: "workspace-contract", + remedy: + doc.contract === undefined + ? `Upgrade the workspace's chant to ${WORKSPACE_CHANT_FLOOR} or newer.` + : "Upgrade behold: this chant writes a newer workspace contract than it knows.", + }; +} + +/** The refusal code for a command: `workspace-ls`, `workspace-graph`, `workspace-intent`. */ +const codeFor = (command: WorkspaceReadCommand): string => (command === "graph --intent" ? "workspace-intent" : `workspace-${command}`); + +/** The reader over `chant`. One read is one chant call. */ +export function workspaceReader(chant: ChantTransport): WorkspaceReader { + return { + async read(command, args) { + const argv = readArgv(command, args); + const shown = `chant ${argv.join(" ")}`; + const run = await chant.run(argv); + const code = codeFor(command); + if (!run.stdout.trim()) { + const said = run.stderr.trim().split("\n").slice(-3).join(" "); + throw new WorkspaceReadError({ error: `${shown} printed nothing (exit ${run.status ?? "killed"})${said ? `: ${said}` : ""}`, code, remedy: `Run \`${shown}\` in the workspace root to see what it says.` }); + } + let doc: unknown; + try { + doc = JSON.parse(run.stdout); + } catch { + throw new WorkspaceReadError({ error: `${shown} printed something that is not JSON.`, code, remedy: `Run \`${shown}\` in the workspace root to see what it says.` }); + } + if (!isRecord(doc)) throw new WorkspaceReadError({ error: `${shown} printed JSON that is not an object.`, code, remedy: `Run \`${shown}\` in the workspace root.` }); + const refused = contractRefusal(doc, command); + if (refused) throw new WorkspaceReadError(refused); + return doc; + }, + }; +} + +/** + * The transport behold reads a workspace over: the root's own chant, run from + * the root (ws-021), through `runChantRaw`. `env` merges over the process + * environment for this one run, for a lens (src/chant.ts `envOverridesFor`). + */ +export function rootTransport(root: string, env?: Record): ChantTransport { + return { + async run(argv) { + const r = await runChantRaw(argv, root, env); + return { status: r.code, stdout: r.stdout, stderr: r.stderr }; + }, + }; +} + +/** The reader for a workspace root: {@link workspaceReader} over {@link rootTransport}. */ +export function rootReader(root: string, env?: Record): WorkspaceReader { + return workspaceReader(rootTransport(root, env)); +} diff --git a/src/workspace.test.ts b/src/workspace.test.ts index b91dc74a..8a57f95a 100644 --- a/src/workspace.test.ts +++ b/src/workspace.test.ts @@ -2,6 +2,7 @@ import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; +import { readArgv } from "./workspace-reader.ts"; import { drawnMembers, findDeclaration, @@ -202,7 +203,7 @@ describe("memberIrFromWorkspaceGraph", () => { }); it("passes only the flags the contract takes", () => { - expect(workspaceGraphArgs("/w", "api", { env: "prod", live: true, overlay: true, traffic: "peak" })).toEqual([ + expect(readArgv("graph", workspaceGraphArgs("/w", "api", { env: "prod", live: true, overlay: true, traffic: "peak" }))).toEqual([ "workspace", "graph", "/w", "--member", "api", "--env", "prod", "--live", "--overlay", "--traffic", "peak", ]); expect(workspaceGraphTakes({ env: "prod", live: true })).toBe(true); diff --git a/src/workspace.ts b/src/workspace.ts index 14a05f3c..360fe540 100644 --- a/src/workspace.ts +++ b/src/workspace.ts @@ -29,15 +29,21 @@ import { existsSync } from "node:fs"; import { join, resolve } from "node:path"; import type { GraphIR } from "@intentius/chant"; -import { envOverridesFor, runChantRaw, resolveChant, type GraphOptions } from "./chant.ts"; +import { envOverridesFor, resolveChant, type GraphOptions } from "./chant.ts"; import type { MemberVia } from "./member-ir.ts"; import { meetsFloor } from "./floor.ts"; import { setStampExclusions } from "./member-source.ts"; - -/** The read contract version behold reads (chant's `reference/workspace-read-contract`). */ -export const WORKSPACE_CONTRACT = 1; -/** The first chant that writes contract 1. An older one has no `workspace` command at all. */ -export const WORKSPACE_CHANT_FLOOR = "0.81.0"; +import { + contractRefusal, + rootReader, + WORKSPACE_CHANT_FLOOR, + WorkspaceReadError, + type WorkspaceDocument, + type WorkspaceReader, + type WorkspaceRefusal, +} from "./workspace-reader.ts"; + +export { contractRefusal, WORKSPACE_CHANT_FLOOR, WORKSPACE_CONTRACT, type WorkspaceRefusal } from "./workspace-reader.ts"; export const LS_SCHEMA_ID = "https://intentius.io/chant/schemas/workspace/ls/v1/ls.schema.json"; export const GRAPH_SCHEMA_ID = "https://intentius.io/chant/schemas/workspace/graph/v1/graph.schema.json"; @@ -73,13 +79,6 @@ export interface Workspace { members: WorkspaceMember[]; } -/** Why behold will not serve a declared workspace, in the #193 refusal shape. */ -export interface WorkspaceRefusal { - error: string; - code: string; - remedy: string; -} - export type WorkspaceRead = { ok: true; workspace: Workspace } | { ok: false; refusal: WorkspaceRefusal }; /** The declaration file in `dir`, or a refusal when both spellings exist. `undefined` when there is none. */ @@ -112,6 +111,15 @@ export function parseWorkspaceLs(text: string, root: string): WorkspaceRead { return refuse(`chant workspace ls printed something that is not JSON for ${root}.`, "workspace-ls", "Run `chant workspace ls --json` in the workspace root to see what it says."); } if (!isRecord(doc)) return refuse("chant workspace ls printed JSON that is not an object.", "workspace-ls", "Run `chant workspace ls --json` in the workspace root."); + return workspaceFromLs(doc, root); +} + +/** + * The workspace an `ls` document lists, or why behold can't use it. The + * reader (src/workspace-reader.ts) has checked the contract already; this + * checks it again for a document handed over straight, as a test does. + */ +export function workspaceFromLs(doc: WorkspaceDocument, root: string): WorkspaceRead { const contract = contractRefusal(doc, "ls"); if (contract) return { ok: false, refusal: contract }; if (isRecord(doc.error)) { @@ -143,26 +151,8 @@ export function parseWorkspaceLs(text: string, root: string): WorkspaceRead { }; } -/** - * The contract check every workspace document gets. A document with another - * `contract` is refused whole: within a version fields are only added, and a - * new version can change what a field means. - */ -export function contractRefusal(doc: Record, command: "ls" | "graph" | "status"): WorkspaceRefusal | undefined { - if (doc.contract === WORKSPACE_CONTRACT) return undefined; - const said = doc.contract === undefined ? "no contract version" : `contract ${JSON.stringify(doc.contract)}`; - return { - error: `chant workspace ${command} wrote a document with ${said}; behold reads contract ${WORKSPACE_CONTRACT}.`, - code: "workspace-contract", - remedy: - doc.contract === undefined - ? `Upgrade the workspace's chant to ${WORKSPACE_CHANT_FLOOR} or newer.` - : "Upgrade behold: this chant writes a newer workspace contract than it knows.", - }; -} - /** Ask the workspace's own chant for its member list. */ -export async function readWorkspace(root: string): Promise { +export async function readWorkspace(root: string, reader: WorkspaceReader = rootReader(resolve(root))): Promise { const dir = resolve(root); const found = findDeclaration(dir); if (!found) return refuse(`${dir} has no chant.workspace.json.`, "declaration-missing", "`chant workspace init` proposes one."); @@ -177,11 +167,12 @@ export async function readWorkspace(root: string): Promise { `Install @intentius/chant ${WORKSPACE_CHANT_FLOOR} or newer in the workspace root.`, ); } - const run = await runChantRaw(["workspace", "ls", dir, "--json"], dir); - if (!run.stdout.trim()) { - return refuse(`chant workspace ls failed in ${dir} (exit ${run.code}): ${run.stderr.trim().split("\n").slice(-3).join(" ")}`, "workspace-ls", "Run `chant workspace ls` in the workspace root."); + try { + return workspaceFromLs(await reader.read("ls", [dir]), dir); + } catch (e) { + if (e instanceof WorkspaceReadError) return { ok: false, refusal: e.refusal }; + throw e; } - return parseWorkspaceLs(run.stdout, dir); } // --------------------------------------------------------------------------- @@ -313,6 +304,11 @@ export function memberIrFromWorkspaceGraph(text: string, member: string): GraphI throw new Error("chant workspace graph printed something that is not JSON"); } if (!isRecord(doc)) throw new Error("chant workspace graph printed JSON that is not an object"); + return memberIrFromGraphDocument(doc, member); +} + +/** {@link memberIrFromWorkspaceGraph} over a document the reader returned. */ +export function memberIrFromGraphDocument(doc: WorkspaceDocument, member: string): GraphIR { const contract = contractRefusal(doc, "graph"); if (contract) throw new Error(`${contract.error} ${contract.remedy}`); if (isRecord(doc.error)) throw new Error(`chant workspace graph: ${String(doc.error.code)}: ${String(doc.error.message ?? "")}`); @@ -367,9 +363,9 @@ export function memberIrFromWorkspaceGraph(text: string, member: string): GraphI return ir as unknown as GraphIR; } -/** The flags one member's contract read passes on. */ +/** The arguments one member's contract read passes `workspace graph`. */ export function workspaceGraphArgs(root: string, member: string, opts: GraphOptions): string[] { - const args = ["workspace", "graph", root, "--member", member]; + const args = [root, "--member", member]; if (opts.env) args.push("--env", opts.env); if (opts.live) args.push("--live"); if (opts.overlay) args.push("--overlay"); @@ -394,10 +390,8 @@ export function workspaceVia(member: WorkspaceMember, root: string, fallback: Me }, read: async (dir, opts) => { if (!workspaceGraphTakes(opts)) return fallback.read(dir, opts); - const args = workspaceGraphArgs(root, member.name, opts); - const run = await runChantRaw(args, root, envOverridesFor(opts)); - if (!run.stdout.trim()) throw new Error(`chant ${args.join(" ")} exited ${run.code}: ${run.stderr.trim()}`); - return memberIrFromWorkspaceGraph(run.stdout, member.name); + const doc = await rootReader(root, envOverridesFor(opts)).read("graph", workspaceGraphArgs(root, member.name, opts)); + return memberIrFromGraphDocument(doc, member.name); }, }; }