@intentius/chant 0.124.95 → 0.124.97

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/change-set-graph.d.ts +3 -1
  2. package/dist/change-set-graph.d.ts.map +1 -1
  3. package/dist/change-set-graph.js +7 -1
  4. package/dist/change-set.d.ts +5 -2
  5. package/dist/change-set.d.ts.map +1 -1
  6. package/dist/change-set.js +6 -3
  7. package/dist/floor-table.data.d.ts.map +1 -1
  8. package/dist/floor-table.data.js +3 -7
  9. package/dist/reconcile.d.ts +9 -0
  10. package/dist/reconcile.d.ts.map +1 -1
  11. package/dist/release-floors.d.ts +3 -1
  12. package/dist/release-floors.d.ts.map +1 -1
  13. package/dist/release-floors.js +5 -3
  14. package/dist/wave-runtime.mjs +253 -253
  15. package/dist/workspace/drift-cli.d.ts +9 -0
  16. package/dist/workspace/drift-cli.d.ts.map +1 -1
  17. package/dist/workspace/drift-cli.js +54 -5
  18. package/dist/workspace/drift-reader.d.ts +60 -0
  19. package/dist/workspace/drift-reader.d.ts.map +1 -0
  20. package/dist/workspace/drift-reader.js +81 -0
  21. package/dist/workspace/drift-reader.schema.json +44 -0
  22. package/dist/workspace/kinds.d.ts +15 -0
  23. package/dist/workspace/kinds.d.ts.map +1 -1
  24. package/dist/workspace/kinds.js +17 -0
  25. package/dist/workspace/workspace-kinds.schema.json +23 -0
  26. package/package.json +1 -1
  27. package/src/change-set-graph.test.ts +33 -1
  28. package/src/change-set-graph.ts +7 -1
  29. package/src/change-set.ts +6 -3
  30. package/src/cli/handlers/pr-before-merge.test.ts +18 -0
  31. package/src/floor-table.data.ts +3 -2
  32. package/src/reconcile.ts +9 -0
  33. package/src/release-floors.ts +6 -3
  34. package/src/workspace/drift-cli.ts +53 -4
  35. package/src/workspace/drift-reader.schema.json +44 -0
  36. package/src/workspace/drift-reader.test.ts +192 -0
  37. package/src/workspace/drift-reader.ts +104 -0
  38. package/src/workspace/kinds.ts +32 -1
  39. package/src/workspace/workspace-kinds.schema.json +23 -0
package/src/reconcile.ts CHANGED
@@ -58,6 +58,15 @@ export interface ChangeSetEntry {
58
58
  after?: unknown;
59
59
  /** Field-level diff, populated for `update` entries. */
60
60
  fields?: FieldChange[];
61
+ /**
62
+ * The entry's address in a change set (`reconcilePlanPart`, #5089): the id
63
+ * of the graph node it changes, as the warden's `graph.reader` names it
64
+ * (`repo/<org>/<name>`), or `<node id>#<resourceType>[<key>]` for a change
65
+ * under that node. Set by a warden whose kind draws a graph, so plan
66
+ * entries sit on the same nodes as its drift records and two orgs never
67
+ * share an address. Absent, the address is `<resourceType>.<key>`.
68
+ */
69
+ address?: string;
61
70
  }
62
71
 
63
72
  /** The full set of changes to reconcile for one scope (e.g. one org). */
