@intentius/chant 0.124.56 → 0.124.57

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 (93) hide show
  1. package/dist/ci-audit/index.d.ts.map +1 -1
  2. package/dist/ci-audit/index.js +1 -2
  3. package/dist/ci-product.d.ts.map +1 -1
  4. package/dist/ci-product.js +4 -5
  5. package/dist/cli/handlers/lifecycle.d.ts.map +1 -1
  6. package/dist/cli/handlers/lifecycle.js +14 -0
  7. package/dist/cli/handlers/pr.d.ts.map +1 -1
  8. package/dist/cli/handlers/pr.js +90 -35
  9. package/dist/components/auto-release.d.ts +5 -2
  10. package/dist/components/auto-release.d.ts.map +1 -1
  11. package/dist/components/auto-release.js +9 -4
  12. package/dist/components/capability.d.ts +10 -0
  13. package/dist/components/capability.d.ts.map +1 -1
  14. package/dist/components/deploy-units.d.ts +12 -0
  15. package/dist/components/deploy-units.d.ts.map +1 -1
  16. package/dist/components/deploy-units.js +20 -1
  17. package/dist/components/pr-pipeline.d.ts +8 -2
  18. package/dist/components/pr-pipeline.d.ts.map +1 -1
  19. package/dist/components/pr-pipeline.js +11 -3
  20. package/dist/components/row-lease.d.ts +22 -1
  21. package/dist/components/row-lease.d.ts.map +1 -1
  22. package/dist/components/row-lease.js +32 -6
  23. package/dist/e2e-harness/index.d.ts.map +1 -1
  24. package/dist/e2e-harness/index.js +1 -2
  25. package/dist/lexicon.d.ts +9 -0
  26. package/dist/lexicon.d.ts.map +1 -1
  27. package/dist/lifecycle/git.d.ts +39 -3
  28. package/dist/lifecycle/git.d.ts.map +1 -1
  29. package/dist/lifecycle/git.js +223 -15
  30. package/dist/lifecycle/lock-rows.d.ts +23 -0
  31. package/dist/lifecycle/lock-rows.d.ts.map +1 -1
  32. package/dist/lifecycle/lock-rows.js +47 -8
  33. package/dist/lifecycle/resource-lock.d.ts +70 -0
  34. package/dist/lifecycle/resource-lock.d.ts.map +1 -1
  35. package/dist/lifecycle/resource-lock.js +241 -5
  36. package/dist/op/gate.js +21 -4
  37. package/dist/op/op-waves-release-port.js +1 -1
  38. package/dist/op/op-waves-release.d.ts +2 -1
  39. package/dist/op/op-waves-release.d.ts.map +1 -1
  40. package/dist/op/op-waves-run.d.ts +8 -0
  41. package/dist/op/op-waves-run.d.ts.map +1 -1
  42. package/dist/op/op-waves-run.js +101 -29
  43. package/dist/op/op-waves.d.ts +18 -0
  44. package/dist/op/op-waves.d.ts.map +1 -1
  45. package/dist/op/op-waves.js +16 -0
  46. package/dist/pr-loop.d.ts.map +1 -1
  47. package/dist/pr-loop.js +1 -2
  48. package/dist/release-floors.d.ts +1 -1
  49. package/dist/release-floors.js +1 -1
  50. package/dist/wave-runtime.mjs +310 -300
  51. package/package.json +1 -1
  52. package/src/ci-audit/index.ts +1 -2
  53. package/src/ci-product.ts +4 -5
  54. package/src/cli/handlers/lifecycle.ts +13 -0
  55. package/src/cli/handlers/pr-before-merge.test.ts +1 -1
  56. package/src/cli/handlers/pr-deploy-inputs.test.ts +1 -1
  57. package/src/cli/handlers/pr-endpoint.test.ts +1 -1
  58. package/src/cli/handlers/pr-green.test.ts +1 -1
  59. package/src/cli/handlers/pr-plan-comment-targets.test.ts +1 -1
  60. package/src/cli/handlers/pr-plan-flags.test.ts +1 -1
  61. package/src/cli/handlers/pr-plan-targets.test.ts +1 -1
  62. package/src/cli/handlers/pr-record.test.ts +34 -2
  63. package/src/cli/handlers/pr-waves-blocked.test.ts +1 -1
  64. package/src/cli/handlers/pr-waves.test.ts +1 -1
  65. package/src/cli/handlers/pr.test.ts +1 -1
  66. package/src/cli/handlers/pr.ts +86 -31
  67. package/src/components/auto-release.test.ts +4 -2
  68. package/src/components/auto-release.ts +9 -5
  69. package/src/components/capability.ts +10 -0
  70. package/src/components/deploy-units.test.ts +18 -1
  71. package/src/components/deploy-units.ts +26 -1
  72. package/src/components/pr-pipeline.ts +12 -3
  73. package/src/components/row-lease.test.ts +61 -1
  74. package/src/components/row-lease.ts +48 -7
  75. package/src/e2e-harness/index.ts +1 -2
  76. package/src/lexicon.ts +9 -0
  77. package/src/lifecycle/git.test.ts +155 -0
  78. package/src/lifecycle/git.ts +213 -17
  79. package/src/lifecycle/lock-rows.test.ts +6 -1
  80. package/src/lifecycle/lock-rows.ts +58 -7
  81. package/src/lifecycle/resource-lock-wait.test.ts +292 -0
  82. package/src/lifecycle/resource-lock.ts +261 -7
  83. package/src/op/gate.test.ts +7 -5
  84. package/src/op/gate.ts +20 -4
  85. package/src/op/op-waves-after-plan.test.ts +1 -2
  86. package/src/op/op-waves-ledger-lock.test.ts +208 -0
  87. package/src/op/op-waves-release-port.ts +1 -1
  88. package/src/op/op-waves-release.ts +1 -1
  89. package/src/op/op-waves-run.ts +104 -29
  90. package/src/op/op-waves.ts +18 -0
  91. package/src/pr-loop-bundle.test.ts +0 -2
  92. package/src/pr-loop.ts +1 -2
  93. package/src/release-floors.ts +1 -1
