@intentius/chant 0.124.94 → 0.124.96

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 (56) hide show
  1. package/dist/ci-comment-commands.d.ts +12 -1
  2. package/dist/ci-comment-commands.d.ts.map +1 -1
  3. package/dist/ci-comment-commands.js +29 -0
  4. package/dist/ci-note-commands.d.ts +1 -1
  5. package/dist/ci-note-commands.d.ts.map +1 -1
  6. package/dist/ci-note-commands.js +11 -1
  7. package/dist/ci-product.d.ts +2 -0
  8. package/dist/ci-product.d.ts.map +1 -1
  9. package/dist/ci-product.js +5 -4
  10. package/dist/cli/handlers/pr-comment.d.ts.map +1 -1
  11. package/dist/cli/handlers/pr-comment.js +11 -4
  12. package/dist/components/product-pipeline.d.ts.map +1 -1
  13. package/dist/components/product-pipeline.js +4 -2
  14. package/dist/components/product-plan.d.ts +6 -0
  15. package/dist/components/product-plan.d.ts.map +1 -1
  16. package/dist/components/product-plan.js +9 -1
  17. package/dist/floor-table.data.d.ts.map +1 -1
  18. package/dist/floor-table.data.js +10 -7
  19. package/dist/op/before-merge-decide.d.ts +39 -2
  20. package/dist/op/before-merge-decide.d.ts.map +1 -1
  21. package/dist/op/before-merge-decide.js +59 -0
  22. package/dist/release-floors.d.ts +7 -1
  23. package/dist/release-floors.d.ts.map +1 -1
  24. package/dist/release-floors.js +11 -5
  25. package/dist/wave-runtime.mjs +272 -272
  26. package/dist/workspace/drift-cli.d.ts +9 -0
  27. package/dist/workspace/drift-cli.d.ts.map +1 -1
  28. package/dist/workspace/drift-cli.js +54 -5
  29. package/dist/workspace/drift-reader.d.ts +60 -0
  30. package/dist/workspace/drift-reader.d.ts.map +1 -0
  31. package/dist/workspace/drift-reader.js +81 -0
  32. package/dist/workspace/drift-reader.schema.json +44 -0
  33. package/dist/workspace/kinds.d.ts +15 -0
  34. package/dist/workspace/kinds.d.ts.map +1 -1
  35. package/dist/workspace/kinds.js +17 -0
  36. package/dist/workspace/workspace-kinds.schema.json +23 -0
  37. package/package.json +1 -1
  38. package/src/ci-comment-commands.test.ts +147 -0
  39. package/src/ci-comment-commands.ts +29 -1
  40. package/src/ci-note-commands.ts +12 -2
  41. package/src/ci-product.ts +5 -4
  42. package/src/cli/handlers/pr-comment.ts +10 -4
  43. package/src/components/product-pipeline.ts +4 -2
  44. package/src/components/product-plan.ts +9 -2
  45. package/src/floor-table.data.ts +10 -7
  46. package/src/op/before-merge-decide.ts +74 -2
  47. package/src/op/op-waves-remainder.test.ts +2 -3
  48. package/src/op/op-waves-render-spec.test.ts +1 -2
  49. package/src/op/op-waves-split-resume.test.ts +2 -3
  50. package/src/release-floors.ts +14 -5
  51. package/src/workspace/drift-cli.ts +53 -4
  52. package/src/workspace/drift-reader.schema.json +44 -0
  53. package/src/workspace/drift-reader.test.ts +192 -0
  54. package/src/workspace/drift-reader.ts +104 -0
  55. package/src/workspace/kinds.ts +32 -1
  56. package/src/workspace/workspace-kinds.schema.json +23 -0
