Skip to content
Merged
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
8 changes: 8 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
29 changes: 14 additions & 15 deletions src/workspace-gates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -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 <env> --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 <env> --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)) {
Expand Down Expand Up @@ -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<GatesRead> {
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 <env>` 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<GatesRead> {
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. */
Expand Down
68 changes: 68 additions & 0 deletions src/workspace-reader-conformance.test.ts
Original file line number Diff line number Diff line change
@@ -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([]);
});
});
151 changes: 151 additions & 0 deletions src/workspace-reader.ts
Original file line number Diff line number Diff line change
@@ -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<WorkspaceReadCommand, readonly string[]> = {
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<TransportRun>;
}

export type WorkspaceDocument = Record<string, unknown>;

export interface WorkspaceReader {
/** Run one contract command with `args`, and return the document chant printed, unchanged. */
read(command: WorkspaceReadCommand, args: string[]): Promise<WorkspaceDocument>;
}

const isRecord = (v: unknown): v is Record<string, unknown> => v !== null && typeof v === "object" && !Array.isArray(v);

/** The argv one read runs: `workspace <command> <args> <json flag>`. */
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<string, unknown>, 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<string, string>): 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<string, string>): WorkspaceReader {
return workspaceReader(rootTransport(root, env));
}
3 changes: 2 additions & 1 deletion src/workspace.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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);
Expand Down
Loading
Loading