@@ -4,6 +4,8 @@
4
4
  * All operations use git plumbing commands — no checkout, no branch switching,
5
5
  * no working tree changes.
6
6
  */
7
+ import { unlinkSync } from "node:fs";
8
+ import { isAbsolute, join } from "node:path";
7
9
  import { getRuntime } from "../runtime-adapter";
8
10
  import { memberLedgerPrefix, resolveMemberLedger } from "./member-ledger";
9
11
  import { LIFECYCLE_LOCAL_NOTE } from "./local-note";
@@ -896,24 +898,208 @@ export function describeLifecyclePush(result: LifecyclePushStatus): string | nul
896
898
  */
897
899
  export async function pushLifecycleReport(opts?: { cwd?: string }): Promise<{ pushed: boolean; pushWarning?: string }> {
898
900
  try {
899
- const result = await pushLifecycleStatus(opts);
900
- switch (result.status) {
901
- case "pushed":
902
- return { pushed: true };
903
- case "no-remote":
904
- return { pushed: false, pushWarning: LIFECYCLE_LOCAL_NOTE };
905
- case "not-recorded":
906
- return { pushed: false, pushWarning: NO_RECORD_PUSH_NOTE };
907
- case "stale":
908
- return { pushed: false, pushWarning: new StaleLifecycleBranchError(result.expected, result.stderr).message };
909
- case "failed":
910
- return { pushed: false, pushWarning: describeLifecyclePush(result) ?? "the push did not land" };
911
- }
901
+ return pushReportOf(await pushLifecycleStatus(opts));
912
902
  } catch (err) {
913
903
  return { pushed: false, pushWarning: err instanceof Error ? err.message : String(err) };
914
904
  }
915
905
  }
916
906
 