@@ -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
@@ -1 +1 @@
1
- {"version":3,"file":"drift-cli.d.ts","sourceRoot":"","sources":["../../src/workspace/drift-cli.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;AAKH,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E,MAAM,CAAC;IACd,uBAAuB;IACvB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE;QAAE,IAAI,EAAE,cAAc,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC;CACnD,CAAC;AAEF,MAAM,WAAW,UAAU;IACzB,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,8EAA8E;IAC9E,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,UAAU,CAAC,EAAE,OAAO,CAAC;CACtB;AAED,MAAM,MAAM,eAAe,GAAG;IAAE,KAAK,EAAE,SAAS,EAAE,CAAA;CAAE,GAAG;IAAE,KAAK,EAAE;QAAE,IAAI,EAAE,cAAc,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAA;CAAE,CAAC;AAuH5G;;;GAGG;AACH,wBAAsB,kBAAkB,CAAC,KAAK,EAAE,UAAU,GAAG,OAAO,CAAC,eAAe,CAAC,CA+FpF;AAED,sFAAsF;AACtF,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,eAAe,GAAG,sBAAsB,CAQjG;AAED,wBAAsB,iBAAiB,CAAC,GAAG,EAAE,cAAc,GAAG,OAAO,CAAC,MAAM,CAAC,CAuC5E"}
@@ -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
@@ -41,13 +50,15 @@
41
50
  * prints nothing on stdout in stream mode and says why on stderr.
42
51
  */
43
52
  import { existsSync } from "node:fs";
44
- import { resolve } from "node:path";
53
+ import { join, resolve } from "node:path";
45
54
  import { formatError } from "../cli/format.js";
46
55
  import { graphNodeFor } from "../change-set-graph.js";
47
56
  import { componentStatusDriftRecords, countDriftStatuses, decodeDriftLines, DRIFT_READS, DRIFT_SCHEMA_ID, DRIFT_VERSION, driftExpected, driftPlanner, driftRecordLine, driftSettle, driftStart, encodeDriftLines, foldDriftLines, lexiconDriftRecords, } from "../drift-record.js";
48
57
  import { readDeclaration, readerVersion, WORKSPACE_ERROR_CODES, WorkspaceReadError } from "./declaration.js";
58
+ import { readDriftWithModule } from "./drift-reader.js";
49
59
  import { prepareKindReaders } from "./kind-readers.js";
50
- import { loadKindRegistry } from "./kinds.js";
60
+ import { loadKindRegistry, substituteGraphConfig } from "./kinds.js";
61
+ import { memberReason } from "./ls.js";
51
62
  import { emitDocument, executePlan, planMembers } from "./member-commands.js";
52
63
  import { handToRootChant, locateWorkspace } from "./which-chant.js";
53
64
  /** The version of the read contract the document is written under. */
@@ -96,6 +107,33 @@ class DriftReadFailure extends Error {
96
107
  function tail(text) {
97
108
  return text.trim().split("\n").slice(-5).join("\n");
98
109
  }
110
+ /** Read a member through its kind's drift reader module (#5068): the lines it returns, checked, or a failure. */
111
+ async function kindReaderLines(query, entry, drift, root) {
112
+ if (query.read !== undefined && !DRIFT_READS.includes(query.read)) {
113
+ throw new DriftReadFailure("read-unsupported", `--read ${query.read} is not a drift read; the reads are ${DRIFT_READS.join(", ")}`);
114
+ }
115
+ const abs = entry.dir === "." ? root : join(root, entry.dir);
116
+ const config = substituteGraphConfig(drift.config, { member: entry.name, dir: abs, workspace: root });
117
+ const answer = await readDriftWithModule(drift.readerFile, {
118
+ dir: typeof config.dir === "string" ? config.dir : abs,
119
+ config,
120
+ member: entry.name,
121
+ observedAt: new Date().toISOString(),
122
+ ...(query.read !== undefined ? { read: query.read } : {}),
123
+ ...(query.resource !== undefined ? { resource: query.resource } : {}),
124
+ ...(query.stack !== undefined ? { stack: query.stack } : {}),
125
+ });
126
+ if ("error" in answer)
127
+ throw new DriftReadFailure("command-failed", `${query.member}: ${answer.error}`);
128
+ if ("refused" in answer)
129
+ throw new DriftReadFailure(answer.refused.code, `${query.member}: ${answer.refused.message}`);
130
+ return answer.lines;
131
+ }
132
+ /** The kinds `workspace drift` reads, for the no-drift-read message: the table's, and each loaded kind with a drift reader. */
133
+ function driftKinds(kinds) {
134
+ const readers = kinds.names().filter((k) => kinds.get(k)?.drift?.readerFile && !DRIFT_READS_BY_KIND[k]);
135
+ return [...Object.keys(DRIFT_READS_BY_KIND), ...readers].join(", ");
136
+ }
99
137
  /** The member's node ids, without the member in front, from its source graph; null when it can't be read. */
100
138
  async function memberGraph(cwd, member) {
101
139
  try {
@@ -189,9 +227,21 @@ export async function readWorkspaceDrift(query) {
189
227
  if (!entry) {
190
228
  throw new DriftReadFailure("member-required", `--member ${query.member} is not a member of ${declaration.name}; it declares ${declaration.members.map((m) => m.name).join(", ")}`);
191
229
  }
230
+ const { registry: kinds, problems } = loadKindRegistry(declaration.pins, located.rootOnDisk);
231
+ const drift = kinds.get(entry.kind)?.drift;
232
+ if (drift?.readerFile) {
233
+ // A kind's own drift reader (#5068), imported here: no reader project, and the member's graph places its records as for any member.
234
+ const reason = memberReason(entry, located.tree, kinds);
235
+ if (reason)
236
+ throw new DriftReadFailure("command-failed", `${query.member}: ${reason.code}: ${reason.message}`);
237
+ const [graph, lines] = await Promise.all([memberGraph(query.cwd, query.member), kindReaderLines(query, entry, drift, located.rootOnDisk)]);
238
+ return { lines: placeLines(lines, query.member, graph) };
239
+ }
192
240
  const reads = DRIFT_READS_BY_KIND[entry.kind];
193
- if (!reads)
194
- 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(", ")}`);
241
+ if (!reads) {
242
+ const problem = problems.find((p) => p.message.includes(`kind ${entry.kind} names drift reader`));
243
+ 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}` : ""}`);
244
+ }
195
245
  if (query.read !== undefined && !DRIFT_READS.includes(query.read)) {
196
246
  throw new DriftReadFailure("read-unsupported", `--read ${query.read} is not a drift read; the reads are ${DRIFT_READS.join(", ")}`);
197
247
  }
@@ -208,7 +258,6 @@ export async function readWorkspaceDrift(query) {
208
258
  throw new DriftReadFailure("read-unsupported", "--stack needs a stack name");
209
259
  if (entry.kind === "chant" && !query.env)
210
260
  throw new DriftReadFailure("env-required", `${query.member} is a chant member, read live through chant lifecycle diff <env> --live: add --env <env>`);
211
- const { registry: kinds, problems } = loadKindRegistry(declaration.pins, located.rootOnDisk);
212
261
  const plan = planMembers("graph", located.rootOnDisk, { only: [query.member], tree: located.tree, kinds, kindProblems: problems.map((p) => p.message) });
213
262
  const notRun = [...plan.unreadable, ...plan.skipped].find((s) => s.name === query.member);
214
263
  if (notRun)
@@ -0,0 +1,60 @@
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
+ import { type DriftRead, type ReadDriftResult } from "../drift-record.js";
25
+ /** The schema a drift reader's output holds to. */
26
+ export declare const DRIFT_READER_SCHEMA_ID = "https://intentius.io/chant/schemas/workspace/drift-reader/v1/drift-reader.schema.json";
27
+ /** What a drift reader module's default export is called with. */
28
+ export interface DriftReaderInput {
29
+ /** The member's directory, absolute: the kind config's `dir` when it sets one as a string, else the member's own directory. */
30
+ dir: string;
31
+ /** The kind's `drift.config`, with `{member}`, `{dir}` and `{workspace}` substituted. */
32
+ config: Record<string, unknown>;
33
+ /** The workspace member the records are for. chant puts this name on every line whatever the reader writes. */
34
+ member: string;
35
+ /** RFC 3339, the `observedAt` to give every record the reader builds. */
36
+ observedAt: string;
37
+ /** `--read`, when given. Unset, the reader's default read. */
38
+ read?: DriftRead;
39
+ /** `--resource`, when given: one address to read. */
40
+ resource?: string;
41
+ /** `--stack`, when given. */
42
+ stack?: string;
43
+ }
44
+ /** What a drift reader module returns: the same answer as a lexicon's `readDrift`. */
45
+ export type DriftReaderOutput = ReadDriftResult;
46
+ /** A drift reader module's default export. */
47
+ export type DriftReader = (input: DriftReaderInput) => DriftReaderOutput | Promise<DriftReaderOutput>;
48
+ /**
49
+ * Check what a reader returned: each line through the drift codec, a
50
+ * refusal's code against the closed list. `error` says why it is not an
51
+ * answer.
52
+ */
53
+ export declare function checkDriftReaderOutput(out: unknown): DriftReaderOutput | {
54
+ error: string;
55
+ };
56
+ /** Import the module and call it, or say why not. Never throws. */
57
+ export declare function readDriftWithModule(module: string, input: DriftReaderInput): Promise<DriftReaderOutput | {
58
+ error: string;
59
+ }>;
60
+ //# sourceMappingURL=drift-reader.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"drift-reader.d.ts","sourceRoot":"","sources":["../../src/workspace/drift-reader.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAIH,OAAO,EAAmC,KAAK,SAAS,EAA6B,KAAK,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAEnI,mDAAmD;AACnD,eAAO,MAAM,sBAAsB,0FAA0F,CAAC;AAE9H,kEAAkE;AAClE,MAAM,WAAW,gBAAgB;IAC/B,+HAA+H;IAC/H,GAAG,EAAE,MAAM,CAAC;IACZ,yFAAyF;IACzF,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAChC,+GAA+G;IAC/G,MAAM,EAAE,MAAM,CAAC;IACf,yEAAyE;IACzE,UAAU,EAAE,MAAM,CAAC;IACnB,8DAA8D;IAC9D,IAAI,CAAC,EAAE,SAAS,CAAC;IACjB,qDAAqD;IACrD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,6BAA6B;IAC7B,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,sFAAsF;AACtF,MAAM,MAAM,iBAAiB,GAAG,eAAe,CAAC;AAEhD,8CAA8C;AAC9C,MAAM,MAAM,WAAW,GAAG,CAAC,KAAK,EAAE,gBAAgB,KAAK,iBAAiB,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAAC;AAMtG;;;;GAIG;AACH,wBAAgB,sBAAsB,CAAC,GAAG,EAAE,OAAO,GAAG,iBAAiB,GAAG;IAAE,KAAK,EAAE,MAAM,CAAA;CAAE,CAmB1F;AAED,mEAAmE;AACnE,wBAAsB,mBAAmB,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,gBAAgB,GAAG,OAAO,CAAC,iBAAiB,GAAG;IAAE,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC,CAiBjI"}
@@ -0,0 +1,81 @@
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
+ import { isAbsolute } from "node:path";
25
+ import { pathToFileURL } from "node:url";
26
+ import { decodeDriftLine } from "../drift-record.js";
27
+ /** The schema a drift reader's output holds to. */
28
+ export const DRIFT_READER_SCHEMA_ID = "https://intentius.io/chant/schemas/workspace/drift-reader/v1/drift-reader.schema.json";
29
+ const REFUSAL_CODES = ["read-unsupported", "resource-unsupported", "no-drift-read"];
30
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
31
+ /**
32
+ * Check what a reader returned: each line through the drift codec, a
33
+ * refusal's code against the closed list. `error` says why it is not an
34
+ * answer.
35
+ */
36
+ export function checkDriftReaderOutput(out) {
37
+ if (!isObject(out))
38
+ return { error: "returned something that is not an object with lines or refused" };
39
+ if ("refused" in out) {
40
+ const refused = out.refused;
41
+ if (!isObject(refused) || !REFUSAL_CODES.includes(refused.code) || typeof refused.message !== "string" || refused.message === "") {
42
+ return { error: `returned a refusal that is not { code: ${REFUSAL_CODES.join(" | ")}, message }` };
43
+ }
44
+ return { refused: { code: refused.code, message: refused.message } };
45
+ }
46
+ if (!Array.isArray(out.lines))
47
+ return { error: "returned something with no lines array and no refusal" };
48
+ const lines = [];
49
+ for (const [i, line] of out.lines.entries()) {
50
+ try {
51
+ lines.push(decodeDriftLine(JSON.stringify(line)));
52
+ }
53
+ catch (err) {
54
+ return { error: `returned a line ${i} that is not drift: ${err instanceof Error ? err.message : String(err)}` };
55
+ }
56
+ }
57
+ return { lines };
58
+ }
59
+ /** Import the module and call it, or say why not. Never throws. */
60
+ export async function readDriftWithModule(module, input) {
61
+ if (!isAbsolute(module))
62
+ return { error: `drift reader ${module} must be an absolute path` };
63
+ let read;
64
+ try {
65
+ read = (await import(pathToFileURL(module).href)).default;
66
+ }
67
+ catch (err) {
68
+ return { error: `drift reader ${module} could not be loaded: ${err instanceof Error ? err.message : String(err)}` };
69
+ }
70
+ if (typeof read !== "function")
71
+ return { error: `drift reader ${module} has no default export function` };
72
+ let out;
73
+ try {
74
+ out = await read(input);
75
+ }
76
+ catch (err) {
77
+ return { error: `drift reader ${module} failed: ${err instanceof Error ? err.message : String(err)}` };
78
+ }
79
+ const checked = checkDriftReaderOutput(out);
80
+ return "error" in checked ? { error: `drift reader ${module} ${checked.error}` } : checked;
81
+ }
@@ -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
+ }
@@ -144,6 +144,19 @@ export interface KindGraph {
144
144
  readerFile?: string;
145
145
  config: Record<string, unknown>;
146
146
  }
147
+ /**
148
+ * How `chant workspace drift --member` reads a member of a package's kind
149
+ * (#5068): a drift reader module the package ships, and the config it is
150
+ * called with. See `./drift-reader.ts` for the contract and
151
+ * {@link substituteGraphConfig} for the placeholders.
152
+ */
153
+ export interface KindDrift {
154
+ /** The drift reader module, as the kinds file names it: a path inside the supplying package. */
155
+ reader: string;
156
+ /** The reader module, absolute; set once the package directory is known. */
157
+ readerFile?: string;
158
+ config: Record<string, unknown>;
159
+ }
147
160
  export interface MemberKind {
148
161
  name: string;
149
162
  /** One line for listings and error messages. */
@@ -165,6 +178,8 @@ export interface MemberKind {
165
178
  packageDir?: string;
166
179
  /** How `workspace graph` reads a member of this kind (#2874); unset, the member is `kind-not-run`. */
167
180
  graph?: KindGraph;
181
+ /** How `workspace drift` reads a member of this kind (#5068); unset, the member answers `no-drift-read` unless chant reads its kind itself. */
182
+ drift?: KindDrift;
168
183
  /** The fields a member entry of this kind may set, with their defaults (#3151); unset, the kind declares none. */
169
184
  fields?: Record<string, KindField>;
170
185
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"kinds.d.ts","sourceRoot":"","sources":["../../src/workspace/kinds.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAKH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AAG5C,OAAO,EAAmC,oBAAoB,EAAE,MAAM,cAAc,CAAC;AAIrF,eAAO,MAAM,eAAe,QAAa,CAAC;AAE1C,oDAAoD;AACpD,eAAO,MAAM,aAAa,sBAAsB,CAAC;AAEjD;;;;;;GAMG;AACH,MAAM,WAAW,SAAS;IACxB,yEAAyE;IACzE,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IACnB;;;;;OAKG;IACH,QAAQ,CAAC,EAAE;QAAE,EAAE,EAAE,MAAM,EAAE,CAAC;QAAC,MAAM,EAAE,MAAM,EAAE,CAAA;KAAE,CAAC;IAC9C;;;;;OAKG;IACH,UAAU,CAAC,EAAE;QAAE,EAAE,EAAE,MAAM,EAAE,CAAC;QAAC,QAAQ,EAAE,MAAM,EAAE,CAAA;KAAE,CAAC;IAClD;;;;;OAKG;IACH,OAAO,CAAC,EAAE;QAAE,EAAE,EAAE,MAAM,EAAE,CAAC;QAAC,MAAM,EAAE,MAAM,EAAE,CAAA;KAAE,CAAC;IAC7C;;;;;;;;;;OAUG;IACH,WAAW,CAAC,EAAE;QAAE,EAAE,EAAE,MAAM,EAAE,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,EAAE,CAAA;KAAE,CAAC;CACnE;AAED,kFAAkF;AAClF,MAAM,WAAW,eAAe;IAC9B,IAAI,EAAE,QAAQ,GAAG,SAAS,GAAG,SAAS,CAAC;IACvC,WAAW,EAA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AE,OAAO,EACZ,aAAa,EAAE,MAAM,EACrB,MAAM,GAAE,MAAsB,GAC7B;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,OAAO,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAsB9D;AAED;;;;;;;;GAQG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,SAAS,OAAO,EAAE,EAAE,aAAa,EAAE,MAAM,GAAG,WAAW,CA4B7F;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,UAAU,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAcxE;AAID,6EAA6E;AAC7E,MAAM,MAAM,UAAU,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC;AAyCnD,sGAAsG;AACtG,MAAM,WAAW,kBAAkB;IACjC,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,YAAY;IAC3B,uIAAuI;IACvI,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,UAAU,GAAG,IAAI,GAAG,MAAM,CAAC,MAAM,EAAE,UAAU,GAAG,IAAI,CAAC,CAAC,GAAG,IAAI,CAAC;IACrF,QAAQ,EAAE,kBAAkB,EAAE,CAAC;CAChC;AAED;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,UAAU,GAAG,SAAS,EAAE,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,GAAG,YAAY,CAsCrH"}
@@ -351,6 +351,7 @@ export function parseKindData(text, source) {
351
351
  ...(k.graph
352
352
  ? { graph: { ...(k.graph.lexicon ? { lexicon: k.graph.lexicon } : {}), ...(k.graph.reader ? { reader: k.graph.reader } : {}), config: structuredClone(k.graph.config ?? {}) } }
353
353
  : {}),
354
+ ...(k.drift ? { drift: { reader: k.drift.reader, config: structuredClone(k.drift.config ?? {}) } } : {}),
354
355
  ...(k.fields ? { fields: structuredClone(k.fields) } : {}),
355
356
  ...(k.reader && KIND_LINK_READERS.includes(k.reader) ? { reader: k.reader } : {}),
356
357
  ...(k.memberFile ? { memberFile: { path: k.memberFile.path, schema: k.memberFile.schema } } : {}),
@@ -430,6 +431,22 @@ export function readPackageKinds(packageDir, source) {
430
431
  `and this package is ${packageName ?? "unnamed"}; the kind is kept, and workspace graph lists its members with kind-not-run`);
431
432
  delete k.graph;
432
433
  }
434
+ if (k.drift) {
435
+ // A drift reader module (#5068) is the package's own file, like a graph reader: inside the package and present. Nothing is imported here.
436
+ const file = resolve(packageDir, ...k.drift.reader.split("/"));
437
+ const inside = relative(packageDir, file);
438
+ if (inside.startsWith("..") || isAbsolute(inside)) {
439
+ 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`);
440
+ delete k.drift;
441
+ }
442
+ else if (!existsSync(file)) {
443
+ 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`);
444
+ delete k.drift;
445
+ }
446
+ else {
447
+ k.drift.readerFile = file;
448
+ }
449
+ }
433
450
  }
434
451
  return { ...data, file };
435
452
  }
@@ -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.",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@intentius/chant",
3
- "version": "0.124.94",
3
+ "version": "0.124.96",
4
4
  "description": "Declarative infrastructure-as-code toolkit — TypeScript on Node.js",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://intentius.io/chant",
@@ -451,3 +451,150 @@ describe("the comment job's apply before merge on the waves (#4984)", () => {
451
451
  expect(() => commentJobsFromEnv(JSON.stringify({ ...jobs, wavesBeforeMerge: { ...bm, requires: ["green"] } }))).toThrow("requires is a list of approved, mergeable, undiverged, checks");
452
452
  });
453
453
  });
454
+
455
+ describe("lock and unlock before merge, by the reach line (#5061)", () => {
456
+ const bm = { workflow: "tf-apply.yml", plan: ["terragucci/plan"], pipelineFiles: [".github/workflows/"], locks: { gate: "tf-apply" } };
457
+ const jobs: CommentJobs = { applyOnMerge: true, waves: { op: "tf-apply", count: 2 }, wavesBeforeMerge: bm };
458
+
459
+ /** A checkout of the default branch whose origin is itself, so the base fetch works. */
460
+ async function checkout() {
461
+ const { spawnSync } = await import("node:child_process");
462
+ const { mkdtempSync, writeFileSync } = await import("node:fs");
463
+ const { tmpdir } = await import("node:os");
464
+ const { join } = await import("node:path");
465
+ const dir = mkdtempSync(join(tmpdir(), "chant-cc-locks-"));
466
+ const git = (...args: string[]) => {
467
+ const r = spawnSync("git", args, { cwd: dir, encoding: "utf-8", env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" } });
468
+ if (r.status !== 0) throw new Error(r.stderr);
469
+ return r.stdout.trim();
470
+ };
471
+ git("init", "-q", "-b", "main");
472
+ writeFileSync(join(dir, "main.tf"), "1");
473
+ git("add", ".");
474
+ git("commit", "-q", "-m", "base");
475
+ git("remote", "add", "origin", dir);
476
+ const run: NonNullable<AnswerCommentOptions["beforeMerge"]>["git"] = (argv, o) => {
477
+ const r = spawnSync(argv[0]!, argv.slice(1), { encoding: "utf8", ...(o.cwd ? { cwd: o.cwd } : {}) });
478
+ return { status: r.status, stdout: r.stdout ?? "", stderr: r.stderr ?? "" };
479
+ };
480
+ return { dir, baseSha: git("rev-parse", "HEAD"), git: run };
481
+ }
482
+
483
+ /** The comment job with the lock and unlock the handler gives it, each call kept. */
484
+ async function locking(body: string, o: { forge?: "github" | "forgejo"; pr?: Partial<PullRequestDetail>; jobs?: CommentJobs; held?: string; released?: string[]; reached?: string[]; permission?: string; event?: Record<string, unknown> } = {}) {
485
+ const c = await checkout();
486
+ const head = "c".repeat(40);
487
+ const s = setup({ pr: { state: "open", headSha: head, mergeCommit: undefined, ...o.pr }, ...(o.permission ? { permission: o.permission } : {}) }, o.jobs ?? jobs, body, { ...(o.forge ? { forge: o.forge } : {}), ...(o.event ? { event: o.event } : {}) });
488
+ const locked: Array<[number, string, string, string, string | undefined]> = [];
489
+ const unlocked: number[] = [];
490
+ const got = await answerProductComment({
491
+ ...s.opts,
492
+ beforeMerge: {
493
+ requires: async () => null,
494
+ statuses: async () => [],
495
+ git: c.git,
496
+ cwd: c.dir,
497
+ lock: async (pr, h, base, by, asked) => {
498
+ locked.push([pr, h, base, by, asked]);
499
+ return o.held ? { ok: false, text: o.held } : { ok: true, targets: o.reached ?? ["envs/dev", "envs/prod"] };
500
+ },
501
+ unlock: async (pr) => (unlocked.push(pr), o.released ?? ["envs/dev"]),
502
+ record: async () => {
503
+ throw new Error("a lock records no decision");
504
+ },
505
+ stop: async () => {
506
+ throw new Error("a lock writes no wave stop");
507
+ },
508
+ },
509
+ });
510
+ return { got, posted: s.posted, locked, unlocked, dispatched: s.dispatched, head, baseSha: c.baseSha };
511
+ }
512
+
513
+ for (const forge of ["github", "forgejo"] as const) {
514
+ test(`${forge}: /terragucci lock takes the locks of what the reach line prints, measured from the default branch, and applies nothing`, async () => {
515
+ const r = await locking("/terragucci lock", { forge });
516
+ expect(r.locked).toEqual([[12, r.head, r.baseSha, "alice", "lock"]]);
517
+ expect(r.dispatched).toEqual([]);
518
+ expect(r.got).toMatchObject({ command: "lock", ran: false, replied: true });
519
+ expect(r.posted).toEqual([`terragucci: locked \`envs/dev\`, \`envs/prod\` for pull request 12 at ${r.head.slice(0, 8)} for alice, and nothing is applied; the locks hold until it merges or closes, or \`/terragucci unlock\` releases them`]);
520
+ });
521
+
522
+ test(`${forge}: a lock another open pull request holds is refused with its holder named`, async () => {
523
+ const held = "`envs/dev` is locked by pull request 9 (alice, apply), so pull request 12 takes no lock. It can once that pull request merges or closes, or someone with write access unlocks it";
524
+ const r = await locking("/terragucci lock", { forge, held });
525
+ expect(r.posted).toEqual([`terragucci: ${held}`]);
526
+ expect(r.got.fail).toBeUndefined();
527
+ });
528
+
529
+ test(`${forge}: /terragucci unlock releases the pull request's locks`, async () => {
530
+ const r = await locking("/terragucci unlock", { forge });
531
+ expect(r.unlocked).toEqual([12]);
532
+ expect(r.locked).toEqual([]);
533
+ expect(r.posted).toEqual(["terragucci: released `envs/dev`, which pull request 12 held, for alice"]);
534
+ const none = await locking("/terragucci unlock", { forge, released: [] });
535
+ expect(none.posted).toEqual(["terragucci: pull request 12 holds no lock, so there is nothing to unlock"]);
536
+ });
537
+
538
+ test(`${forge}: a fork is refused, and someone without write access gets nothing`, async () => {
539
+ const fork = await locking("/terragucci lock", { forge, pr: { sameRepo: false } });
540
+ expect(fork.locked).toEqual([]);
541
+ expect(fork.posted).toEqual([`terragucci: ${tgInput.replies!.fork}`]);
542
+ const forkUnlock = await locking("/terragucci unlock", { forge, pr: { sameRepo: false } });
543
+ expect(forkUnlock.unlocked).toEqual([]);
544
+ const reader = await locking("/terragucci lock", forge === "github" ? { forge, permission: "read" } : { forge, event: { repository: { full_name: "acme/infra", default_branch: "main", permissions: { push: false } } } });
545
+ expect(reader.locked).toEqual([]);
546
+ expect(reader.posted).toEqual([]);
547
+ expect(reader.got.replied).toBe(false);
548
+ });
549
+ }
550
+
551
+ test("a closed pull request takes no lock, one into another branch neither, and reaching nothing locks nothing", async () => {
552
+ expect((await locking("/terragucci lock", { pr: { state: "closed" } })).posted).toEqual(["terragucci: pull request 12 is not open, so it takes no lock"]);
553
+ expect((await locking("/terragucci lock", { pr: { base: "release" } })).posted).toEqual(["terragucci: pull request 12 targets release, not the default branch main, so it takes no lock"]);
554
+ const r = await locking("/terragucci lock", { reached: [] });
555
+ expect(r.posted).toEqual([`terragucci: pull request 12 reaches nothing at ${r.head.slice(0, 8)}, so it takes no lock`]);
556
+ });
557
+
558
+ test("with the comment lock jobs of locks: \"plan\", or without the reach line, nothing changes", async () => {
559
+ const planLocks = await locking("/terragucci lock", { jobs: { ...jobs, locks: true } });
560
+ expect(planLocks.got).toMatchObject({ replied: false, reason: "another job answers this comment" });
561
+ expect(planLocks.locked).toEqual([]);
562
+ const { locks: _l, ...noReach } = bm;
563
+ const without = await locking("/terragucci unlock", { jobs: { ...jobs, wavesBeforeMerge: noReach } });
564
+ expect(without.unlocked).toEqual([]);
565
+ expect(without.posted).toEqual([`terragucci: ${tgInput.replies!.unlock}`]);
566
+ });
567
+
568
+ test("GitLab's note poll locks and unlocks the same way through chantNoteRuns", async () => {
569
+ const c = await checkout();
570
+ const head = "d".repeat(40);
571
+ const mr: PullRequestDetail = { number: 3, title: "", body: "", state: "open", head: "feature", headSha: head, base: "main", sameRepo: true };
572
+ const locked: unknown[] = [];
573
+ const unlocked: number[] = [];
574
+ const deps = {
575
+ requires: async () => null,
576
+ statuses: async () => [],
577
+ git: c.git,
578
+ cwd: c.dir,
579
+ lock: async (pr: number, h: string, base: string, by: string, asked?: "apply" | "lock") => (locked.push([pr, h, base, by, asked]), { ok: true as const, targets: ["envs/dev"] }),
580
+ unlock: async (pr: number) => (unlocked.push(pr), ["envs/dev"]),
581
+ record: async () => {
582
+ throw new Error("no decision");
583
+ },
584
+ stop: async () => {},
585
+ };
586
+ const glJobs = { applyOnMerge: true, waves: { op: "tf-apply", count: 2 }, wavesBeforeMerge: { plan: ["terragucci/plan"], pipelineFiles: [".gitlab-ci.yml"], locks: { gate: "tf-apply" } } };
587
+ const runs = chantNoteRuns(glJobs, { beforeMerge: deps });
588
+ const ask = (body: string, m = mr): Omit<NoteCommand, "parsed"> => ({ mr: m, note: { id: 41, body, system: false, author: "bob" }, role: "developer", base: "main", words: tg });
589
+ expect(await runs({ ...ask("/terragucci lock"), parsed: { kind: "lock" } })).toEqual({ kind: "reply", text: `locked \`envs/dev\` for !3 at ${head.slice(0, 8)} for bob, and nothing is applied; the locks hold until it merges or closes, or \`/terragucci unlock\` releases them` });
590
+ expect(locked).toEqual([[3, head, c.baseSha, "bob", "lock"]]);
591
+ expect(await runs({ ...ask("/terragucci unlock"), parsed: { kind: "unlock" } })).toEqual({ kind: "reply", text: "released `envs/dev`, which !3 held, for bob" });
592
+ expect(unlocked).toEqual([3]);
593
+ expect(await runs({ ...ask("/terragucci lock", { ...mr, sameRepo: false }), parsed: { kind: "lock" } })).toEqual({ kind: "reply", text: tgInput.replies!.fork });
594
+ // With locks: "plan" the lock job runs, as before; without the reach line the product's sentence.
595
+ expect((await chantNoteRuns({ ...glJobs, locks: true }, { beforeMerge: deps })({ ...ask("/terragucci lock"), parsed: { kind: "lock" } })).kind).toBe("pipeline");
596
+ const { lock: _lock, unlock: _unlock, ...noReach } = deps;
597
+ expect(await chantNoteRuns(glJobs, { beforeMerge: noReach })({ ...ask("/terragucci lock"), parsed: { kind: "lock" } })).toEqual({ kind: "reply", text: tgInput.replies!.lock });
598
+ expect(locked).toHaveLength(1);
599
+ });
600
+ });