@intentius/chant 0.124.56 → 0.124.58

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 (199) 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-words.d.ts +47 -2
  4. package/dist/ci-product-words.d.ts.map +1 -1
  5. package/dist/ci-product-words.js +59 -1
  6. package/dist/ci-product.d.ts +26 -2
  7. package/dist/ci-product.d.ts.map +1 -1
  8. package/dist/ci-product.js +30 -7
  9. package/dist/cli/commands/init.d.ts +2 -0
  10. package/dist/cli/commands/init.d.ts.map +1 -1
  11. package/dist/cli/commands/init.js +1 -1
  12. package/dist/cli/handlers/build.d.ts.map +1 -1
  13. package/dist/cli/handlers/build.js +5 -1
  14. package/dist/cli/handlers/init.d.ts.map +1 -1
  15. package/dist/cli/handlers/init.js +16 -0
  16. package/dist/cli/handlers/lifecycle.d.ts.map +1 -1
  17. package/dist/cli/handlers/lifecycle.js +14 -0
  18. package/dist/cli/handlers/pr.d.ts.map +1 -1
  19. package/dist/cli/handlers/pr.js +90 -35
  20. package/dist/cli/handlers/serve.d.ts.map +1 -1
  21. package/dist/cli/handlers/serve.js +9 -0
  22. package/dist/cli/main.d.ts.map +1 -1
  23. package/dist/cli/main.js +6 -2
  24. package/dist/cli/mcp/product-tools.d.ts +40 -7
  25. package/dist/cli/mcp/product-tools.d.ts.map +1 -1
  26. package/dist/cli/mcp/product-tools.js +59 -15
  27. package/dist/cli/mcp/read-only.d.ts +2 -1
  28. package/dist/cli/mcp/read-only.d.ts.map +1 -1
  29. package/dist/cli/mcp/read-only.js +2 -1
  30. package/dist/cli/mcp/server.d.ts +11 -0
  31. package/dist/cli/mcp/server.d.ts.map +1 -1
  32. package/dist/cli/mcp/server.js +15 -3
  33. package/dist/cli/mcp-config.d.ts +4 -1
  34. package/dist/cli/mcp-config.d.ts.map +1 -1
  35. package/dist/cli/mcp-config.js +6 -2
  36. package/dist/cli/parse-args.d.ts.map +1 -1
  37. package/dist/cli/parse-args.js +9 -0
  38. package/dist/cli/registry.d.ts +8 -0
  39. package/dist/cli/registry.d.ts.map +1 -1
  40. package/dist/components/auto-release.d.ts +5 -2
  41. package/dist/components/auto-release.d.ts.map +1 -1
  42. package/dist/components/auto-release.js +9 -4
  43. package/dist/components/capability.d.ts +10 -0
  44. package/dist/components/capability.d.ts.map +1 -1
  45. package/dist/components/deploy-units.d.ts +12 -0
  46. package/dist/components/deploy-units.d.ts.map +1 -1
  47. package/dist/components/deploy-units.js +20 -1
  48. package/dist/components/pr-pipeline.d.ts +64 -2
  49. package/dist/components/pr-pipeline.d.ts.map +1 -1
  50. package/dist/components/pr-pipeline.js +66 -5
  51. package/dist/components/product-pipeline.d.ts +18 -1
  52. package/dist/components/product-pipeline.d.ts.map +1 -1
  53. package/dist/components/product-pipeline.js +8 -2
  54. package/dist/components/row-lease.d.ts +22 -1
  55. package/dist/components/row-lease.d.ts.map +1 -1
  56. package/dist/components/row-lease.js +32 -6
  57. package/dist/e2e-harness/driver.d.ts.map +1 -1
  58. package/dist/e2e-harness/driver.js +97 -0
  59. package/dist/e2e-harness/forgejo.d.ts +5 -1
  60. package/dist/e2e-harness/forgejo.d.ts.map +1 -1
  61. package/dist/e2e-harness/forgejo.js +35 -0
  62. package/dist/e2e-harness/index.d.ts +7 -0
  63. package/dist/e2e-harness/index.d.ts.map +1 -1
  64. package/dist/e2e-harness/index.js +11 -2
  65. package/dist/e2e-harness/ports.d.ts +31 -0
  66. package/dist/e2e-harness/ports.d.ts.map +1 -1
  67. package/dist/e2e-harness/scenario.d.ts.map +1 -1
  68. package/dist/e2e-harness/scenario.js +9 -5
  69. package/dist/e2e-harness/schemas/e2e-scenario.schema.json +43 -3
  70. package/dist/e2e-harness/schemas/index.d.ts +22 -1
  71. package/dist/e2e-harness/schemas/index.d.ts.map +1 -1
  72. package/dist/e2e-harness/schemas/index.js +1 -1
  73. package/dist/e2e-harness/steps.d.ts.map +1 -1
  74. package/dist/e2e-harness/steps.js +4 -0
  75. package/dist/lexicon.d.ts +9 -0
  76. package/dist/lexicon.d.ts.map +1 -1
  77. package/dist/lifecycle/git.d.ts +39 -3
  78. package/dist/lifecycle/git.d.ts.map +1 -1
  79. package/dist/lifecycle/git.js +223 -15
  80. package/dist/lifecycle/lock-rows.d.ts +23 -0
  81. package/dist/lifecycle/lock-rows.d.ts.map +1 -1
  82. package/dist/lifecycle/lock-rows.js +47 -8
  83. package/dist/lifecycle/resource-lock.d.ts +70 -0
  84. package/dist/lifecycle/resource-lock.d.ts.map +1 -1
  85. package/dist/lifecycle/resource-lock.js +241 -5
  86. package/dist/mcp/types.d.ts +9 -0
  87. package/dist/mcp/types.d.ts.map +1 -1
  88. package/dist/op/gate.js +21 -4
  89. package/dist/op/op-waves-release-port.js +1 -1
  90. package/dist/op/op-waves-release.d.ts +2 -1
  91. package/dist/op/op-waves-release.d.ts.map +1 -1
  92. package/dist/op/op-waves-run.d.ts +8 -0
  93. package/dist/op/op-waves-run.d.ts.map +1 -1
  94. package/dist/op/op-waves-run.js +101 -29
  95. package/dist/op/op-waves.d.ts +18 -0
  96. package/dist/op/op-waves.d.ts.map +1 -1
  97. package/dist/op/op-waves.js +16 -0
  98. package/dist/pr-loop.d.ts.map +1 -1
  99. package/dist/pr-loop.js +1 -2
  100. package/dist/release-floors.d.ts +1 -1
  101. package/dist/release-floors.js +1 -1
  102. package/dist/template-request/index.d.ts +9 -0
  103. package/dist/template-request/index.d.ts.map +1 -0
  104. package/dist/template-request/index.js +8 -0
  105. package/dist/template-request/request-body.d.ts +21 -0
  106. package/dist/template-request/request-body.d.ts.map +1 -0
  107. package/dist/template-request/request-body.js +86 -0
  108. package/dist/template-request/template-request.d.ts +100 -0
  109. package/dist/template-request/template-request.d.ts.map +1 -0
  110. package/dist/template-request/template-request.js +150 -0
  111. package/dist/template-request/template-request.schema.json +100 -0
  112. package/dist/template-request/template-spec.d.ts +83 -0
  113. package/dist/template-request/template-spec.d.ts.map +1 -0
  114. package/dist/template-request/template-spec.js +146 -0
  115. package/dist/template-request/template.schema.json +114 -0
  116. package/dist/template-request/validate.d.ts +4 -0
  117. package/dist/template-request/validate.d.ts.map +1 -0
  118. package/dist/template-request/validate.js +21 -0
  119. package/dist/wave-runtime.mjs +310 -300
  120. package/package.json +8 -1
  121. package/src/ci-audit/index.ts +1 -2
  122. package/src/ci-product-words.test.ts +23 -0
  123. package/src/ci-product-words.ts +68 -3
  124. package/src/ci-product.ts +36 -6
  125. package/src/cli/commands/init.ts +3 -1
  126. package/src/cli/handlers/build.ts +5 -1
  127. package/src/cli/handlers/init.ts +18 -0
  128. package/src/cli/handlers/lifecycle.ts +13 -0
  129. package/src/cli/handlers/pr-before-merge.test.ts +1 -1
  130. package/src/cli/handlers/pr-deploy-inputs.test.ts +1 -1
  131. package/src/cli/handlers/pr-endpoint.test.ts +1 -1
  132. package/src/cli/handlers/pr-green.test.ts +1 -1
  133. package/src/cli/handlers/pr-plan-comment-targets.test.ts +1 -1
  134. package/src/cli/handlers/pr-plan-flags.test.ts +1 -1
  135. package/src/cli/handlers/pr-plan-targets.test.ts +1 -1
  136. package/src/cli/handlers/pr-record.test.ts +34 -2
  137. package/src/cli/handlers/pr-waves-blocked.test.ts +1 -1
  138. package/src/cli/handlers/pr-waves.test.ts +1 -1
  139. package/src/cli/handlers/pr.test.ts +1 -1
  140. package/src/cli/handlers/pr.ts +86 -31
  141. package/src/cli/handlers/serve.ts +9 -0
  142. package/src/cli/main.ts +6 -2
  143. package/src/cli/mcp/product-tools.test.ts +57 -1
  144. package/src/cli/mcp/product-tools.ts +67 -15
  145. package/src/cli/mcp/read-only.ts +2 -1
  146. package/src/cli/mcp/server.ts +20 -5
  147. package/src/cli/mcp-config.test.ts +52 -2
  148. package/src/cli/mcp-config.ts +6 -3
  149. package/src/cli/parse-args.ts +7 -0
  150. package/src/cli/registry.ts +8 -0
  151. package/src/components/auto-release.test.ts +4 -2
  152. package/src/components/auto-release.ts +9 -5
  153. package/src/components/capability.ts +10 -0
  154. package/src/components/deploy-units.test.ts +18 -1
  155. package/src/components/deploy-units.ts +26 -1
  156. package/src/components/pr-pipeline.ts +99 -5
  157. package/src/components/product-actions.test.ts +76 -0
  158. package/src/components/product-pipeline.ts +21 -2
  159. package/src/components/row-lease.test.ts +61 -1
  160. package/src/components/row-lease.ts +48 -7
  161. package/src/e2e-harness/driver.test.ts +163 -0
  162. package/src/e2e-harness/driver.ts +86 -1
  163. package/src/e2e-harness/forgejo.ts +42 -1
  164. package/src/e2e-harness/index.ts +12 -2
  165. package/src/e2e-harness/ports.ts +33 -0
  166. package/src/e2e-harness/scenario.ts +8 -6
  167. package/src/e2e-harness/schemas/README.md +11 -2
  168. package/src/e2e-harness/schemas/e2e-scenario.schema.json +43 -3
  169. package/src/e2e-harness/schemas/index.ts +5 -1
  170. package/src/e2e-harness/schemas.test.ts +44 -1
  171. package/src/e2e-harness/steps.ts +4 -0
  172. package/src/lexicon.ts +9 -0
  173. package/src/lifecycle/git.test.ts +155 -0
  174. package/src/lifecycle/git.ts +213 -17
  175. package/src/lifecycle/lock-rows.test.ts +6 -1
  176. package/src/lifecycle/lock-rows.ts +58 -7
  177. package/src/lifecycle/resource-lock-wait.test.ts +292 -0
  178. package/src/lifecycle/resource-lock.ts +261 -7
  179. package/src/mcp/types.ts +9 -0
  180. package/src/op/gate.test.ts +7 -5
  181. package/src/op/gate.ts +20 -4
  182. package/src/op/op-waves-after-plan.test.ts +1 -2
  183. package/src/op/op-waves-ledger-lock.test.ts +208 -0
  184. package/src/op/op-waves-release-port.ts +1 -1
  185. package/src/op/op-waves-release.ts +1 -1
  186. package/src/op/op-waves-run.ts +104 -29
  187. package/src/op/op-waves.ts +18 -0
  188. package/src/pr-loop-bundle.test.ts +0 -2
  189. package/src/pr-loop.ts +1 -2
  190. package/src/release-floors.ts +1 -1
  191. package/src/template-request/__fixtures__/request-body.md +41 -0
  192. package/src/template-request/index.ts +8 -0
  193. package/src/template-request/request-body.ts +91 -0
  194. package/src/template-request/template-request.schema.json +100 -0
  195. package/src/template-request/template-request.test.ts +316 -0
  196. package/src/template-request/template-request.ts +235 -0
  197. package/src/template-request/template-spec.ts +176 -0
  198. package/src/template-request/template.schema.json +114 -0
  199. package/src/template-request/validate.ts +28 -0