907
+ function pushReportOf(result: LifecyclePushStatus): { pushed: boolean; pushWarning?: string } {
908
+ switch (result.status) {
909
+ case "pushed":
910
+ return { pushed: true };
911
+ case "no-remote":
912
+ return { pushed: false, pushWarning: LIFECYCLE_LOCAL_NOTE };
913
+ case "not-recorded":
914
+ return { pushed: false, pushWarning: NO_RECORD_PUSH_NOTE };
915
+ case "stale":
916
+ return { pushed: false, pushWarning: new StaleLifecycleBranchError(result.expected, result.stderr).message };
917
+ case "failed":
918
+ return { pushed: false, pushWarning: describeLifecyclePush(result) ?? "the push did not land" };
919
+ }
920
+ }
921
+
922
+ /** How many pushes {@link pushLifecycleRebasing} makes, as the snapshot store's `publishRef` does. */
923
+ export const LIFECYCLE_PUSH_TRIES = 3;
924
+
925
+ /**
926
+ * Thrown by {@link pushLifecycleRebasing} when the ledger branch did not reach
927
+ * the remote: another writer pushed before each of its tries, or this
928
+ * checkout's commits do not replay on the remote's tip. What this run wrote
929
+ * stays in this checkout's `chant/lifecycle` only.
930
+ */
931
+ export class LifecyclePushLostError extends Error {
932
+ readonly remote: string;
933
+ readonly tries: number;
934
+ constructor(remote: string, tries: number, detail: string) {
935
+ super(
936
+ `${STATE_BRANCH} was not pushed to "${remote}" after ${tries} ${tries === 1 ? "try" : "tries"}: ${detail}. ` +
937
+ `The records this run wrote are only in this checkout; run the command again.`,
938
+ );
939
+ this.name = "LifecyclePushLostError";
940
+ this.remote = remote;
941
+ this.tries = tries;
942
+ }
943
+ }
944
+
945
+ /** Scratch ref for the remote tip while {@link rebaseLifecycleOnRemote} replays onto it. */
946
+ const REBASE_REF = "refs/chant/lifecycle-rebase";
947
+
948
+ /**
949
+ * Put this checkout's `chant/lifecycle` commits that the remote lacks on top
950
+ * of the remote's tip (fetched again), and point the push's lease at that
951
+ * tip. Each commit is replayed with `git merge-tree --write-tree` against its
952
+ * own parent and keeps its author and message; nothing touches a work tree.
953
+ * Returns why it could not, such as a commit whose files the other writer
954
+ * changed too.
955
+ */
956
+ async function rebaseLifecycleOnRemote(remote: string, cwd?: string): Promise<{ error: string } | { rebased: number }> {
957
+ const rt = getRuntime();
958
+ const run = (args: string[], env: Record<string, string> = {}) => rt.spawn(["git", ...args], { cwd, env: { ...C_LOCALE_ENV, ...env } });
959
+ const firstLine = (s: string | undefined) => (s ?? "").trim().split("\n")[0] ?? "";
960
+ try {
961
+ const fetched = await run(["fetch", "--no-tags", "--force", remote, `refs/heads/${STATE_BRANCH}:${REBASE_REF}`]);
962
+ if (fetched.exitCode !== 0) return { error: `the fetch of the remote's tip failed (git said: ${firstLine(fetched.stderr)})` };
963
+ const remoteTip = (await run(["rev-parse", "--verify", REBASE_REF])).stdout.trim();
964
+ const local = await getStateBranchTip(cwd);
965
+ if (!remoteTip || !local) return { error: "the remote's tip or the local branch could not be read" };
966
+ if ((await run(["merge-base", "--is-ancestor", remoteTip, local])).exitCode === 0) {
967
+ // Already on the remote's history: only the lease was behind.
968
+ await trackRemoteLifecycle(remote, remoteTip, cwd);
969
+ return { rebased: 0 };
970
+ }
971
+ const ours = (await run(["rev-list", "--reverse", "--first-parent", local, `^${remoteTip}`])).stdout.trim().split("\n").filter(Boolean);
972
+ const identityArgs = await ledgerCommitIdentityArgs(cwd);
973
+ let onto = remoteTip;
974
+ for (const commit of ours) {
975
+ const parent = await run(["rev-parse", "--verify", "--quiet", `${commit}^1`]);
976
+ if (parent.exitCode !== 0) return { error: `${commit.slice(0, 12)} shares no history with the remote's ${STATE_BRANCH}` };
977
+ const merged = await run(["merge-tree", "--write-tree", `--merge-base=${parent.stdout.trim()}`, onto, commit]);
978
+ const subject = firstLine((await run(["log", "-1", "--format=%s", commit])).stdout);
979
+ let tree: string;
980
+ if (merged.exitCode === 1) {
981
+ // plywood#22 finding 9: two writers that each appended lines to one ledger file (a run record, a release record, a gate line) meet here.
982
+ const appended = await replayAppends(parent.stdout.trim(), commit, onto, cwd);
983
+ if ("error" in appended) return { error: `"${subject}" (${commit.slice(0, 12)}) changes files the other writer changed too: ${appended.error}` };
984
+ tree = appended.tree;
985
+ } else if (merged.exitCode !== 0) {
986
+ return { error: `git merge-tree failed on ${commit.slice(0, 12)} (git said: ${firstLine(merged.stderr)})` };
987
+ } else {
988
+ tree = firstLine(merged.stdout);
989
+ }
990
+ const [name, email, date] = (await run(["log", "-1", "--format=%an%x00%ae%x00%aI", commit])).stdout.replace(/\n$/, "").split("\0");
991
+ const message = (await run(["log", "-1", "--format=%B", commit])).stdout;
992
+ const made = await rt.spawn(["git", ...identityArgs, "commit-tree", tree, "-p", onto, "-F", "-"], {
993
+ cwd,
994
+ stdin: message,
995
+ env: { ...C_LOCALE_ENV, GIT_AUTHOR_NAME: name ?? "", GIT_AUTHOR_EMAIL: email ?? "", GIT_AUTHOR_DATE: date ?? "" },
996
+ });
997
+ if (made.exitCode !== 0) return { error: `git commit-tree failed on ${commit.slice(0, 12)} (git said: ${firstLine(made.stderr)})` };
998
+ onto = made.stdout.trim();
999
+ }
1000
+ try {
1001
+ await updateRefCAS(`refs/heads/${STATE_BRANCH}`, onto, local, { cwd });
1002
+ } catch (err) {
1003
+ if (err instanceof RefCASConflictError) return { error: `${STATE_BRANCH} moved in this checkout while it was replayed` };
1004
+ throw err;
1005
+ }
1006
+ await trackRemoteLifecycle(remote, remoteTip, cwd);
1007
+ return { rebased: ours.length };
1008
+ } finally {
1009
+ await run(["update-ref", "-d", REBASE_REF]);
1010
+ }
1011
+ }
1012
+
1013
+ /**
1014
+ * Replay a commit whose only changes are lines appended to `.jsonl` ledger
1015
+ * files, or new `.jsonl` files, onto `onto` (plywood#22 finding 9): each
1016
+ * file becomes `onto`'s copy with the commit's new lines after it, less any
1017
+ * line `onto` already holds. A run record, a release record and a gate line
1018
+ * are such appends, so two writers to one environment's file no longer lose
1019
+ * one of them on a replay. Any other change, or a file the commit rewrote
1020
+ * rather than appended to, returns why, and the replay stops as before.
1021
+ */
1022
+ async function replayAppends(parent: string, commit: string, onto: string, cwd?: string): Promise<{ tree: string } | { error: string }> {
1023
+ const rt = getRuntime();
1024
+ const run = (args: string[], opts: { env?: Record<string, string>; stdin?: string } = {}) =>
1025
+ rt.spawn(["git", ...args], { cwd, env: { ...C_LOCALE_ENV, ...(opts.env ?? {}) }, ...(opts.stdin !== undefined ? { stdin: opts.stdin } : {}) });
1026
+ const diff = await run(["diff-tree", "-r", "--no-renames", "--name-status", "-z", parent, commit]);
1027
+ if (diff.exitCode !== 0) return { error: "git diff-tree failed" };
1028
+ const fields = diff.stdout.split("\0").filter((f) => f !== "");
1029
+ const changes: Array<{ status: string; path: string }> = [];
1030
+ for (let i = 0; i + 1 < fields.length; i += 2) changes.push({ status: fields[i]!, path: fields[i + 1]! });
1031
+ if (changes.length === 0) return { error: "nothing to replay" };
1032
+ const blob = async (rev: string, path: string): Promise<string | null> => {
1033
+ const out = await run(["cat-file", "blob", `${rev}:${path}`]);
1034
+ return out.exitCode === 0 ? out.stdout : null;
1035
+ };
1036
+ const files: Array<{ path: string; content: string }> = [];
1037
+ for (const { status, path } of changes) {
1038
+ if (!path.endsWith(".jsonl") || (status !== "M" && status !== "A")) return { error: `${path} is not a ledger line file this replay appends to` };
1039
+ const ours = (await blob(commit, path)) ?? "";
1040
+ const base = status === "M" ? ((await blob(parent, path)) ?? "") : "";
1041
+ if (!ours.startsWith(base)) return { error: `${path} was rewritten, not appended to` };
1042
+ const theirs = (await blob(onto, path)) ?? "";
1043
+ const have = new Set(theirs.split("\n").filter((l) => l !== ""));
1044
+ const added = ours.slice(base.length).split("\n").filter((l) => l !== "" && !have.has(l));
1045
+ const head = theirs === "" || theirs.endsWith("\n") ? theirs : `${theirs}\n`;
1046
+ files.push({ path, content: added.length > 0 ? `${head}${added.join("\n")}\n` : theirs });
1047
+ }
1048
+ const indexPath = (await run(["rev-parse", "--git-path", `chant-lifecycle-replay-${process.pid}.index`])).stdout.trim();
1049
+ if (!indexPath) return { error: "no scratch index path" };
1050
+ const index = isAbsolute(indexPath) || !cwd ? indexPath : join(cwd, indexPath);
1051
+ const env = { GIT_INDEX_FILE: index };
1052
+ try {
1053
+ if ((await run(["read-tree", onto], { env })).exitCode !== 0) return { error: "git read-tree failed" };
1054
+ for (const f of files) {
1055
+ const hashed = await run(["hash-object", "-w", "--stdin"], { stdin: f.content });
1056
+ if (hashed.exitCode !== 0) return { error: `git hash-object failed on ${f.path}` };
1057
+ const added = await run(["update-index", "--add", "--cacheinfo", `100644,${hashed.stdout.trim()},${f.path}`], { env });
1058
+ if (added.exitCode !== 0) return { error: `git update-index failed on ${f.path}` };
1059
+ }
1060
+ const written = await run(["write-tree"], { env });
1061
+ if (written.exitCode !== 0) return { error: "git write-tree failed" };
1062
+ return { tree: written.stdout.trim() };
1063
+ } finally {
1064
+ try {
1065
+ unlinkSync(index);
1066
+ } catch {
1067
+ // No index was written.
1068
+ }
1069
+ }
1070
+ }
1071
+
1072
+ /**
1073
+ * {@link pushLifecycleReport} for a writer whose records must reach the
1074
+ * remote, such as the merge record `pr-record` writes. A push refused because
1075
+ * another writer pushed first fetches the remote's tip, replays this
1076
+ * checkout's commits on it ({@link rebaseLifecycleOnRemote}) and pushes again,
1077
+ * up to {@link LIFECYCLE_PUSH_TRIES} pushes in all. After the last refusal, or
1078
+ * a replay that cannot be made, it throws {@link LifecyclePushLostError}. No
1079
+ * remote, recording off and a push git refused for another reason (no
1080
+ * network, no credentials) are returned as {@link pushLifecycleReport}
1081
+ * returns them.
1082
+ */
1083
+ export async function pushLifecycleRebasing(opts?: { cwd?: string; tries?: number }): Promise<{ pushed: boolean; pushWarning?: string }> {
1084
+ const tries = Math.max(1, opts?.tries ?? LIFECYCLE_PUSH_TRIES);
1085
+ const cwd = opts?.cwd;
1086
+ for (let attempt = 1; ; attempt++) {
1087
+ let result: LifecyclePushStatus;
1088
+ try {
1089
+ result = await pushLifecycleStatus({ cwd });
1090
+ } catch (err) {
1091
+ return { pushed: false, pushWarning: err instanceof Error ? err.message : String(err) };
1092
+ }
1093
+ if (result.status !== "stale") return pushReportOf(result);
1094
+ if (attempt >= tries) {
1095
+ const said = result.stderr.trim().split("\n")[0];
1096
+ throw new LifecyclePushLostError(result.remote, attempt, `another writer pushed before each try${said ? ` (git said: ${said})` : ""}`);
1097
+ }
1098
+ const rebased = await rebaseLifecycleOnRemote(result.remote, cwd);
1099
+ if ("error" in rebased) throw new LifecyclePushLostError(result.remote, attempt, rebased.error);
1100
+ }
1101
+ }
1102
+
917
1103
  /**
918
1104
  * Fetch the state branch from remote.
919
1105
  */