@@ -19,7 +19,7 @@
19
19
  * this constant to the next patch (#4501). The check fails while a floor
20
20
  * still names this constant after its version shipped.
21
21
  */
22
- export const NEXT_RELEASE = "0.124.95";
22
+ export const NEXT_RELEASE = "0.124.97";
23
23
 
24
24
  /** The first chant with `chant dev local` and `chant dev bundle-check`, `@intentius/chant/local-chant` and `@intentius/chant/bundle-check` (`chantRuntimeTarget`, `chantExternalPlugin`, `checkBundle`): a product built against a chant checkout, and its bundle checked, without its own scripts (#4787). */
25
25
  export const LOCAL_CHANT_FLOOR = "0.124.86";
@@ -247,10 +247,13 @@ export const OP_WAVES_SPLIT_RESUME_FLOOR = "0.124.94";
247
247
  export const OP_WAVES_REMAINDER_PARITY_FLOOR = "0.124.94";
248
248
 
249
249
  /** The first chant whose Op waves generators, in a product's workflow (`runIf`) with `beforeMerge` and a spec `control`, run the control job on the default branch's push, outside the product's `runIf` and after its `firstWaveNeeds` jobs, and tell the control repo the waves applied at the pushed commit without adding up outcomes, on GitHub, Forgejo and GitLab (#5060). */
250
- export const OP_WAVES_CONTROL_BEFORE_MERGE_FLOOR = NEXT_RELEASE;
250
+ export const OP_WAVES_CONTROL_BEFORE_MERGE_FLOOR = "0.124.95";
251
251
 
252
252
  /** The first chant whose waves before merge lock and unlock on a comment by the product plan's reach line (#5061): with `wavesBeforeMerge` and `productPlan.reach`, and no `locks: "plan"`, the comment job (GitHub, Forgejo) and the note poll (GitLab, `chantNoteRuns`) answer `/<product> lock` on an open pull request by taking the locks of what the reach line prints at stage `apply` in `_locks/<reach.gate>.json` without applying (`decideLocksBeforeMerge`), refused with the holder named, and `/<product> unlock` by releasing the pull request's locks; and the product plan takes `reach` without `locks: "plan"` under `wavesBeforeMerge`, writing no reach lock job. */
253
- export const WAVES_BEFORE_MERGE_LOCKS_FLOOR = NEXT_RELEASE;
253
+ export const WAVES_BEFORE_MERGE_LOCKS_FLOOR = "0.124.95";
254
+
255
+ /** The first chant whose kinds file takes `drift: { reader, config }` beside `graph` and whose `chant workspace drift --member` reads a member of such a kind with that module, `(input: { dir, config, member, observedAt, read?, resource?, stack? }) => DriftReaderOutput` from `@intentius/chant/workspace/drift-reader`, checked against `drift-reader.schema.json` (#5068). */
256
+ export const KIND_DRIFT_READER_FLOOR = "0.124.96";
254
257
 
255
258
  /** The first chant whose `chant run resume` (`resumeGateRun`) on GitLab retries a wave job's `<wave job>-evidence` with the wave job when the evidence job already ran, and whose `ci evidence sign --from-job` waits for a job it reads to finish, so a resumed wave's evidence job signs from the new try (#4978). */
256
259
  export const GITLAB_WAVE_EVIDENCE_RETRY_FLOOR = "0.124.89";
@@ -21,6 +21,15 @@
21
21
  * falls back to another stack's export or the checked-in file. Any other kind
22
22
  * answers `read-unsupported`.
23
23
  *
24
+ * A member of a package's kind whose kinds file names a drift reader
25
+ * (`drift.reader`, #5068) is read by that module instead (`./drift-reader.ts`):
26
+ * chant imports it in this process, with this process's environment, calls
27
+ * it with the member's directory, the kind's config (placeholders
28
+ * substituted), `--read`, `--resource` and `--stack`, and checks each line
29
+ * it returns with the drift codec. The reader answers for itself, refusals
30
+ * included; chant makes no forge call for it. A declared drift reader comes
31
+ * before the table above.
32
+ *
24
33
  * Any other kind has no drift read and answers `no-drift-read`. A member of
25
34
  * a package's kind runs in the reader project `workspace graph` writes for it
26
35
  * (`./kind-readers.ts`), under the member's own toolchain, so chant core
@@ -42,7 +51,7 @@
42
51
  */
43
52
 
44
53
  import { existsSync } from "node:fs";
45
- import { resolve } from "node:path";
54
+ import { join, resolve } from "node:path";
46
55
  import { formatError } from "../cli/format";
47
56
  import type { CommandContext, ParsedArgs } from "../cli/registry";
48
57
  import { graphNodeFor, type ChangeSetGraphNodes } from "../change-set-graph";
@@ -69,8 +78,10 @@ import {
69
78
  } from "../drift-record";
70
79
  import type { ComponentStatusRow } from "../lifecycle/status";
71
80
  import { readDeclaration, readerVersion, WORKSPACE_ERROR_CODES, WorkspaceReadError } from "./declaration";
81
+ import { readDriftWithModule } from "./drift-reader";
72
82
  import { prepareKindReaders } from "./kind-readers";
73
- import { loadKindRegistry } from "./kinds";
83
+ import { loadKindRegistry, substituteGraphConfig, type KindDrift, type KindRegistry } from "./kinds";
84
+ import { memberReason } from "./ls";
74
85
  import { emitDocument, executePlan, planMembers, type UnitResult } from "./member-commands";
75
86
  import type { ReasonCode } from "./reason-codes";
76
87
  import { handToRootChant, locateWorkspace } from "./which-chant";
@@ -156,6 +167,33 @@ function tail(text: string): string {
156
167
  return text.trim().split("\n").slice(-5).join("\n");
157
168
  }
158
169
 
170
+ /** Read a member through its kind's drift reader module (#5068): the lines it returns, checked, or a failure. */
171
+ async function kindReaderLines(query: DriftQuery, entry: { name: string; dir: string; kind: string }, drift: KindDrift, root: string): Promise<DriftLine[]> {
172
+ if (query.read !== undefined && !(DRIFT_READS as readonly string[]).includes(query.read)) {
173
+ throw new DriftReadFailure("read-unsupported", `--read ${query.read} is not a drift read; the reads are ${DRIFT_READS.join(", ")}`);
174
+ }
175
+ const abs = entry.dir === "." ? root : join(root, entry.dir);
176
+ const config = substituteGraphConfig(drift.config, { member: entry.name, dir: abs, workspace: root });
177
+ const answer = await readDriftWithModule(drift.readerFile!, {
178
+ dir: typeof config.dir === "string" ? config.dir : abs,
179
+ config,
180
+ member: entry.name,
181
+ observedAt: new Date().toISOString(),
182
+ ...(query.read !== undefined ? { read: query.read as DriftRead } : {}),
183
+ ...(query.resource !== undefined ? { resource: query.resource } : {}),
184
+ ...(query.stack !== undefined ? { stack: query.stack } : {}),
185
+ });
186
+ if ("error" in answer) throw new DriftReadFailure("command-failed", `${query.member}: ${answer.error}`);
187
+ if ("refused" in answer) throw new DriftReadFailure(answer.refused.code, `${query.member}: ${answer.refused.message}`);
188
+ return answer.lines;
189
+ }
190
+
191
+ /** The kinds `workspace drift` reads, for the no-drift-read message: the table's, and each loaded kind with a drift reader. */
192
+ function driftKinds(kinds: KindRegistry): string {
193
+ const readers = kinds.names().filter((k) => kinds.get(k)?.drift?.readerFile && !DRIFT_READS_BY_KIND[k]);
194
+ return [...Object.keys(DRIFT_READS_BY_KIND), ...readers].join(", ");
195
+ }
196
+
159
197
  /** The member's node ids, without the member in front, from its source graph; null when it can't be read. */
160
198
  async function memberGraph(cwd: string, member: string): Promise<ChangeSetGraphNodes | null> {
161
199
  try {
@@ -246,8 +284,20 @@ export async function readWorkspaceDrift(query: DriftQuery): Promise<DriftReadRe
246
284
  if (!entry) {
247
285
  throw new DriftReadFailure("member-required", `--member ${query.member} is not a member of ${declaration.name}; it declares ${declaration.members.map((m) => m.name).join(", ")}`);
248
286
  }
287
+ const { registry: kinds, problems } = loadKindRegistry(declaration.pins, located.rootOnDisk);
288
+ const drift = kinds.get(entry.kind)?.drift;
289
+ if (drift?.readerFile) {
290
+ // A kind's own drift reader (#5068), imported here: no reader project, and the member's graph places its records as for any member.
291
+ const reason = memberReason(entry, located.tree, kinds);
292
+ if (reason) throw new DriftReadFailure("command-failed", `${query.member}: ${reason.code}: ${reason.message}`);
293
+ const [graph, lines] = await Promise.all([memberGraph(query.cwd, query.member), kindReaderLines(query, entry, drift, located.rootOnDisk)]);
294
+ return { lines: placeLines(lines, query.member, graph) };
295
+ }
249
296
  const reads = DRIFT_READS_BY_KIND[entry.kind];
250
- if (!reads) throw new DriftReadFailure("no-drift-read", `${query.member} is kind ${entry.kind}, and chant workspace drift reads members of kind ${Object.keys(DRIFT_READS_BY_KIND).join(", ")}`);
297
+ if (!reads) {
298
+ const problem = problems.find((p) => p.message.includes(`kind ${entry.kind} names drift reader`));
299
+ throw new DriftReadFailure("no-drift-read", `${query.member} is kind ${entry.kind}, and chant workspace drift reads members of kind ${driftKinds(kinds)}${problem ? `; ${problem.message}` : ""}`);
300
+ }
251
301
  if (query.read !== undefined && !(DRIFT_READS as readonly string[]).includes(query.read)) {
252
302
  throw new DriftReadFailure("read-unsupported", `--read ${query.read} is not a drift read; the reads are ${DRIFT_READS.join(", ")}`);
253
303
  }
@@ -262,7 +312,6 @@ export async function readWorkspaceDrift(query: DriftQuery): Promise<DriftReadRe
262
312
  if (query.stack !== undefined && query.stack.trim() === "") throw new DriftReadFailure("read-unsupported", "--stack needs a stack name");
263
313
  if (entry.kind === "chant" && !query.env) throw new DriftReadFailure("env-required", `${query.member} is a chant member, read live through chant lifecycle diff <env> --live: add --env <env>`);
264
314
 
265
- const { registry: kinds, problems } = loadKindRegistry(declaration.pins, located.rootOnDisk);
266
315
  const plan = planMembers("graph", located.rootOnDisk, { only: [query.member], tree: located.tree, kinds, kindProblems: problems.map((p) => p.message) });
267
316
  const notRun = [...plan.unreadable, ...plan.skipped].find((s) => s.name === query.member);
268
317
  if (notRun) throw new DriftReadFailure(plan.unreadable.includes(notRun) ? "command-failed" : "no-drift-read", `${query.member}: ${notRun.reason.code}: ${notRun.reason.message}`);
@@ -0,0 +1,44 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://intentius.io/chant/schemas/workspace/drift-reader/v1/drift-reader.schema.json",
4
+ "title": "drift reader output",
5
+ "description": "What a kind's drift reader module returns (#5068), the same answer a lexicon's readDrift gives chant lifecycle drift (ReadDriftResult in @intentius/chant/drift-record, DriftReaderOutput in @intentius/chant/workspace/drift-reader). Either the lines of each read the reader ran, in order, as the drift record's NDJSON stream has them (a drift-start, its drift-record lines and a drift-settle per read, each line one of drift.schema.json's $defs/line), or a refusal with a code chant workspace drift prints. A read that ran and failed is not a refusal: its addresses are records with status not-observed. chant workspace drift renames every line's member to the workspace member and places each record on the member's graph. First read by chant 0.124.96.",
6
+ "oneOf": [
7
+ {
8
+ "type": "object",
9
+ "required": ["lines"],
10
+ "properties": {
11
+ "lines": {
12
+ "type": "array",
13
+ "items": {
14
+ "$ref": "https://intentius.io/chant/schemas/workspace/drift/v1/drift.schema.json#/$defs/line"
15
+ },
16
+ "description": "The stream lines, in order. An empty list is a read that found nothing to report."
17
+ }
18
+ },
19
+ "additionalProperties": false
20
+ },
21
+ {
22
+ "type": "object",
23
+ "required": ["refused"],
24
+ "properties": {
25
+ "refused": {
26
+ "type": "object",
27
+ "required": ["code", "message"],
28
+ "properties": {
29
+ "code": {
30
+ "enum": ["read-unsupported", "resource-unsupported", "no-drift-read"],
31
+ "description": "read-unsupported for a --read or --stack the reader has not got, resource-unsupported for --resource on a reader that cannot read one resource on its own, no-drift-read when there is nothing to read (ReadDriftRefusalCode)."
32
+ },
33
+ "message": {
34
+ "type": "string",
35
+ "minLength": 1
36
+ }
37
+ },
38
+ "additionalProperties": false
39
+ }
40
+ },
41
+ "additionalProperties": false
42
+ }
43
+ ]
44
+ }
@@ -0,0 +1,192 @@
1
+ /**
2
+ * A kind's drift reader (#5068): the kinds file takes `drift.reader` beside
3
+ * `graph`, the loader resolves it inside the package, and `chant workspace
4
+ * drift --member` calls it for a member of the kind, checks what it returns
5
+ * and puts the workspace member on every line. A kind without one still
6
+ * answers `no-drift-read`.
7
+ */
8
+
9
+ import Ajv2020 from "ajv/dist/2020";
10
+ import { join } from "node:path";
11
+ import { afterAll, describe, expect, test } from "vitest";
12
+ import { driftRecord, driftRecordLine, driftSettle, driftStart } from "../drift-record";
13
+ import { KIND_DRIFT_READER_FLOOR } from "../release-floors";
14
+ import { cleanScratch, declaration, repo } from "./__fixtures__/contract-repo";
15
+ import { driftReadDocument, readWorkspaceDrift } from "./drift-cli";
16
+ import { checkDriftReaderOutput, DRIFT_READER_SCHEMA_ID } from "./drift-reader";
17
+ import driftReaderSchema from "./drift-reader.schema.json";
18
+ import driftSchema from "./drift.schema.json";
19
+ import { readContractSchema } from "./conformance";
20
+ import { loadKindRegistry, parseKindData } from "./kinds";
21
+ import kindsSchema from "./workspace-kinds.schema.json";
22
+
23
+ afterAll(cleanScratch);
24
+
25
+ const at = "2026-11-14T09:00:00Z";
26
+ const probe = { anyFile: ["governance.yml"] };
27
+ const kind = (extra: Record<string, unknown> = {}) => ({ name: "gov", description: "a forge governance policy", precedence: 500, probe, ...extra });
28
+ const kindsFile = (kinds: unknown[]) => JSON.stringify({ schema: 1, kinds });
29
+
30
+ /** A reader that reports one drifted repo and one in sync, echoing what it was handed in the evidence. */
31
+ const DRIFTING = `export default async function read(input) {
32
+ const evidence = { tool: "warden", command: JSON.stringify({ dir: input.dir, config: input.config, read: input.read ?? null, token: process.env.WARDEN_TEST_TOKEN ?? null }) };
33
+ const base = { member: input.member, engine: "warden", observedAt: input.observedAt, read: "live-read", node: null, evidence };
34
+ return {
35
+ lines: [
36
+ { type: "drift-start", drift: "v1", member: input.member, engine: "warden", read: "live-read", at: input.observedAt, expected: ["repo.api", "repo.web", "team.ops"] },
37
+ { type: "drift-record", ...base, address: "repo.api", resourceType: "Repo", status: "drifted", attributes: [{ path: "visibility", before: "private", after: "public" }] },
38
+ { type: "drift-record", ...base, address: "repo.web", resourceType: "Repo", status: "in-sync" },
39
+ { type: "drift-settle", drift: "v1", member: input.member, engine: "warden", read: "live-read", counts: { drifted: 1, "in-sync": 1 }, at: input.observedAt },
40
+ ],
41
+ };
42
+ }
43
+ `;
44
+
45
+ /** A reader whose read found nothing to report. */
46
+ const QUIET = `export default () => ({ lines: [] });\n`;
47
+
48
+ /** A reader that refuses every --read but its own. */
49
+ const REFUSING = `export default (input) => input.read && input.read !== "live-read" ? { refused: { code: "read-unsupported", message: "the warden reads live-read only" } } : { lines: [] };\n`;
50
+
51
+ /** A reader that writes a state read saying in-sync, which the drift record refuses. */
52
+ const LYING = `export default (input) => ({ lines: [{ type: "drift-record", member: input.member, engine: "warden", address: "x", node: null, observedAt: input.observedAt, read: "state", status: "in-sync", evidence: { tool: "warden" } }] });\n`;
53
+
54
+ function wardenPackage(name: string, reader: string | null, drift: Record<string, unknown> | null = { reader: "dist/drift-reader.mjs", config: { dir: "{dir}", file: "governance.yml", who: "{member}" } }): Record<string, string> {
55
+ return {
56
+ [`node_modules/${name}/package.json`]: JSON.stringify({ name, version: "1.0.0", exports: { "./workspace-kinds": "./workspace-kinds.json" } }),
57
+ [`node_modules/${name}/workspace-kinds.json`]: kindsFile([kind(drift ? { drift } : {})]),
58
+ ...(reader !== null ? { [`node_modules/${name}/dist/drift-reader.mjs`]: reader } : {}),
59
+ };
60
+ }
61
+
62
+ function workspace(reader: string | null, drift?: Record<string, unknown> | null): string {
63
+ return repo({
64
+ "chant.workspace.json": declaration([{ name: "forge", dir: "org", kind: "gov" }], { pins: [{ package: "@acme/warden", version: "1.0.0" }] }),
65
+ "org/governance.yml": "org: acme\n",
66
+ ".gitignore": "node_modules\n",
67
+ ...wardenPackage("@acme/warden", reader, drift),
68
+ });
69
+ }
70
+
71
+ describe("the kinds file's drift block", () => {
72
+ const ajv = new Ajv2020({ strict: true, allErrors: true });
73
+ const validate = ajv.compile(kindsSchema);
74
+
75
+ test("the schema accepts drift.reader with or without config, beside graph", () => {
76
+ expect(validate({ schema: 1, kinds: [kind({ drift: { reader: "dist/drift-reader.mjs" } })] }), JSON.stringify(validate.errors)).toBe(true);
77
+ expect(validate({ schema: 1, kinds: [kind({ graph: { reader: "dist/graph.mjs" }, drift: { reader: "dist/drift-reader.mjs", config: { dir: "{dir}" }, "x-note": "ours" } })] }), JSON.stringify(validate.errors)).toBe(true);
78
+ });
79
+
80
+ test("the schema refuses a drift block with no reader, a path that leaves the package, or an unknown field", () => {
81
+ expect(validate({ schema: 1, kinds: [kind({ drift: { config: {} } })] })).toBe(false);
82
+ expect(validate({ schema: 1, kinds: [kind({ drift: { reader: "/etc/x.mjs" } })] })).toBe(false);
83
+ expect(validate({ schema: 1, kinds: [kind({ drift: { reader: "../x.mjs" } })] })).toBe(false);
84
+ expect(validate({ schema: 1, kinds: [kind({ drift: { reader: "x.mjs", lexicon: "github" } })] })).toBe(false);
85
+ });
86
+
87
+ test("parseKindData keeps the block, config defaulting to {}", () => {
88
+ const { kinds, problems } = parseKindData(kindsFile([kind({ drift: { reader: "dist/drift-reader.mjs" } })]), "p");
89
+ expect(problems).toEqual([]);
90
+ expect(kinds[0].drift).toEqual({ reader: "dist/drift-reader.mjs", config: {} });
91
+ });
92
+
93
+ test("the loader resolves the reader inside the package, and drops one that is missing", () => {
94
+ const root = repo({ ...wardenPackage("@acme/warden", QUIET), ...wardenPackage("@acme/gone", null) });
95
+ const good = loadKindRegistry([{ package: "@acme/warden", version: "1.0.0", path: null }], root);
96
+ expect(good.problems).toEqual([]);
97
+ expect(good.registry.get("gov")?.drift?.readerFile).toBe(join(root, "node_modules/@acme/warden/dist/drift-reader.mjs"));
98
+ const gone = loadKindRegistry([{ package: "@acme/gone", version: "1.0.0", path: null }], root);
99
+ expect(gone.problems.map((p) => p.message)).toEqual([expect.stringMatching(/drift reader dist\/drift-reader.mjs, which does not exist/)]);
100
+ expect(gone.registry.get("gov")).toBeDefined();
101
+ expect(gone.registry.get("gov")?.drift).toBeUndefined();
102
+ });
103
+ });
104
+
105
+ describe("the drift reader's output schema", () => {
106
+ const ajv = new Ajv2020({ strict: true, allErrors: true });
107
+ ajv.addSchema(driftSchema);
108
+ const validate = ajv.compile(driftReaderSchema);
109
+
110
+ test("names its $id, and the floor is the release that shipped it", () => {
111
+ expect(driftReaderSchema.$id).toBe(DRIFT_READER_SCHEMA_ID);
112
+ expect(KIND_DRIFT_READER_FLOOR).toBe("0.124.96");
113
+ });
114
+
115
+ test("takes the lines of a read and a refusal, and nothing else", () => {
116
+ const record = driftRecord({ member: "forge", engine: "warden", address: "repo.api", node: null, observedAt: at, read: "live-read", status: "in-sync", evidence: { tool: "warden" } });
117
+ const start = driftStart({ member: "forge", engine: "warden", read: "live-read", at, expected: ["repo.api"] });
118
+ const lines = [start, driftRecordLine(record), driftSettle(start, [record], at).line];
119
+ expect(validate({ lines }), JSON.stringify(validate.errors)).toBe(true);
120
+ expect(validate({ lines: [] })).toBe(true);
121
+ expect(validate({ refused: { code: "read-unsupported", message: "no" } })).toBe(true);
122
+ expect(validate({ refused: { code: "command-failed", message: "no" } })).toBe(false);
123
+ expect(validate({ lines: [{ type: "drift-nope" }] })).toBe(false);
124
+ expect(validate({ records: [] })).toBe(false);
125
+ expect(checkDriftReaderOutput({ lines })).toEqual({ lines });
126
+ expect(checkDriftReaderOutput({ records: [] })).toEqual({ error: expect.stringMatching(/no lines array/) });
127
+ });
128
+ });
129
+
130
+ describe("chant workspace drift --member over a kind's drift reader", () => {
131
+ test("runs the reader with the substituted config and the environment, and prints its records for the member", async () => {
132
+ const root = workspace(DRIFTING);
133
+ process.env.WARDEN_TEST_TOKEN = "t0ken";
134
+ try {
135
+ const answer = await readWorkspaceDrift({ cwd: root, member: "forge" });
136
+ if ("error" in answer) throw new Error(`${answer.error.code}: ${answer.error.message}`);
137
+ const doc = driftReadDocument("forge", answer);
138
+ const { validate } = readContractSchema("drift");
139
+ expect(validate(doc), JSON.stringify(validate.errors)).toBe(true);
140
+ expect(doc.error).toBeUndefined();
141
+ expect(doc.records.map((r) => [r.member, r.engine, r.address, r.status])).toEqual([
142
+ ["forge", "warden", "repo.api", "drifted"],
143
+ ["forge", "warden", "repo.web", "in-sync"],
144
+ ["forge", "warden", "team.ops", "not-observed"],
145
+ ]);
146
+ expect(doc.records[2].unobserved?.reason).toBe("not-reached");
147
+ expect(JSON.parse(doc.records[0].evidence.command!)).toEqual({
148
+ dir: join(root, "org"),
149
+ config: { dir: join(root, "org"), file: "governance.yml", who: "forge" },
150
+ read: null,
151
+ token: "t0ken",
152
+ });
153
+ } finally {
154
+ delete process.env.WARDEN_TEST_TOKEN;
155
+ }
156
+ });
157
+
158
+ test("a reader that finds nothing answers an empty document, not an error", async () => {
159
+ const answer = await readWorkspaceDrift({ cwd: workspace(QUIET), member: "forge" });
160
+ expect(answer).toEqual({ lines: [] });
161
+ const doc = driftReadDocument("forge", answer);
162
+ expect(doc.records).toEqual([]);
163
+ expect(doc.error).toBeUndefined();
164
+ });
165
+
166
+ test("--read passes through, and the reader's refusal is the document's error", async () => {
167
+ const root = workspace(REFUSING);
168
+ const refused = await readWorkspaceDrift({ cwd: root, member: "forge", read: "state" });
169
+ expect(refused).toEqual({ error: { code: "read-unsupported", message: "forge: the warden reads live-read only" } });
170
+ expect(await readWorkspaceDrift({ cwd: root, member: "forge", read: "live-read" })).toEqual({ lines: [] });
171
+ const bad = await readWorkspaceDrift({ cwd: root, member: "forge", read: "nope" });
172
+ expect("error" in bad && bad.error.code).toBe("read-unsupported");
173
+ });
174
+
175
+ test("a line the drift record refuses fails the read with command-failed", async () => {
176
+ const answer = await readWorkspaceDrift({ cwd: workspace(LYING), member: "forge" });
177
+ expect("error" in answer && answer.error.code).toBe("command-failed");
178
+ expect("error" in answer && answer.error.message).toMatch(/is not drift/);
179
+ });
180
+
181
+ test("a kind with no drift reader still answers no-drift-read", async () => {
182
+ const answer = await readWorkspaceDrift({ cwd: workspace(null, null), member: "forge" });
183
+ expect("error" in answer && answer.error.code).toBe("no-drift-read");
184
+ expect("error" in answer && answer.error.message).toMatch(/forge is kind gov, and chant workspace drift reads members of kind chant, terraform, choudoufu, pulumi$/);
185
+ });
186
+
187
+ test("a kind whose drift reader is missing from the package answers no-drift-read and says why", async () => {
188
+ const answer = await readWorkspaceDrift({ cwd: workspace(null), member: "forge" });
189
+ expect("error" in answer && answer.error.code).toBe("no-drift-read");
190
+ expect("error" in answer && answer.error.message).toMatch(/names drift reader dist\/drift-reader.mjs, which does not exist/);
191
+ });
192
+ });
@@ -0,0 +1,104 @@
1
+ /**
2
+ * A kind's drift reader (#5068).
3
+ *
4
+ * A kinds file can name a drift reader module beside its graph reader:
5
+ *
6
+ * ```json
7
+ * "drift": { "reader": "dist/drift-reader.mjs", "config": { "dir": "{dir}", "file": "governance.yml" } }
8
+ * ```
9
+ *
10
+ * `chant workspace drift --member <name>` imports the module for a member of
11
+ * that kind and calls its default export with {@link DriftReaderInput}. It
12
+ * answers as a lexicon's `readDrift` answers `chant lifecycle drift`
13
+ * ({@link DriftReaderOutput}, `ReadDriftResult` in `../drift-record.ts`):
14
+ * the drift stream lines of each read it ran, or a refusal. Its schema is
15
+ * `./drift-reader.schema.json`, `$id` {@link DRIFT_READER_SCHEMA_ID}.
16
+ *
17
+ * The module runs in the process of the chant that reads the workspace, with
18
+ * that process's environment, so a reader that asks a forge brings its own
19
+ * credentials from there. chant makes no call to the forge for it. Each line
20
+ * the module returns is checked with the drift record's codec
21
+ * (`decodeDriftLine`), so a state read that says in-sync, or a not-observed
22
+ * record with no reason, fails the read rather than reaching a renderer.
23
+ */
24
+
25
+ import { isAbsolute } from "node:path";
26
+ import { pathToFileURL } from "node:url";
27
+ import { decodeDriftLine, type DriftLine, type DriftRead, type ReadDriftRefusalCode, type ReadDriftResult } from "../drift-record";
28
+
29
+ /** The schema a drift reader's output holds to. */
30
+ export const DRIFT_READER_SCHEMA_ID = "https://intentius.io/chant/schemas/workspace/drift-reader/v1/drift-reader.schema.json";
31
+
32
+ /** What a drift reader module's default export is called with. */
33
+ export interface DriftReaderInput {
34
+ /** The member's directory, absolute: the kind config's `dir` when it sets one as a string, else the member's own directory. */
35
+ dir: string;
36
+ /** The kind's `drift.config`, with `{member}`, `{dir}` and `{workspace}` substituted. */
37
+ config: Record<string, unknown>;
38
+ /** The workspace member the records are for. chant puts this name on every line whatever the reader writes. */
39
+ member: string;
40
+ /** RFC 3339, the `observedAt` to give every record the reader builds. */
41
+ observedAt: string;
42
+ /** `--read`, when given. Unset, the reader's default read. */
43
+ read?: DriftRead;
44
+ /** `--resource`, when given: one address to read. */
45
+ resource?: string;
46
+ /** `--stack`, when given. */
47
+ stack?: string;
48
+ }
49
+
50
+ /** What a drift reader module returns: the same answer as a lexicon's `readDrift`. */
51
+ export type DriftReaderOutput = ReadDriftResult;
52
+
53
+ /** A drift reader module's default export. */
54
+ export type DriftReader = (input: DriftReaderInput) => DriftReaderOutput | Promise<DriftReaderOutput>;
55
+
56
+ const REFUSAL_CODES: readonly ReadDriftRefusalCode[] = ["read-unsupported", "resource-unsupported", "no-drift-read"];
57
+
58
+ const isObject = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v);
59
+
60
+ /**
61
+ * Check what a reader returned: each line through the drift codec, a
62
+ * refusal's code against the closed list. `error` says why it is not an
63
+ * answer.
64
+ */
65
+ export function checkDriftReaderOutput(out: unknown): DriftReaderOutput | { error: string } {
66
+ if (!isObject(out)) return { error: "returned something that is not an object with lines or refused" };
67
+ if ("refused" in out) {
68
+ const refused = out.refused;
69
+ if (!isObject(refused) || !(REFUSAL_CODES as readonly unknown[]).includes(refused.code) || typeof refused.message !== "string" || refused.message === "") {
70
+ return { error: `returned a refusal that is not { code: ${REFUSAL_CODES.join(" | ")}, message }` };
71
+ }
72
+ return { refused: { code: refused.code as ReadDriftRefusalCode, message: refused.message } };
73
+ }
74
+ if (!Array.isArray(out.lines)) return { error: "returned something with no lines array and no refusal" };
75
+ const lines: DriftLine[] = [];
76
+ for (const [i, line] of out.lines.entries()) {
77
+ try {
78
+ lines.push(decodeDriftLine(JSON.stringify(line)));
79
+ } catch (err) {
80
+ return { error: `returned a line ${i} that is not drift: ${err instanceof Error ? err.message : String(err)}` };
81
+ }
82
+ }
83
+ return { lines };
84
+ }
85
+
86
+ /** Import the module and call it, or say why not. Never throws. */
87
+ export async function readDriftWithModule(module: string, input: DriftReaderInput): Promise<DriftReaderOutput | { error: string }> {
88
+ if (!isAbsolute(module)) return { error: `drift reader ${module} must be an absolute path` };
89
+ let read: unknown;
90
+ try {
91
+ read = ((await import(pathToFileURL(module).href)) as { default?: unknown }).default;
92
+ } catch (err) {
93
+ return { error: `drift reader ${module} could not be loaded: ${err instanceof Error ? err.message : String(err)}` };
94
+ }
95
+ if (typeof read !== "function") return { error: `drift reader ${module} has no default export function` };
96
+ let out: unknown;
97
+ try {
98
+ out = await (read as DriftReader)(input);
99
+ } catch (err) {
100
+ return { error: `drift reader ${module} failed: ${err instanceof Error ? err.message : String(err)}` };
101
+ }
102
+ const checked = checkDriftReaderOutput(out);
103
+ return "error" in checked ? { error: `drift reader ${module} ${checked.error}` } : checked;
104
+ }
@@ -137,6 +137,20 @@ export interface KindGraph {
137
137
  config: Record<string, unknown>;
138
138
  }
139
139
 
140
+ /**
141
+ * How `chant workspace drift --member` reads a member of a package's kind
142
+ * (#5068): a drift reader module the package ships, and the config it is
143
+ * called with. See `./drift-reader.ts` for the contract and
144
+ * {@link substituteGraphConfig} for the placeholders.
145
+ */
146
+ export interface KindDrift {
147
+ /** The drift reader module, as the kinds file names it: a path inside the supplying package. */
148
+ reader: string;
149
+ /** The reader module, absolute; set once the package directory is known. */
150
+ readerFile?: string;
151
+ config: Record<string, unknown>;
152
+ }
153
+
140
154
  export interface MemberKind {
141
155
  name: string;
142
156
  /** One line for listings and error messages. */
@@ -158,6 +172,8 @@ export interface MemberKind {
158
172
  packageDir?: string;
159
173
  /** How `workspace graph` reads a member of this kind (#2874); unset, the member is `kind-not-run`. */
160
174
  graph?: KindGraph;
175
+ /** How `workspace drift` reads a member of this kind (#5068); unset, the member answers `no-drift-read` unless chant reads its kind itself. */
176
+ drift?: KindDrift;
161
177
  /** The fields a member entry of this kind may set, with their defaults (#3151); unset, the kind declares none. */
162
178
  fields?: Record<string, KindField>;
163
179
  /**
@@ -518,7 +534,7 @@ export function parseKindData(text: string, source: string): KindData {
518
534
  const problems: string[] = [];
519
535
  const kinds: MemberKind[] = [];
520
536
  const seen = new Set<string>();
521
- for (const k of (raw as { kinds: { name: string; description: string; precedence: number; probe: FileProbe; outputs?: string[]; graph?: KindGraph; fields?: Record<string, KindField>; reader?: string; memberFile?: { path: string; schema: string } }[] }).kinds) {
537
+ for (const k of (raw as { kinds: { name: string; description: string; precedence: number; probe: FileProbe; outputs?: string[]; graph?: KindGraph; drift?: { reader: string; config?: Record<string, unknown> }; fields?: Record<string, KindField>; reader?: string; memberFile?: { path: string; schema: string } }[] }).kinds) {
522
538
  if (BUILTIN_KIND_NAMES.includes(k.name)) {
523
539
  problems.push(`${source}: kind ${k.name} is built in and can't be supplied by a package`);
524
540
  continue;
@@ -545,6 +561,7 @@ export function parseKindData(text: string, source: string): KindData {
545
561
  ...(k.graph
546
562
  ? { graph: { ...(k.graph.lexicon ? { lexicon: k.graph.lexicon } : {}), ...(k.graph.reader ? { reader: k.graph.reader } : {}), config: structuredClone(k.graph.config ?? {}) } }
547
563
  : {}),
564
+ ...(k.drift ? { drift: { reader: k.drift.reader, config: structuredClone(k.drift.config ?? {}) } } : {}),
548
565
  ...(k.fields ? { fields: structuredClone(k.fields) } : {}),
549
566
  ...(k.reader && (KIND_LINK_READERS as readonly string[]).includes(k.reader) ? { reader: k.reader as KindLinkReaderName } : {}),
550
567
  ...(k.memberFile ? { memberFile: { path: k.memberFile.path, schema: k.memberFile.schema } } : {}),
@@ -624,6 +641,20 @@ export function readPackageKinds(packageDir: string, source?: string): PackageKi
624
641
  );
625
642
  delete k.graph;
626
643
  }
644
+ if (k.drift) {
645
+ // A drift reader module (#5068) is the package's own file, like a graph reader: inside the package and present. Nothing is imported here.
646
+ const file = resolve(packageDir, ...k.drift.reader.split("/"));
647
+ const inside = relative(packageDir, file);
648
+ if (inside.startsWith("..") || isAbsolute(inside)) {
649
+ data.problems.push(`${name}: kind ${k.name} names drift reader ${k.drift.reader}, which is outside the package; the kind is kept, and workspace drift answers no-drift-read for its members`);
650
+ delete k.drift;
651
+ } else if (!existsSync(file)) {
652
+ data.problems.push(`${name}: kind ${k.name} names drift reader ${k.drift.reader}, which does not exist in the package; the kind is kept, and workspace drift answers no-drift-read for its members`);
653
+ delete k.drift;
654
+ } else {
655
+ k.drift.readerFile = file;
656
+ }
657
+ }
627
658
  }
628
659
  return { ...data, file };
629
660
  }
@@ -76,6 +76,9 @@
76
76
  "graph": {
77
77
  "$ref": "#/$defs/graph"
78
78
  },
79
+ "drift": {
80
+ "$ref": "#/$defs/drift"
81
+ },
79
82
  "fields": {
80
83
  "$ref": "#/$defs/fields"
81
84
  },
@@ -265,6 +268,26 @@
265
268
  },
266
269
  "additionalProperties": false
267
270
  },
271
+ "drift": {
272
+ "type": "object",
273
+ "description": "How chant workspace drift --member reads a member of this kind (#5068): a drift reader module the supplying package ships, called with the member's directory and config. In every string key and value of config, {member} becomes the member's name, {dir} its absolute directory and {workspace} the absolute workspace root, as in graph. Without this field a member of the kind answers no-drift-read. A chant older than this field can't read a kinds file that uses it.",
274
+ "required": ["reader"],
275
+ "properties": {
276
+ "reader": {
277
+ "type": "string",
278
+ "pattern": "^(?!/)(?!.*\\.\\.)(?!.*\\\\)[^\\u0000-\\u001f]+$",
279
+ "description": "A drift reader module, as a path inside the supplying package: an ES module whose default export is (input: { dir, config, member, observedAt, read?, resource?, stack? }) => DriftReaderOutput, sync or async, the lines of each read it ran or a refusal (drift-reader.schema.json). chant workspace drift imports it in its own process, with the process's environment, so the reader brings its own credentials; chant makes no call of its own for it."
280
+ },
281
+ "config": {
282
+ "type": "object",
283
+ "description": "The config object the module is called with (optional). Placeholders are substituted; nothing else is interpreted."
284
+ }
285
+ },
286
+ "patternProperties": {
287
+ "^x-": true
288
+ },
289
+ "additionalProperties": false
290
+ },
268
291
  "fields": {
269
292
  "type": "object",
270
293
  "description": "The fields a member entry of this kind may set under its own fields block, each with a type and, optionally, a default (#3151). chant workspace check fails a member whose fields name one the kind doesn't declare or give a value of the wrong type (WSP005), and chant workspace status --json prints every declared field with the defaults filled in. Added by chant 0.103.0; an older chant can't read a kinds file that uses it.",