@@ -55,7 +55,7 @@
55
55
  },
56
56
  "$defs": {
57
57
  "name": { "type": "string", "pattern": "^[a-z0-9][a-z0-9-]*$" },
58
- "do": { "enum": ["open", "open-concurrent", "plan", "approve", "merge", "apply", "out-of-band", "kill-job"] },
58
+ "do": { "enum": ["open", "open-concurrent", "await-pull", "plan", "approve", "merge", "comment", "apply", "out-of-band", "kill-job"] },
59
59
  "step": {
60
60
  "type": "object",
61
61
  "required": ["id", "do"],
@@ -81,10 +81,29 @@
81
81
  "type": "object",
82
82
  "properties": {
83
83
  "do": { "enum": ["plan", "approve", "merge"] },
84
- "pull": { "$ref": "#/$defs/name", "description": "The id of the open step whose pull request this is." }
84
+ "pull": { "$ref": "#/$defs/name", "description": "The id of the open or await-pull step whose pull request this is." }
85
85
  },
86
86
  "required": ["pull"]
87
87
  },
88
+ {
89
+ "type": "object",
90
+ "properties": {
91
+ "do": { "const": "await-pull" },
92
+ "branch": { "type": "string", "minLength": 1, "description": "The exact head branch of the pull request a product opens. Both runs wait for this same branch: the BREAK run does not add -break to it." },
93
+ "title": { "type": "string", "minLength": 1, "description": "Text the pull request's title must hold, when given." }
94
+ },
95
+ "required": ["branch"]
96
+ },
97
+ {
98
+ "type": "object",
99
+ "properties": {
100
+ "do": { "const": "comment" },
101
+ "pull": { "$ref": "#/$defs/name", "description": "The id of the open or await-pull step whose pull request the comment goes on." },
102
+ "body": { "type": "string", "minLength": 1 },
103
+ "as": { "enum": ["author", "reviewer", "admin"], "description": "Who posts it. Default author." }
104
+ },
105
+ "required": ["pull", "body"]
106
+ },
88
107
  {
89
108
  "type": "object",
90
109
  "properties": {
@@ -112,7 +131,7 @@
112
131
  },
113
132
  "outcome": {
114
133
  "type": "object",
115
- "description": "One thing a step must show. report reads the step's pr-plan.json or pr-apply.json; ledger reads the run records the scenario added; comment and issue read the forge; exit is an out-of-band command's exit code.",
134
+ "description": "One thing a step must show. report reads the step's pr-plan.json or pr-apply.json; ledger reads the run records the scenario added; gated reads the gated requests the scenario added; comment, issue and pull read the forge; exit is an out-of-band command's exit code.",
116
135
  "minProperties": 1,
117
136
  "maxProperties": 1,
118
137
  "additionalProperties": false,
@@ -136,7 +155,28 @@
136
155
  "count": { "type": "integer", "minimum": 0 }
137
156
  }
138
157
  },
158
+ "gated": {
159
+ "type": "object",
160
+ "required": ["op"],
161
+ "additionalProperties": false,
162
+ "description": "Gated requests of op on the ledger, asked since the run started. A request is gated until a finished line names it, then ok when it applied and failed when it did not.",
163
+ "properties": {
164
+ "op": { "type": "string" },
165
+ "status": { "enum": ["gated", "ok", "failed"] },
166
+ "count": { "type": "integer", "minimum": 0 }
167
+ }
168
+ },
139
169
  "comment": { "type": "string", "minLength": 1, "description": "Text one of the step's pull request comments holds." },
170
+ "pull": {
171
+ "type": "object",
172
+ "additionalProperties": false,
173
+ "description": "The step's pull request: its title holds title, it changes every path in files, and with only it changes no other path.",
174
+ "properties": {
175
+ "title": { "type": "string", "minLength": 1 },
176
+ "files": { "type": "array", "items": { "type": "string", "minLength": 1 } },
177
+ "only": { "type": "boolean", "description": "files names every path the pull request changes." }
178
+ }
179
+ },
140
180
  "issue": {
141
181
  "type": "object",
142
182
  "required": ["title"],
@@ -111,14 +111,16 @@ export interface DemoCycle {
111
111
 
112
112
  // ── e2e-scenario/v1 ───────────────────────────────────────────────────
113
113
 
114
- export const SCENARIO_STEP_KINDS = ["open", "open-concurrent", "plan", "approve", "merge", "apply", "out-of-band", "kill-job"] as const;
114
+ export const SCENARIO_STEP_KINDS = ["open", "open-concurrent", "await-pull", "plan", "approve", "merge", "comment", "apply", "out-of-band", "kill-job"] as const;
115
115
  export type ScenarioStepKind = (typeof SCENARIO_STEP_KINDS)[number];
116
116
 
117
117
  /** One thing a step must show. Exactly one key is set. */
118
118
  export type ScenarioOutcome =
119
119
  | { report: { status?: string; components?: Record<string, string>; only?: boolean } }
120
120
  | { ledger: { op: string; status?: "ok" | "fail" | "gated" | "waiting"; count?: number } }
121
+ | { gated: { op: string; status?: "gated" | "ok" | "failed"; count?: number } }
121
122
  | { comment: string }
123
+ | { pull: { title?: string; files?: string[]; only?: boolean } }
122
124
  | { issue: { title: string; open?: boolean } }
123
125
  | { exit: number };
124
126
 
@@ -130,7 +132,9 @@ interface StepBase {
130
132
 
131
133
  export type ScenarioStep =
132
134
  | (StepBase & { do: "open" | "open-concurrent"; branch: string; overlay: string; title: string; body?: string })
135
+ | (StepBase & { do: "await-pull"; branch: string; title?: string })
133
136
  | (StepBase & { do: "plan" | "approve" | "merge"; pull: string })
137
+ | (StepBase & { do: "comment"; pull: string; body: string; as?: "author" | "reviewer" | "admin" })
134
138
  | (StepBase & { do: "apply"; merge: string })
135
139
  | (StepBase & { do: "out-of-band"; command: string[] })
136
140
  | (StepBase & { do: "kill-job"; match?: string });
@@ -65,7 +65,7 @@ describe("e2e-scenario/v1 and its lint", () => {
65
65
  steps[2] = { id: "one-plan", do: "plan", pull: "nobody", expect: [{ report: { status: "planned" } }] };
66
66
  steps[4] = { id: "one-apply", do: "apply", merge: "one", expect: [{ exit: 0 }] };
67
67
  const findings = lintScenario(s);
68
- expect(findings).toContainEqual({ at: "/steps/2/pull", message: "plan names nobody, which is not an earlier open step" });
68
+ expect(findings).toContainEqual({ at: "/steps/2/pull", message: "plan names nobody, which is not an earlier open or await-pull step" });
69
69
  expect(findings).toContainEqual({ at: "/steps/4/merge", message: "apply names one, which is not an earlier merge step" });
70
70
  expect(findings).toContainEqual({ at: "/steps/4/expect/0", message: "an exit outcome belongs on an out-of-band step" });
71
71
  });
@@ -97,6 +97,49 @@ describe("e2e-scenario/v1 and its lint", () => {
97
97
  });
98
98
  });
99
99
 
100
+ describe("e2e-scenario/v1 steps for a pull request a product opens (chant#4650)", () => {
101
+ const product = (steps: unknown[]): Record<string, unknown> => ({ ...scenario(), steps });
102
+ const request = { id: "request", do: "out-of-band", command: ["terragucci", "request"], expect: [{ exit: 0 }] };
103
+
104
+ test("await-pull, comment and the pull and gated outcomes are in the schema", () => {
105
+ const s = product([
106
+ request,
107
+ { id: "pr", do: "await-pull", branch: "request/bucket/orders", title: "orders", expect: [{ pull: { title: "orders", files: ["apps/orders/main.tf"], only: true } }] },
108
+ { id: "pr-plan", do: "plan", pull: "pr", expect: [{ report: { status: "planned" } }] },
109
+ { id: "invoke", do: "comment", pull: "pr", body: "/terragucci action orders rotate", as: "reviewer", expect: [{ gated: { op: "tf-action", status: "gated", count: 1 } }] },
110
+ ]);
111
+ expect(validateScenario(s)).toMatchObject({ ok: true });
112
+ expect(lintScenario({ ...s, limits: { "await-pull": 600, comment: 30 } })).toEqual([]);
113
+ });
114
+
115
+ test("a plan naming an await-pull step lints clean, and one naming an unknown id has one finding naming it", () => {
116
+ const steps = (pull: string) => [request, { id: "pr", do: "await-pull", branch: "request/bucket/orders" }, { id: "pr-plan", do: "plan", pull, expect: [{ report: { status: "planned" } }] }];
117
+ expect(lintScenario(product(steps("pr")))).toEqual([]);
118
+ expect(lintScenario(product(steps("nobody")))).toEqual([{ at: "/steps/2/pull", message: "plan names nobody, which is not an earlier open or await-pull step" }]);
119
+ });
120
+
121
+ test("a comment step names an earlier pull request, and a pull outcome belongs on a step with one", () => {
122
+ expect(lintScenario(product([request, { id: "c", do: "comment", pull: "later", body: "hi" }]))).toEqual([{ at: "/steps/1/pull", message: "comment names later, which is not an earlier open or await-pull step" }]);
123
+ expect(lintScenario(product([{ ...request, expect: [{ pull: { only: true } }] }]))).toEqual([{ at: "/steps/0/expect/0", message: "a pull outcome belongs on a step with a pull request" }]);
124
+ });
125
+
126
+ test("the schema refuses an await-pull with no branch, a comment with no pull or body, and unknown fields in the outcomes", () => {
127
+ for (const bad of [
128
+ { id: "s", do: "await-pull", title: "T" },
129
+ { id: "s", do: "comment", pull: "one" },
130
+ { id: "s", do: "comment", body: "hi" },
131
+ { id: "s", do: "comment", pull: "one", body: "hi", as: "stranger" },
132
+ { id: "s", do: "plan", pull: "one", expect: [{ pull: { branch: "x" } }] },
133
+ { id: "s", do: "plan", pull: "one", expect: [{ gated: { status: "ok" } }] },
134
+ { id: "s", do: "plan", pull: "one", expect: [{ gated: { op: "tf-action", status: "applied" } }] },
135
+ ]) {
136
+ const s = scenario();
137
+ (s.steps as unknown[]).push(bad);
138
+ expect(validateScenario(s).ok, JSON.stringify(bad)).toBe(false);
139
+ }
140
+ });
141
+ });
142
+
100
143
  const row = (over: Partial<ClaimRow> = {}): ClaimRow => ({
101
144
  $schema: E2E_CLAIM_ROW_SCHEMA,
102
145
  contract: 1,
@@ -10,12 +10,16 @@ export const HARNESS_LIMITS: Record<ScenarioStepKind, number> = {
10
10
  /** The branch push and the pull request open. */
11
11
  open: 60,
12
12
  "open-concurrent": 60,
13
+ /** An open pull request from the branch, which a product opens. */
14
+ "await-pull": 300,
13
15
  /** pr-plan.json at the head, from the push. */
14
16
  plan: 600,
15
17
  /** The forge review and chant approve. */
16
18
  approve: 120,
17
19
  /** The merge and its merge commit. */
18
20
  merge: 60,
21
+ /** Posting a comment on the pull request. */
22
+ comment: 60,
19
23
  /** pr-apply.json at the merge commit, from the merge. */
20
24
  apply: 900,
21
25
  /** A command run out of band. */
package/src/lexicon.ts CHANGED
@@ -1049,6 +1049,15 @@ export interface OpWavesPipelineOptions
1049
1049
  * fills it from the active product words. Absent: chant's.
1050
1050
  */
1051
1051
  words?: import("./ci-product-words").CiProductWordsInput | import("./ci-product-words").CiProductWords;
1052
+ /**
1053
+ * Each wave job's timeout in minutes (ruling for ci-products 2026-10-28,
1054
+ * "Ledger lock"). The jobs carry it (`timeout-minutes`, GitLab's
1055
+ * `timeout`), and `CHANT_LOCK_WAIT` five minutes under it, so a run on
1056
+ * the `target` or `repo` grain waiting for its row on the ledger gives up
1057
+ * by name before the forge stops the job. Default
1058
+ * `OP_WAVE_JOB_TIMEOUT_MINUTES` (180).
1059
+ */
1060
+ jobTimeoutMinutes?: number;
1052
1061
  }
1053
1062
 
1054
1063
  /** An Op waves pipeline: one file, and its jobs in order. */
@@ -13,6 +13,9 @@ import {
13
13
  getHeadCommit,
14
14
  pushLifecycle,
15
15
  pushLifecycleReport,
16
+ pushLifecycleRebasing,
17
+ LifecyclePushLostError,
18
+ LIFECYCLE_PUSH_TRIES,
16
19
  StaleLifecycleBranchError,
17
20
  appendReleaseRecordLine,
18
21
  readReleaseLedgerLines,
@@ -30,6 +33,8 @@ import {
30
33
  fetchRefInto,
31
34
  RefCASConflictError,
32
35
  StaleLockError,
36
+ fetchLifecycleStatus,
37
+ requireLifecycleLedger,
33
38
  } from "./git";
34
39
  import { LIFECYCLE_LOCAL_NOTE } from "./local-note";
35
40
 
@@ -526,6 +531,156 @@ describe("lifecycle/git", () => {
526
531
  expect(err.message).toContain("moved");
527
532
  });
528
533
 
534
+ // #4551: a pr handler's push (the merge record pr-record writes) fetches, replays and pushes again, as publishRef does.
535
+ describe("pushLifecycleRebasing", () => {
536
+ /** A, and B with its own copy of the branch: the record job's checkout, taken before A pushes again. */
537
+ async function twoWriters(): Promise<{ a: string; b: string; remotePath: string; done: () => Promise<void> }> {
538
+ const { clonePath: a, remotePath, cleanup } = await setupClonePair();
539
+ const b = join(tmpdir(), `chant-state-clone-b-${Date.now()}-${Math.random()}`);
540
+ git(["clone", "-q", remotePath, b], tmpdir());
541
+ git(["config", "user.email", "record@chant.dev"], b);
542
+ git(["config", "user.name", "Record"], b);
543
+ await writeSnapshot("prod", "aws", JSON.stringify({ a: 1 }), { cwd: a });
544
+ expect(await pushLifecycle({ cwd: a })).toBe(true);
545
+ git(["fetch", "-q", "origin", "chant/lifecycle:chant/lifecycle"], b);
546
+ git(["fetch", "-q", "origin", "+refs/heads/chant/lifecycle:refs/remotes/origin/chant/lifecycle"], b);
547
+ return {
548
+ a,
549
+ b,
550
+ remotePath,
551
+ done: async () => {
552
+ await cleanup();
553
+ const { rm } = await import("node:fs/promises");
554
+ await rm(b, { recursive: true, force: true });
555
+ },
556
+ };
557
+ }
558
+ /** A moves the remote on behind B's back, as a wave job pushing beside the record job does. */
559
+ async function advance(a: string, filename: string, content: string): Promise<void> {
560
+ git(["fetch", "-q", "origin", "+refs/heads/chant/lifecycle:refs/remotes/origin/chant/lifecycle"], a);
561
+ await writeBlobToPath("prod", filename, content, `wave: ${filename}`, { cwd: a });
562
+ expect(await pushLifecycle({ cwd: a })).toBe(true);
563
+ }
564
+
565
+ test("a push another writer beat between checkout and push replays on the remote's tip and lands, with both writes kept", async () => {
566
+ const { a, b, remotePath, done } = await twoWriters();
567
+ try {
568
+ await advance(a, "wave.json", '{"wave":1}');
569
+ await writeBlobToPath("prod", "merge.json", '{"merge":1}', "Merge record: abc", { cwd: b });
570
+ // The single push refuses, as pr-record's did before.
571
+ expect((await pushLifecycleReport({ cwd: b })).pushed).toBe(false);
572
+
573
+ expect(await pushLifecycleRebasing({ cwd: b })).toEqual({ pushed: true });
574
+ const tip = git(["rev-parse", "refs/heads/chant/lifecycle"], remotePath).stdout.trim();
575
+ expect(git(["rev-parse", "refs/heads/chant/lifecycle"], b).stdout.trim()).toBe(tip);
576
+ expect(git(["show", `${tip}:prod/merge.json`], remotePath).stdout).toBe('{"merge":1}');
577
+ expect(git(["show", `${tip}:prod/wave.json`], remotePath).stdout).toBe('{"wave":1}');
578
+ expect(git(["show", `${tip}:prod/aws.json`], remotePath).stdout).toBe(JSON.stringify({ a: 1 }));
579
+ // B's commit sits on A's, with its own message and author.
580
+ expect(git(["log", "-1", "--format=%s|%an|%ae", tip], remotePath).stdout.trim()).toBe("Merge record: abc|Record|record@chant.dev");
581
+ expect(git(["log", "-1", "--format=%s", `${tip}^`], remotePath).stdout.trim()).toBe("wave: wave.json");
582
+ // The lease now names the tip that landed, so the next push needs no retry.
583
+ expect(git(["rev-parse", "refs/remotes/origin/chant/lifecycle"], b).stdout.trim()).toBe(tip);
584
+ expect(git(["rev-parse", "--verify", "--quiet", "refs/chant/lifecycle-rebase"], b).exitCode).not.toBe(0);
585
+ } finally {
586
+ await done();
587
+ }
588
+ });
589
+
590
+ test("a commit that changes the file the other writer changed is refused by name, and the local write is kept", async () => {
591
+ const { a, b, done } = await twoWriters();
592
+ try {
593
+ await advance(a, "merge.json", '{"merge":"wave"}');
594
+ await writeBlobToPath("prod", "merge.json", '{"merge":"record"}', "Merge record: abc", { cwd: b });
595
+ const local = git(["rev-parse", "refs/heads/chant/lifecycle"], b).stdout.trim();
596
+ const err = await pushLifecycleRebasing({ cwd: b }).catch((e: unknown) => e);
597
+ expect(err).toBeInstanceOf(LifecyclePushLostError);
598
+ expect((err as LifecyclePushLostError).name).toBe("LifecyclePushLostError");
599
+ expect((err as Error).message).toContain('"Merge record: abc"');
600
+ expect((err as Error).message).toContain("changes files the other writer changed too");
601
+ expect(git(["rev-parse", "refs/heads/chant/lifecycle"], b).stdout.trim()).toBe(local);
602
+ } finally {
603
+ await done();
604
+ }
605
+ });
606
+
607
+ test(`a remote that refuses every push fails after ${LIFECYCLE_PUSH_TRIES} tries with LifecyclePushLostError`, async () => {
608
+ const { b, remotePath, done } = await twoWriters();
609
+ try {
610
+ const hook = join(remotePath, "hooks", "update");
611
+ writeFileSync(hook, "#!/bin/sh\necho 'another writer is mid-push' >&2\nexit 1\n", { mode: 0o755 });
612
+ await writeBlobToPath("prod", "merge.json", '{"merge":1}', "Merge record: abc", { cwd: b });
613
+ const err = await pushLifecycleRebasing({ cwd: b }).catch((e: unknown) => e);
614
+ expect(err).toBeInstanceOf(LifecyclePushLostError);
615
+ expect((err as LifecyclePushLostError).tries).toBe(LIFECYCLE_PUSH_TRIES);
616
+ expect((err as Error).message).toContain(`chant/lifecycle was not pushed to "origin" after ${LIFECYCLE_PUSH_TRIES} tries`);
617
+ } finally {
618
+ await done();
619
+ }
620
+ });
621
+
622
+ test("plywood#22 finding 9: two writers that append lines to one ledger file both land, in push order", async () => {
623
+ const { a, b, remotePath, done } = await twoWriters();
624
+ try {
625
+ // A, a wave job, appends its release record and pushes; B, the record job, appends to the same file from its older copy.
626
+ git(["fetch", "-q", "origin", "+refs/heads/chant/lifecycle:refs/remotes/origin/chant/lifecycle"], a);
627
+ await appendReleaseRecordLine("prod", '{"from":"wave"}', { cwd: a });
628
+ expect(await pushLifecycle({ cwd: a })).toBe(true);
629
+ await appendReleaseRecordLine("prod", '{"from":"record"}', { cwd: b });
630
+ expect(await pushLifecycleRebasing({ cwd: b })).toEqual({ pushed: true });
631
+ const tip = git(["rev-parse", "refs/heads/chant/lifecycle"], remotePath).stdout.trim();
632
+ expect(git(["show", `${tip}:prod/releases.jsonl`], remotePath).stdout).toBe('{"from":"wave"}\n{"from":"record"}\n');
633
+ expect(git(["log", "-1", "--format=%s", tip], remotePath).stdout.trim()).toBe("Release record");
634
+ } finally {
635
+ await done();
636
+ }
637
+ });
638
+
639
+ test("plywood#22 finding 9: a read that finds its unpushed commits diverged from the remote replays them on the remote's tip", async () => {
640
+ const { a, b, remotePath, done } = await twoWriters();
641
+ try {
642
+ await appendReleaseRecordLine("prod", '{"from":"unpushed"}', { cwd: b });
643
+ git(["fetch", "-q", "origin", "+refs/heads/chant/lifecycle:refs/remotes/origin/chant/lifecycle"], a);
644
+ await appendReleaseRecordLine("prod", '{"from":"other"}', { cwd: a });
645
+ expect(await pushLifecycle({ cwd: a })).toBe(true);
646
+ const remoteTip = git(["rev-parse", "refs/heads/chant/lifecycle"], remotePath).stdout.trim();
647
+
648
+ expect(await fetchLifecycleStatus({ cwd: b })).toEqual({ status: "ahead", remote: "origin" });
649
+ await expect(requireLifecycleLedger({ cwd: b })).resolves.toBeUndefined();
650
+ const local = git(["rev-parse", "refs/heads/chant/lifecycle"], b).stdout.trim();
651
+ expect(git(["merge-base", "--is-ancestor", remoteTip, local], b).exitCode).toBe(0);
652
+ expect(git(["show", `${local}:prod/releases.jsonl`], b).stdout).toBe('{"from":"other"}\n{"from":"unpushed"}\n');
653
+ // Nothing was pushed by the read; the next push carries the replayed commit.
654
+ expect(git(["rev-parse", "refs/heads/chant/lifecycle"], remotePath).stdout.trim()).toBe(remoteTip);
655
+ expect(await pushLifecycleRebasing({ cwd: b })).toEqual({ pushed: true });
656
+ } finally {
657
+ await done();
658
+ }
659
+ });
660
+
661
+ test("a read whose unpushed commit rewrote the file the other writer changed still finds the ledger diverged", async () => {
662
+ const { a, b, done } = await twoWriters();
663
+ try {
664
+ await writeBlobToPath("prod", "merge.json", '{"merge":"record"}', "Merge record: abc", { cwd: b });
665
+ await advance(a, "merge.json", '{"merge":"wave"}');
666
+ const got = await fetchLifecycleStatus({ cwd: b });
667
+ expect(got.status).toBe("diverged");
668
+ expect(got.status === "diverged" ? got.stderr : "").toContain("could not be replayed");
669
+ await expect(requireLifecycleLedger({ cwd: b })).rejects.toThrow(/has diverged/);
670
+ } finally {
671
+ await done();
672
+ }
673
+ });
674
+
675
+ test("no remote reads as the local note, as pushLifecycleReport says it", async () => {
676
+ await withTestDir(async (dir) => {
677
+ await initRepo(dir);
678
+ await writeSnapshot("prod", "aws", JSON.stringify({ a: 1 }), { cwd: dir });
679
+ expect(await pushLifecycleRebasing({ cwd: dir })).toEqual({ pushed: false, pushWarning: LIFECYCLE_LOCAL_NOTE });
680
+ });
681
+ });
682
+ });
683
+
529
684
  // ── Release ledger plumbing (#568) ──────────────────────────────────────
530
685
 
531
686
  describe("release ledger plumbing", () => {
@@ -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