@@ -941,8 +1127,10 @@ export async function fetchLifecycle(opts?: { cwd?: string }): Promise<boolean>
941
1127
  * lease already documents.
942
1128
  * - `absent` — the remote answered and has no `chant/lifecycle`. The ledger
943
1129
  * is genuinely empty; this is a project's first gate.
944
- * - `diverged` — both sides have the branch and neither contains the other.
945
- * Appending here would drop one side's facts.
1130
+ * - `diverged` — both sides have the branch, neither contains the other, and
1131
+ * this checkout's unpushed commits could not be replayed on the remote's
1132
+ * tip. Appending here would drop one side's facts. (Commits that do
1133
+ * replay are put on the tip, and the fetch reports `ahead`.)
946
1134
  * - `unreachable` — a remote is configured and did not answer (no network,
947
1135
  * no credentials, a shallow-clone refspec that cannot resolve). Whether
948
1136
  * anything is on the branch is unknown, which is exactly the state that
@@ -1060,7 +1248,12 @@ export async function fetchLifecycleStatus(opts?: { cwd?: string }): Promise<Lif
1060
1248
  if (remoteTip) await trackRemoteLifecycle(remote, remoteTip, cwd);
1061
1249
  return { status: "ahead", remote };
1062
1250
  }
1063
- return { status: "diverged", remote, stderr };
1251
+ // plywood#22 finding 9: the commits this checkout wrote and never pushed go on top of the remote's tip, as a push that
1252
+ // lost its race replays them, and the read goes on from there. A local branch that shares no history with the remote's,
1253
+ // or whose commits change what the other writer changed, still reads as diverged.
1254
+ const replayed = await rebaseLifecycleOnRemote(remote, cwd);
1255
+ if (!("error" in replayed)) return { status: "ahead", remote };
1256
+ return { status: "diverged", remote, stderr: `${stderr}${stderr ? "\n" : ""}the unpushed commits could not be replayed on the remote's tip: ${replayed.error}` };
1064
1257
  }
1065
1258
 
1066
1259
  /**
@@ -1117,7 +1310,10 @@ export class LifecycleLedgerUnreadableError extends Error {
1117
1310
  * So there is one rule now, for readers and writers alike:
1118
1311
  *
1119
1312
  * - `diverged` always refuses. A fork is not the ledger, and nothing good
1120
- * comes of reading one as if it were.
1313
+ * comes of reading one as if it were. Before a fetch calls it diverged,
1314
+ * it replays this checkout's unpushed commits on the remote's tip
1315
+ * (plywood#22 finding 9), as a push that lost its race does; only a
1316
+ * branch whose commits cannot be replayed there stays diverged.
1121
1317
  * - `unreachable` refuses only when the checkout has no local history at all,
1122
1318
  * which is the case that would otherwise read as an empty ledger. With
1123
1319
  * local history and no answer from the remote, the read proceeds and the
@@ -74,7 +74,12 @@ describe("resolvePlannedLock", () => {
74
74
 
75
75
  test("the declared grain wins over the default, and the step's own over both", async () => {
76
76
  expect(await resolvePlannedLock(choudoufu, {}, { member: "net" }, "target")).toEqual({ grain: "target", source: "declared", rows: [] });
77
- expect(await resolvePlannedLock(choudoufu, { lockGrain: "repo" }, { member: "net" }, "resource")).toEqual({ grain: "repo", source: "step", rows: [] });
77
+ expect(await resolvePlannedLock(choudoufu, { lockGrain: "repo" }, { member: "net" }, "resource")).toEqual({
78
+ grain: "repo",
79
+ source: "step",
80
+ rows: [],
81
+ queue: [{ key: "repo", target: "net", address: "the repository" }],
82
+ });
78
83
  });
79
84
 
80
85
  test("resource is refused by name where the lexicon refuses it, and where no hook names rows", async () => {
@@ -6,14 +6,20 @@
6
6
  * `ci.lockGrain` (ruling A) says what one apply holds while it applies, and,
7
7
  * under `ci.locks`, what a pull request's target locks name (ruling D):
8
8
  *
9
- * - `target`: the component, member, root or stack. The apply takes no row
10
- * lease; the engine's own lock keeps one target's applies apart.
9
+ * - `target`: the component, member, root or stack. A lexicon that names
10
+ * the target's row (`targetLockRow`: `stack <project>/<stack>` for stock
11
+ * Pulumi, `root <root>` for Terraform, tofu and Terragrunt) has the apply
12
+ * wait for that row on the ledger, oldest commit first, up to the job's
13
+ * timeout (ruling for ci-products 2026-10-28, "Ledger lock"). Any other
14
+ * lexicon takes no row lease, and the engine's own lock keeps one
15
+ * target's applies apart.
11
16
  * - `resource`: one row per resource the plan changes, from the lexicon's
12
17
  * `lockRows` hook. The apply leases those rows before it applies and lets
13
18
  * go after, and a pull request under `ci.locks` locks the same keys in
14
19
  * place of its component names.
15
- * - `repo`: one apply at a time in the repository, which the pipeline keeps
16
- * (a concurrency group, a resource group, the lock tag on Forgejo).
20
+ * - `repo`: one apply at a time in the repository: the apply waits for the
21
+ * `repo` row, which meets every other row, in the same queue. The waves
22
+ * pipelines carry no concurrency group of their own.
17
23
  *
18
24
  * Absent, each member takes its lexicon's `defaultLockGrain`, else `target`.
19
25
  *
@@ -21,7 +27,10 @@
21
27
  * of cover (ruling C): a `stack <project>/<stack>` row conflicts with every
22
28
  * `urn urn:pulumi:<stack>::<project>::...` row of that stack, which is how a
23
29
  * plunge apply whose components may register children only at apply locks
24
- * the whole stack and still meets a run holding one of its resources.
30
+ * the whole stack and still meets a run holding one of its resources. A
31
+ * waiting grain's rows ({@link PlannedLock.queue}) use the same keys: a stock
32
+ * stack waits on `stack <project>/<stack>`, so a plunge run on that stack's
33
+ * URNs meets it too, and the `repo` row meets every row.
25
34
  */
26
35
  import { parsePulumiUrn } from "../pulumi-urn";
27
36
 
@@ -48,6 +57,13 @@ export interface PlannedLock {
48
57
  source: "step" | "declared" | "lexicon" | "default";
49
58
  /** The rows, sorted by key. Empty on any grain but `resource`. */
50
59
  rows: LockRow[];
60
+ /**
61
+ * The rows the apply waits for on the `target` and `repo` grains (ruling
62
+ * for ci-products 2026-10-28): the target's own row, from the lexicon's
63
+ * `targetLockRow`, or the `repo` row. Absent when the grain is `resource`
64
+ * or the lexicon names no target row.
65
+ */
66
+ queue?: LockRow[];
51
67
  }
52
68
 
53
69
  /** A lexicon refused the grain asked of a member, by name (#4552: `resource` on Terraform, tofu, Terragrunt and stock Pulumi). */
@@ -67,6 +83,19 @@ export function stackRowKey(project: string, stack: string): string {
67
83
  return `stack ${project}/${stack}`;
68
84
  }
69
85
 
86
+ /** The key of the row that stands for a whole Terraform, tofu or Terragrunt root. A choudoufu root keys its resources `root <root> <address>` on the resource grain and never takes this row. */
87
+ export function rootRowKey(root: string): string {
88
+ return `root ${root}`;
89
+ }
90
+
91
+ /** The key of the row a `repo`-grain apply waits for: it meets every other row. */
92
+ export const REPO_ROW_KEY = "repo";
93
+
94
+ /** The row a `repo`-grain apply waits for. */
95
+ export function repoLockRow(target: string): LockRow {
96
+ return { key: REPO_ROW_KEY, target, address: "the repository" };
97
+ }
98
+
70
99
  /** The key of a URN's row. */
71
100
  export function urnRowKey(urn: string): string {
72
101
  return `urn ${urn}`;
@@ -86,7 +115,7 @@ export function lockRowCover(key: string): string | undefined {
86
115
 
87
116
  /** Whether a holder of row `a` keeps row `b` from being taken: the same key, or one covers the other. */
88
117
  export function lockRowsConflict(a: string, b: string): boolean {
89
- return a === b || lockRowCover(a) === b || lockRowCover(b) === a;
118
+ return a === b || a === REPO_ROW_KEY || b === REPO_ROW_KEY || lockRowCover(a) === b || lockRowCover(b) === a;
90
119
  }
91
120
 
92
121
  /** Rows deduplicated by key and sorted, so two takes of the same rows write the same file. */
@@ -102,6 +131,7 @@ export interface LockGrainHooks {
102
131
  defaultLockGrain?(input: never, plan?: never): LockGrain | Promise<LockGrain>;
103
132
  lockGrainRefusal?(input: never, grain: LockGrain, plan?: never): string | undefined | Promise<string | undefined>;
104
133
  lockRows?(input: never, plan: never): LockRow[] | Promise<LockRow[]>;
134
+ targetLockRow?(input: never, plan?: never): LockRow | undefined | Promise<LockRow | undefined>;
105
135
  }
106
136
 
107
137
  /**
@@ -118,11 +148,32 @@ export async function resolvePlannedLock(capability: LockGrainHooks, input: unkn
118
148
  const grain: LockGrain = step ?? declared ?? (capability.defaultLockGrain ? await capability.defaultLockGrain(input as never, plan as never) : "target");
119
149
  const refused = capability.lockGrainRefusal ? await capability.lockGrainRefusal(input as never, grain, plan as never) : undefined;
120
150
  if (refused) throw new LockGrainRefusedError(plan.member, grain, refused);
121
- if (grain !== "resource") return { grain, source, rows: [] };
151
+ if (grain !== "resource") {
152
+ const queue = await queueRowsOf(capability, input, plan.member, grain, plan);
153
+ return { grain, source, rows: [], ...(queue.length > 0 ? { queue } : {}) };
154
+ }
122
155
  if (!capability.lockRows) throw new LockGrainRefusedError(plan.member, grain, `${capability.kind} names no rows for its resources; set ci.lockGrain to target`);
123
156
  return { grain, source, rows: sortedLockRows(await capability.lockRows(input as never, plan as never)) };
124
157
  }
125
158
 
159
+ /**
160
+ * The rows an apply on the `target` or `repo` grain waits for (ruling for
161
+ * ci-products 2026-10-28): the `repo` row, or the target's row from the
162
+ * lexicon's `targetLockRow`. Empty for `resource`, and for a lexicon that
163
+ * names no target row.
164
+ */
165
+ export async function queueRowsOf(capability: LockGrainHooks, input: unknown, member: string, grain: LockGrain, plan?: unknown): Promise<LockRow[]> {
166
+ if (grain === "repo") return [repoLockRow(member)];
167
+ if (grain !== "target" || !capability.targetLockRow) return [];
168
+ const row = await capability.targetLockRow(input as never, plan as never);
169
+ return row ? [row] : [];
170
+ }
171
+
172
+ /** Every row the waiting members of `locks` wait for, deduplicated and sorted. */
173
+ export function queueRowsOfLocks(locks: Readonly<Record<string, PlannedLock>> | undefined): LockRow[] {
174
+ return sortedLockRows(Object.values(locks ?? {}).flatMap((l) => l.queue ?? []));
175
+ }
176
+
126
177
  /**
127
178
  * A member's grain before anything planned (#4594), by the order
128
179
  * {@link resolvePlannedLock} uses: the step input's own `lockGrain`, else the