@intentius/chant 0.124.62 → 0.124.64

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 (262) hide show
  1. package/dist/cli/handlers/approve.d.ts +26 -0
  2. package/dist/cli/handlers/approve.d.ts.map +1 -1
  3. package/dist/cli/handlers/approve.js +167 -18
  4. package/dist/cli/handlers/plan.d.ts +10 -0
  5. package/dist/cli/handlers/plan.d.ts.map +1 -0
  6. package/dist/cli/handlers/plan.js +71 -0
  7. package/dist/cli/handlers/pr.d.ts.map +1 -1
  8. package/dist/cli/handlers/pr.js +2 -1
  9. package/dist/cli/handlers/release.d.ts +11 -7
  10. package/dist/cli/handlers/release.d.ts.map +1 -1
  11. package/dist/cli/handlers/release.js +93 -20
  12. package/dist/cli/main.d.ts.map +1 -1
  13. package/dist/cli/main.js +48 -7
  14. package/dist/cli/mcp/workspace-tools.d.ts.map +1 -1
  15. package/dist/cli/mcp/workspace-tools.js +2 -1
  16. package/dist/cli/parse-args.d.ts.map +1 -1
  17. package/dist/cli/parse-args.js +43 -0
  18. package/dist/cli/registry.d.ts +18 -2
  19. package/dist/cli/registry.d.ts.map +1 -1
  20. package/dist/config.d.ts +50 -0
  21. package/dist/config.d.ts.map +1 -1
  22. package/dist/config.js +1 -0
  23. package/dist/gate-decision.d.ts +1 -1
  24. package/dist/gate-decision.d.ts.map +1 -1
  25. package/dist/gate-decision.js +4 -2
  26. package/dist/gate-statement.schema.json +46 -0
  27. package/dist/lifecycle/__fixtures__/publish-fakes.d.ts +20 -0
  28. package/dist/lifecycle/__fixtures__/publish-fakes.d.ts.map +1 -1
  29. package/dist/lifecycle/__fixtures__/publish-fakes.js +119 -3
  30. package/dist/lifecycle/gate-ledger.d.ts +28 -5
  31. package/dist/lifecycle/gate-ledger.d.ts.map +1 -1
  32. package/dist/lifecycle/gate-ledger.js +6 -0
  33. package/dist/lifecycle/gate-seal.d.ts +59 -7
  34. package/dist/lifecycle/gate-seal.d.ts.map +1 -1
  35. package/dist/lifecycle/gate-seal.js +68 -15
  36. package/dist/lifecycle/gate-statement.d.ts +95 -0
  37. package/dist/lifecycle/gate-statement.d.ts.map +1 -0
  38. package/dist/lifecycle/gate-statement.js +110 -0
  39. package/dist/lifecycle/gate-webauthn.d.ts +79 -0
  40. package/dist/lifecycle/gate-webauthn.d.ts.map +1 -0
  41. package/dist/lifecycle/gate-webauthn.js +105 -0
  42. package/dist/lifecycle/git.d.ts +1 -1
  43. package/dist/lifecycle/git.d.ts.map +1 -1
  44. package/dist/lifecycle/git.js +24 -19
  45. package/dist/lifecycle/ledger-remote.d.ts +37 -0
  46. package/dist/lifecycle/ledger-remote.d.ts.map +1 -0
  47. package/dist/lifecycle/ledger-remote.js +42 -0
  48. package/dist/lifecycle/plan-stale.d.ts +76 -0
  49. package/dist/lifecycle/plan-stale.d.ts.map +1 -0
  50. package/dist/lifecycle/plan-stale.js +120 -0
  51. package/dist/lifecycle/publish-credentials.d.ts +1 -1
  52. package/dist/lifecycle/publish-credentials.d.ts.map +1 -1
  53. package/dist/lifecycle/publish-credentials.js +2 -0
  54. package/dist/lifecycle/publish-declaration.d.ts +107 -0
  55. package/dist/lifecycle/publish-declaration.d.ts.map +1 -1
  56. package/dist/lifecycle/publish-declaration.js +110 -1
  57. package/dist/lifecycle/publish-forge.d.ts +5 -1
  58. package/dist/lifecycle/publish-forge.d.ts.map +1 -1
  59. package/dist/lifecycle/publish-forge.js +13 -4
  60. package/dist/lifecycle/publish-git-ssh.d.ts +82 -0
  61. package/dist/lifecycle/publish-git-ssh.d.ts.map +1 -0
  62. package/dist/lifecycle/publish-git-ssh.js +180 -0
  63. package/dist/lifecycle/publish-github.d.ts +69 -0
  64. package/dist/lifecycle/publish-github.d.ts.map +1 -0
  65. package/dist/lifecycle/publish-github.js +153 -0
  66. package/dist/lifecycle/publish-homebrew.d.ts +77 -0
  67. package/dist/lifecycle/publish-homebrew.d.ts.map +1 -0
  68. package/dist/lifecycle/publish-homebrew.js +265 -0
  69. package/dist/lifecycle/publish-marketplace.d.ts +85 -0
  70. package/dist/lifecycle/publish-marketplace.d.ts.map +1 -0
  71. package/dist/lifecycle/publish-marketplace.js +398 -0
  72. package/dist/lifecycle/publish-targets.d.ts +6 -0
  73. package/dist/lifecycle/publish-targets.d.ts.map +1 -1
  74. package/dist/lifecycle/publish-targets.js +15 -0
  75. package/dist/lifecycle/publish-tauri.d.ts +61 -0
  76. package/dist/lifecycle/publish-tauri.d.ts.map +1 -0
  77. package/dist/lifecycle/publish-tauri.js +181 -0
  78. package/dist/lifecycle/release-cut.d.ts +51 -5
  79. package/dist/lifecycle/release-cut.d.ts.map +1 -1
  80. package/dist/lifecycle/release-cut.js +165 -16
  81. package/dist/lifecycle/release-publish.d.ts +18 -2
  82. package/dist/lifecycle/release-publish.d.ts.map +1 -1
  83. package/dist/lifecycle/release-publish.js +5 -0
  84. package/dist/lifecycle/release-revocation.d.ts +4 -3
  85. package/dist/lifecycle/release-revocation.d.ts.map +1 -1
  86. package/dist/lifecycle/release-revocation.js +5 -4
  87. package/dist/lifecycle/release-store.d.ts +32 -0
  88. package/dist/lifecycle/release-store.d.ts.map +1 -1
  89. package/dist/lifecycle/release-store.js +11 -0
  90. package/dist/lifecycle/snapshot-store.d.ts.map +1 -1
  91. package/dist/lifecycle/snapshot-store.js +17 -9
  92. package/dist/lifecycle/test-passkey.d.ts +25 -0
  93. package/dist/lifecycle/test-passkey.d.ts.map +1 -0
  94. package/dist/lifecycle/test-passkey.js +39 -0
  95. package/dist/notify.d.ts +23 -3
  96. package/dist/notify.d.ts.map +1 -1
  97. package/dist/notify.js +8 -2
  98. package/dist/notify.schema.json +12 -3
  99. package/dist/op/gate.d.ts +1 -1
  100. package/dist/op/gate.d.ts.map +1 -1
  101. package/dist/op/gate.js +2 -1
  102. package/dist/pr-forge.d.ts +20 -0
  103. package/dist/pr-forge.d.ts.map +1 -1
  104. package/dist/pr-forge.js +87 -8
  105. package/dist/release-floors.d.ts +1 -1
  106. package/dist/release-floors.js +1 -1
  107. package/dist/wave-runtime.mjs +333 -331
  108. package/dist/workspace/ci-builds.d.ts +21 -0
  109. package/dist/workspace/ci-builds.d.ts.map +1 -1
  110. package/dist/workspace/ci-builds.js +14 -0
  111. package/dist/workspace/ci-green.d.ts +45 -2
  112. package/dist/workspace/ci-green.d.ts.map +1 -1
  113. package/dist/workspace/ci-green.js +123 -5
  114. package/dist/workspace/ci-quarantine-report.d.ts +80 -0
  115. package/dist/workspace/ci-quarantine-report.d.ts.map +1 -0
  116. package/dist/workspace/ci-quarantine-report.js +204 -0
  117. package/dist/workspace/ci-quarantine.d.ts +73 -0
  118. package/dist/workspace/ci-quarantine.d.ts.map +1 -0
  119. package/dist/workspace/ci-quarantine.js +170 -0
  120. package/dist/workspace/ci-serve.d.ts.map +1 -1
  121. package/dist/workspace/ci-serve.js +7 -4
  122. package/dist/workspace/class-data.d.ts +3 -1
  123. package/dist/workspace/class-data.d.ts.map +1 -1
  124. package/dist/workspace/class-data.js +4 -1
  125. package/dist/workspace/declaration.d.ts +45 -2
  126. package/dist/workspace/declaration.d.ts.map +1 -1
  127. package/dist/workspace/declaration.js +45 -2
  128. package/dist/workspace/declaration.schema.json +51 -3
  129. package/dist/workspace/forge-work.d.ts +76 -0
  130. package/dist/workspace/forge-work.d.ts.map +1 -0
  131. package/dist/workspace/forge-work.js +160 -0
  132. package/dist/workspace/identity-gate-rule.d.ts +3 -2
  133. package/dist/workspace/identity-gate-rule.d.ts.map +1 -1
  134. package/dist/workspace/identity-gate-rule.js +5 -7
  135. package/dist/workspace/identity.d.ts +3 -2
  136. package/dist/workspace/identity.d.ts.map +1 -1
  137. package/dist/workspace/identity.js +6 -3
  138. package/dist/workspace/intent-cli.d.ts +3 -2
  139. package/dist/workspace/intent-cli.d.ts.map +1 -1
  140. package/dist/workspace/intent-cli.js +26 -5
  141. package/dist/workspace/intent-record.d.ts +3 -0
  142. package/dist/workspace/intent-record.d.ts.map +1 -1
  143. package/dist/workspace/intent-record.schema.json +32 -0
  144. package/dist/workspace/intent.d.ts +9 -0
  145. package/dist/workspace/intent.d.ts.map +1 -1
  146. package/dist/workspace/intent.js +2 -0
  147. package/dist/workspace/intent.schema.json +32 -0
  148. package/dist/workspace/kind-readers.d.ts.map +1 -1
  149. package/dist/workspace/kind-readers.js +2 -1
  150. package/dist/workspace/kinds.d.ts +6 -1
  151. package/dist/workspace/kinds.d.ts.map +1 -1
  152. package/dist/workspace/kinds.js +8 -3
  153. package/dist/workspace/plan-stale.schema.json +286 -0
  154. package/dist/workspace/release-candidates.d.ts +42 -7
  155. package/dist/workspace/release-candidates.d.ts.map +1 -1
  156. package/dist/workspace/release-candidates.js +64 -23
  157. package/dist/workspace/release-candidates.schema.json +55 -2
  158. package/dist/workspace/releases.schema.json +47 -0
  159. package/dist/workspace/trust/policy.d.ts +10 -0
  160. package/dist/workspace/trust/policy.d.ts.map +1 -1
  161. package/dist/workspace/trust/policy.js +19 -1
  162. package/dist/workspace/trust/run-commits.d.ts.map +1 -1
  163. package/dist/workspace/trust/run-commits.js +2 -1
  164. package/dist/workspace/trust/seal.d.ts.map +1 -1
  165. package/dist/workspace/trust/seal.js +34 -3
  166. package/dist/workspace/trust/trust-files.d.ts.map +1 -1
  167. package/dist/workspace/trust/trust-files.js +6 -1
  168. package/package.json +2 -1
  169. package/src/cli/handlers/approve-external-signature.test.ts +328 -0
  170. package/src/cli/handlers/approve.ts +206 -18
  171. package/src/cli/handlers/plan.ts +74 -0
  172. package/src/cli/handlers/pr.ts +2 -1
  173. package/src/cli/handlers/release.ts +84 -20
  174. package/src/cli/main.ts +48 -7
  175. package/src/cli/mcp/workspace-tools.ts +2 -1
  176. package/src/cli/parse-args.ts +33 -0
  177. package/src/cli/registry.ts +18 -2
  178. package/src/config.ts +8 -0
  179. package/src/gate-decision-bundle.test.ts +4 -2
  180. package/src/gate-decision.ts +11 -2
  181. package/src/gate-statement.schema.json +46 -0
  182. package/src/lifecycle/__fixtures__/publish-fakes.ts +125 -5
  183. package/src/lifecycle/gate-ledger.ts +34 -5
  184. package/src/lifecycle/gate-seal.ts +86 -15
  185. package/src/lifecycle/gate-statement.ts +144 -0
  186. package/src/lifecycle/gate-webauthn.test.ts +77 -0
  187. package/src/lifecycle/gate-webauthn.ts +133 -0
  188. package/src/lifecycle/git.ts +23 -19
  189. package/src/lifecycle/ledger-remote.test.ts +183 -0
  190. package/src/lifecycle/ledger-remote.ts +46 -0
  191. package/src/lifecycle/plan-stale.test.ts +149 -0
  192. package/src/lifecycle/plan-stale.ts +172 -0
  193. package/src/lifecycle/publish-credentials.ts +2 -0
  194. package/src/lifecycle/publish-declaration.ts +116 -1
  195. package/src/lifecycle/publish-forge.ts +14 -4
  196. package/src/lifecycle/publish-git-ssh.ts +202 -0
  197. package/src/lifecycle/publish-github.ts +174 -0
  198. package/src/lifecycle/publish-homebrew.test.ts +358 -0
  199. package/src/lifecycle/publish-homebrew.ts +283 -0
  200. package/src/lifecycle/publish-marketplace.test.ts +406 -0
  201. package/src/lifecycle/publish-marketplace.ts +421 -0
  202. package/src/lifecycle/publish-resume.test.ts +40 -0
  203. package/src/lifecycle/publish-target-context.test.ts +2 -2
  204. package/src/lifecycle/publish-targets.test.ts +23 -0
  205. package/src/lifecycle/publish-targets.ts +15 -0
  206. package/src/lifecycle/publish-tauri.test.ts +163 -0
  207. package/src/lifecycle/publish-tauri.ts +198 -0
  208. package/src/lifecycle/release-cut-lane.test.ts +177 -0
  209. package/src/lifecycle/release-cut-override.test.ts +213 -0
  210. package/src/lifecycle/release-cut.ts +198 -17
  211. package/src/lifecycle/release-publish.ts +23 -3
  212. package/src/lifecycle/release-revocation.ts +5 -4
  213. package/src/lifecycle/release-store.ts +44 -0
  214. package/src/lifecycle/snapshot-store.ts +16 -9
  215. package/src/lifecycle/test-passkey.ts +55 -0
  216. package/src/notify-bundle.test.ts +3 -1
  217. package/src/notify.schema.json +12 -3
  218. package/src/notify.ts +20 -3
  219. package/src/op/gate.ts +2 -1
  220. package/src/override-gate-bundle.test.ts +2 -0
  221. package/src/pr-forge-bundle.test.ts +2 -2
  222. package/src/pr-forge.test.ts +38 -0
  223. package/src/pr-forge.ts +93 -11
  224. package/src/pr-requires.test.ts +9 -0
  225. package/src/release-floors.ts +1 -1
  226. package/src/stage-hooks-bundle.test.ts +2 -0
  227. package/src/wave-runtime-bundle.test.ts +3 -2
  228. package/src/workspace/ci-builds.ts +27 -0
  229. package/src/workspace/ci-green-stale.test.ts +193 -0
  230. package/src/workspace/ci-green.ts +137 -6
  231. package/src/workspace/ci-quarantine-report.test.ts +145 -0
  232. package/src/workspace/ci-quarantine-report.ts +234 -0
  233. package/src/workspace/ci-quarantine.test.ts +160 -0
  234. package/src/workspace/ci-quarantine.ts +188 -0
  235. package/src/workspace/ci-serve.ts +7 -4
  236. package/src/workspace/class-data.ts +5 -1
  237. package/src/workspace/declaration.schema.json +51 -3
  238. package/src/workspace/declaration.test.ts +1 -0
  239. package/src/workspace/declaration.ts +88 -5
  240. package/src/workspace/forge-work.test.ts +143 -0
  241. package/src/workspace/forge-work.ts +195 -0
  242. package/src/workspace/identity-gate-rule.ts +6 -8
  243. package/src/workspace/identity.ts +6 -3
  244. package/src/workspace/intent-cli.ts +24 -5
  245. package/src/workspace/intent-record.schema.json +32 -0
  246. package/src/workspace/intent-record.ts +3 -0
  247. package/src/workspace/intent.schema.json +32 -0
  248. package/src/workspace/intent.ts +9 -0
  249. package/src/workspace/kind-readers.ts +2 -1
  250. package/src/workspace/kinds.test.ts +13 -0
  251. package/src/workspace/kinds.ts +12 -3
  252. package/src/workspace/plan-stale.schema.json +286 -0
  253. package/src/workspace/release-candidates.schema.json +55 -2
  254. package/src/workspace/release-candidates.test.ts +77 -4
  255. package/src/workspace/release-candidates.ts +80 -23
  256. package/src/workspace/releases.schema.json +47 -0
  257. package/src/workspace/trust/gate-seal.test.ts +44 -0
  258. package/src/workspace/trust/policy.ts +24 -1
  259. package/src/workspace/trust/run-commits.ts +2 -1
  260. package/src/workspace/trust/seal.ts +35 -3
  261. package/src/workspace/trust/trust-files.test.ts +5 -0
  262. package/src/workspace/trust/trust-files.ts +15 -1
@@ -10,6 +10,7 @@ import { getRuntime } from "../runtime-adapter";
10
10
  import { memberLedgerPrefix, resolveMemberLedger } from "./member-ledger";
11
11
  import { LIFECYCLE_LOCAL_NOTE } from "./local-note";
12
12
  import { ledgerRecordingOff, NO_RECORD_PUSH_NOTE, overlayTip, setOverlayTip } from "./no-record";
13
+ import { chooseLedgerRemote, lifecycleRemoteOverride, type LedgerRemoteChoice } from "./ledger-remote";
13
14
  import type { LedgerReadPort } from "./ledger-port";
14
15
 
15
16
  const STATE_BRANCH = "chant/lifecycle";
@@ -819,7 +820,7 @@ export async function pushLifecycleStatus(opts?: { cwd?: string }): Promise<Life
819
820
  const cwd = opts?.cwd;
820
821
  const found = await ledgerRemote(cwd);
821
822
  if (found === null) return { status: "no-remote" };
822
- if ("failed" in found) return { status: "failed", remote: "(unknown)", stderr: found.stderr };
823
+ if ("failed" in found) return { status: "failed", remote: found.named ?? "(unknown)", stderr: found.stderr };
823
824
  const { remote } = found;
824
825
 
825
826
  // Capture the lease SHA — if null, the remote ref doesn't exist yet
@@ -859,7 +860,7 @@ export async function pushLifecycleStatus(opts?: { cwd?: string }): Promise<Life
859
860
  * Returns false (without throwing) when no remote is configured, or when git
860
861
  * refused the push for a reason other than a stale lease.
861
862
  *
862
- * The remote is the ledger's ({@link ledgerRemote}: `origin` when there is one),
863
+ * The remote is the ledger's ({@link ledgerRemote}: the one `CHANT_LIFECYCLE_REMOTE` names, else `origin`),
863
864
  * the same one {@link fetchLifecycleStatus} reads, and a push that lands
864
865
  * records the tip it pushed as the remote-tracking ref, so the next push's
865
866
  * lease is right in a single-branch clone too (#3391).
@@ -1165,21 +1166,21 @@ const NON_FAST_FORWARD_RE = /non-fast-forward|rejected/i;
1165
1166
  const C_LOCALE_ENV = { LC_ALL: "C", LANGUAGE: "" };
1166
1167
 
1167
1168
  /**
1168
- * The remote the ledger lives on.
1169
+ * The remote the ledger lives on ({@link chooseLedgerRemote}).
1169
1170
  *
1170
- * `origin` when it exists, rather than whichever name sorts first — a repo
1171
- * with a `backup` remote alongside `origin` would otherwise fetch the ledger
1172
- * from `backup`. A non-zero exit is *not* read as "no remote": a git that
1173
- * failed to answer is not evidence that a project is single-machine, and
1174
- * treating it as one is what lets an unreadable ledger look empty.
1171
+ * The one `CHANT_LIFECYCLE_REMOTE` names (#4647), else `origin` when it
1172
+ * exists, rather than whichever name sorts first — a repo with a `backup`
1173
+ * remote alongside `origin` would otherwise fetch the ledger from `backup`.
1174
+ * A non-zero exit is *not* read as "no remote": a git that failed to answer
1175
+ * is not evidence that a project is single-machine, and treating it as one is
1176
+ * what lets an unreadable ledger look empty. Nor is a named remote the
1177
+ * repository lacks.
1175
1178
  */
1176
- async function ledgerRemote(cwd?: string): Promise<{ remote: string } | { failed: true; stderr: string } | null> {
1179
+ async function ledgerRemote(cwd?: string): Promise<LedgerRemoteChoice> {
1177
1180
  const rt = getRuntime();
1178
1181
  const result = await rt.spawn(["git", "remote"], { cwd, env: C_LOCALE_ENV });
1179
1182
  if (result.exitCode !== 0) return { failed: true, stderr: (result.stderr ?? "").trim() };
1180
- const names = result.stdout.trim().split("\n").map((n) => n.trim()).filter(Boolean);
1181
- if (names.length === 0) return null;
1182
- return { remote: names.includes("origin") ? "origin" : names[0] };
1183
+ return chooseLedgerRemote(result.stdout.trim().split("\n").map((n) => n.trim()).filter(Boolean));
1183
1184
  }
1184
1185
 
1185
1186
  /** A scratch ref this module owns, used to resolve the remote tip without touching the ledger branch. */
@@ -1208,7 +1209,7 @@ export async function fetchLifecycleStatus(opts?: { cwd?: string }): Promise<Lif
1208
1209
  const found = await ledgerRemote(cwd);
1209
1210
  if (found === null) return { status: "no-remote" };
1210
1211
  if ("failed" in found) {
1211
- return { status: "unreachable", remote: "(unknown)", stderr: found.stderr };
1212
+ return { status: "unreachable", remote: found.named ?? "(unknown)", stderr: found.stderr };
1212
1213
  }
1213
1214
  const { remote } = found;
1214
1215
 
@@ -1560,9 +1561,11 @@ export async function pushRefStatus(ref: string, opts?: { cwd?: string; expect?:
1560
1561
  // The lease still holds in this checkout, the way it does in one with no remote.
1561
1562
  if (ledgerRecordingOff()) return "no-remote";
1562
1563
  const rt = getRuntime();
1563
- const remoteResult = await rt.spawn(["git", "remote"], { cwd: opts?.cwd });
1564
- if (remoteResult.exitCode !== 0 || !remoteResult.stdout.trim()) return "no-remote";
1565
- const remote = remoteResult.stdout.trim().split("\n")[0];
1564
+ // #4647: the ledger's remote, so a lease ref goes where the branch does.
1565
+ const found = await ledgerRemote(opts?.cwd);
1566
+ if (found === null) return "no-remote";
1567
+ if ("failed" in found) return lifecycleRemoteOverride() === undefined ? "no-remote" : "rejected";
1568
+ const { remote } = found;
1566
1569
 
1567
1570
  let expected: string | null;
1568
1571
  if (opts?.expect !== undefined) {
@@ -1618,9 +1621,10 @@ export async function fetchRefIntoStatus(
1618
1621
  opts?: { cwd?: string },
1619
1622
  ): Promise<FetchRefStatus> {
1620
1623
  const rt = getRuntime();
1621
- const remoteResult = await rt.spawn(["git", "remote"], { cwd: opts?.cwd });
1622
- if (remoteResult.exitCode !== 0 || !remoteResult.stdout.trim()) return "no-remote";
1623
- const remote = remoteResult.stdout.trim().split("\n")[0];
1624
+ const found = await ledgerRemote(opts?.cwd);
1625
+ if (found === null) return "no-remote";
1626
+ if ("failed" in found) return lifecycleRemoteOverride() === undefined ? "no-remote" : "failed";
1627
+ const { remote } = found;
1624
1628
  const fetchResult = await rt.spawn(["git", "fetch", remote, `+${remoteRef}:${localRef}`], { cwd: opts?.cwd, env: C_LOCALE_ENV });
1625
1629
  if (fetchResult.exitCode === 0) return "fetched";
1626
1630
  return NO_SUCH_REMOTE_REF_RE.test(fetchResult.stderr ?? "") ? "missing" : "failed";
@@ -0,0 +1,183 @@
1
+ import { afterEach, describe, expect, test, vi } from "vitest";
2
+ import { spawnSync } from "node:child_process";
3
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { chooseLedgerRemote, LIFECYCLE_REMOTE_ENV, lifecycleRemoteOverride } from "./ledger-remote";
7
+ import {
8
+ fetchLifecycleStatus,
9
+ fetchRef,
10
+ pushLifecycleRebasing,
11
+ pushLifecycleReport,
12
+ pushLifecycleStatus,
13
+ pushRef,
14
+ readRefSha,
15
+ updateRefCAS,
16
+ writeBlob,
17
+ writeBlobToPath,
18
+ } from "./git";
19
+ import { NO_RECORD_ENV } from "./no-record";
20
+
21
+ function git(args: string[], cwd: string): string {
22
+ const r = spawnSync("git", args, { cwd, encoding: "utf-8" });
23
+ if (r.status !== 0) throw new Error(`git ${args.join(" ")}: ${r.stderr}`);
24
+ return r.stdout.trim();
25
+ }
26
+
27
+ function tip(repo: string, ref = "refs/heads/chant/lifecycle"): string | null {
28
+ const r = spawnSync("git", ["rev-parse", "--verify", "--quiet", ref], { cwd: repo, encoding: "utf-8" });
29
+ return r.status === 0 ? r.stdout.trim() : null;
30
+ }
31
+
32
+ /**
33
+ * Two checkouts, A and B, cloned from a bare `origin` that is not where the
34
+ * ledger belongs, each with a second remote `ledger` that is.
35
+ */
36
+ function setup(): { a: string; b: string; origin: string; ledger: string; root: string } {
37
+ const root = mkdtempSync(join(tmpdir(), "chant-ledger-remote-"));
38
+ const origin = join(root, "origin.git");
39
+ const ledger = join(root, "ledger.git");
40
+ git(["init", "-q", "--bare", "-b", "main", origin], root);
41
+ git(["init", "-q", "--bare", "-b", "main", ledger], root);
42
+ const seed = join(root, "seed");
43
+ git(["clone", "-q", origin, seed], root);
44
+ git(["config", "user.email", "seed@chant.dev"], seed);
45
+ git(["config", "user.name", "Seed"], seed);
46
+ writeFileSync(join(seed, "README.md"), "fixture\n");
47
+ git(["add", "README.md"], seed);
48
+ git(["commit", "-q", "-m", "init"], seed);
49
+ git(["push", "-q", "origin", "main"], seed);
50
+ const clone = (name: string): string => {
51
+ const dir = join(root, name);
52
+ git(["clone", "-q", origin, dir], root);
53
+ git(["config", "user.email", `${name}@chant.dev`], dir);
54
+ git(["config", "user.name", name], dir);
55
+ git(["remote", "add", "ledger", ledger], dir);
56
+ return dir;
57
+ };
58
+ return { a: clone("a"), b: clone("b"), origin, ledger, root };
59
+ }
60
+
61
+ afterEach(() => {
62
+ vi.unstubAllEnvs();
63
+ });
64
+
65
+ describe("chooseLedgerRemote", () => {
66
+ test("origin, else the first remote, when nothing is named", () => {
67
+ expect(chooseLedgerRemote(["backup", "origin"], {})).toEqual({ remote: "origin" });
68
+ expect(chooseLedgerRemote(["backup", "mirror"], {})).toEqual({ remote: "backup" });
69
+ expect(chooseLedgerRemote([], {})).toBeNull();
70
+ });
71
+
72
+ test("the remote CHANT_LIFECYCLE_REMOTE names, over origin", () => {
73
+ expect(chooseLedgerRemote(["origin", "ledger"], { [LIFECYCLE_REMOTE_ENV]: "ledger" })).toEqual({ remote: "ledger" });
74
+ expect(chooseLedgerRemote(["origin", "ledger"], { [LIFECYCLE_REMOTE_ENV]: " ledger " })).toEqual({ remote: "ledger" });
75
+ });
76
+
77
+ test("a name the repository has no remote by fails, and never falls back to origin", () => {
78
+ expect(chooseLedgerRemote(["origin"], { [LIFECYCLE_REMOTE_ENV]: "ledger" })).toEqual({
79
+ failed: true,
80
+ stderr: `${LIFECYCLE_REMOTE_ENV} names the remote "ledger", and this repository's remotes are origin`,
81
+ named: "ledger",
82
+ });
83
+ expect(chooseLedgerRemote([], { [LIFECYCLE_REMOTE_ENV]: "ledger" })).toMatchObject({ failed: true });
84
+ });
85
+
86
+ test("empty counts as unset", () => {
87
+ expect(lifecycleRemoteOverride({ [LIFECYCLE_REMOTE_ENV]: " " })).toBeUndefined();
88
+ expect(chooseLedgerRemote(["origin"], { [LIFECYCLE_REMOTE_ENV]: "" })).toEqual({ remote: "origin" });
89
+ });
90
+ });
91
+
92
+ describe("CHANT_LIFECYCLE_REMOTE (#4647)", () => {
93
+ test("the branch is pushed to and fetched from the named remote, with its remote-tracking ref, and origin is left alone", async () => {
94
+ const { a, b, origin, ledger, root } = setup();
95
+ try {
96
+ vi.stubEnv(LIFECYCLE_REMOTE_ENV, "ledger");
97
+ await writeBlobToPath("prod", "plan.json", '{"plan":1}', "plan", { cwd: a });
98
+ expect(await pushLifecycleStatus({ cwd: a })).toMatchObject({ status: "pushed", remote: "ledger" });
99
+ const pushed = tip(ledger);
100
+ expect(pushed).toBe(tip(a));
101
+ expect(tip(a, "refs/remotes/ledger/chant/lifecycle")).toBe(pushed);
102
+ expect(tip(origin)).toBeNull();
103
+ expect(tip(a, "refs/remotes/origin/chant/lifecycle")).toBeNull();
104
+
105
+ expect(await fetchLifecycleStatus({ cwd: b })).toEqual({ status: "fetched" });
106
+ expect(tip(b)).toBe(pushed);
107
+ expect(tip(b, "refs/remotes/ledger/chant/lifecycle")).toBe(pushed);
108
+ } finally {
109
+ rmSync(root, { recursive: true, force: true });
110
+ }
111
+ });
112
+
113
+ test("a push another writer beat to the named remote replays on its tip and lands there", async () => {
114
+ const { a, b, origin, ledger, root } = setup();
115
+ try {
116
+ vi.stubEnv(LIFECYCLE_REMOTE_ENV, "ledger");
117
+ await writeBlobToPath("prod", "seed.json", "{}", "seed", { cwd: a });
118
+ expect((await pushLifecycleReport({ cwd: a })).pushed).toBe(true);
119
+ expect((await fetchLifecycleStatus({ cwd: b })).status).toBe("fetched");
120
+
121
+ // A moves the ledger on behind B's back.
122
+ await writeBlobToPath("prod", "wave.json", '{"wave":1}', "wave", { cwd: a });
123
+ expect((await pushLifecycleReport({ cwd: a })).pushed).toBe(true);
124
+ await writeBlobToPath("prod", "merge.json", '{"merge":1}', "merge", { cwd: b });
125
+ expect(await pushLifecycleStatus({ cwd: b })).toMatchObject({ status: "stale", remote: "ledger" });
126
+
127
+ expect(await pushLifecycleRebasing({ cwd: b })).toEqual({ pushed: true });
128
+ const landed = tip(ledger)!;
129
+ expect(git(["show", `${landed}:prod/wave.json`], ledger)).toBe('{"wave":1}');
130
+ expect(git(["show", `${landed}:prod/merge.json`], ledger)).toBe('{"merge":1}');
131
+ expect(tip(b, "refs/remotes/ledger/chant/lifecycle")).toBe(landed);
132
+ expect(tip(origin)).toBeNull();
133
+ } finally {
134
+ rmSync(root, { recursive: true, force: true });
135
+ }
136
+ });
137
+
138
+ test("a lease ref goes to the named remote too", async () => {
139
+ const { a, b, origin, ledger, root } = setup();
140
+ try {
141
+ vi.stubEnv(LIFECYCLE_REMOTE_ENV, "ledger");
142
+ const ref = "refs/chant/lease/converge";
143
+ const blob = await writeBlob('{"holder":"a"}', { cwd: a });
144
+ await updateRefCAS(ref, blob, null, { cwd: a });
145
+ expect(await pushRef(ref, { cwd: a })).toBe(true);
146
+ expect(tip(ledger, ref)).toBe(blob);
147
+ expect(tip(origin, ref)).toBeNull();
148
+ expect(await fetchRef(ref, { cwd: b })).toBe(true);
149
+ expect(await readRefSha(ref, { cwd: b })).toBe(blob);
150
+ } finally {
151
+ rmSync(root, { recursive: true, force: true });
152
+ }
153
+ });
154
+
155
+ test("a name with no such remote fails the push, the fetch and a write, and sends nothing to origin", async () => {
156
+ const { a, origin, root } = setup();
157
+ try {
158
+ await writeBlobToPath("prod", "plan.json", "{}", "plan", { cwd: a });
159
+ vi.stubEnv(LIFECYCLE_REMOTE_ENV, "elsewhere");
160
+ const pushed = await pushLifecycleStatus({ cwd: a });
161
+ expect(pushed).toMatchObject({ status: "failed", remote: "elsewhere" });
162
+ expect(pushed.status === "failed" ? pushed.stderr : "").toBe(`${LIFECYCLE_REMOTE_ENV} names the remote "elsewhere", and this repository's remotes are ledger, origin`);
163
+ expect(await fetchLifecycleStatus({ cwd: a })).toMatchObject({ status: "unreachable", remote: "elsewhere" });
164
+ expect(await pushRef("refs/heads/chant/lifecycle", { cwd: a })).toBe(false);
165
+ expect(tip(origin)).toBeNull();
166
+ } finally {
167
+ rmSync(root, { recursive: true, force: true });
168
+ }
169
+ });
170
+
171
+ test("a run that records nothing pushes nothing to the named remote", async () => {
172
+ const { a, ledger, root } = setup();
173
+ try {
174
+ vi.stubEnv(LIFECYCLE_REMOTE_ENV, "ledger");
175
+ vi.stubEnv(NO_RECORD_ENV, "1");
176
+ await writeBlobToPath("prod", "plan.json", "{}", "plan", { cwd: a });
177
+ expect(await pushLifecycleStatus({ cwd: a })).toEqual({ status: "not-recorded" });
178
+ expect(tip(ledger)).toBeNull();
179
+ } finally {
180
+ rmSync(root, { recursive: true, force: true });
181
+ }
182
+ });
183
+ });
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Which remote `chant/lifecycle` is fetched from and pushed to (#4647).
3
+ *
4
+ * By default the ledger lives on `origin`, or on the first remote when there
5
+ * is no `origin`. `CHANT_LIFECYCLE_REMOTE=<name>` names another one, for a
6
+ * checkout whose `origin` is not where the ledger belongs (a deploy box that
7
+ * clones from a mirror, say). Every read and write of the ledger goes through
8
+ * here: the fetch, the push and its lease, the remote-tracking ref
9
+ * `refs/remotes/<remote>/chant/lifecycle`, and the lease and lock refs pushed
10
+ * beside the branch.
11
+ *
12
+ * A name the repository has no remote by is an error, never a fallback to
13
+ * `origin`: a ledger pushed to the wrong remote is what the setting exists to
14
+ * prevent.
15
+ *
16
+ * Kept free of git and the runtime adapter, so the synchronous readers (the
17
+ * trust checks, `ci base`, ci-serve) can use it too.
18
+ */
19
+
20
+ /** The environment variable that names the ledger's remote. */
21
+ export const LIFECYCLE_REMOTE_ENV = "CHANT_LIFECYCLE_REMOTE";
22
+
23
+ /** The remote `CHANT_LIFECYCLE_REMOTE` names, or undefined when it is unset or empty. */
24
+ export function lifecycleRemoteOverride(env: NodeJS.ProcessEnv = process.env): string | undefined {
25
+ const value = env[LIFECYCLE_REMOTE_ENV]?.trim();
26
+ return value ? value : undefined;
27
+ }
28
+
29
+ /** What {@link chooseLedgerRemote} found: a remote, no remote at all, or a setting that names none of them. */
30
+ export type LedgerRemoteChoice = { remote: string } | { failed: true; stderr: string; named?: string } | null;
31
+
32
+ /**
33
+ * The ledger's remote among `names`, the output of `git remote`: the one
34
+ * `CHANT_LIFECYCLE_REMOTE` names, else `origin`, else the first. Null when
35
+ * there is no remote and nothing is named.
36
+ */
37
+ export function chooseLedgerRemote(names: readonly string[], env: NodeJS.ProcessEnv = process.env): LedgerRemoteChoice {
38
+ const named = lifecycleRemoteOverride(env);
39
+ if (named !== undefined) {
40
+ if (names.includes(named)) return { remote: named };
41
+ const have = names.length === 0 ? "this repository has no remotes" : `this repository's remotes are ${names.join(", ")}`;
42
+ return { failed: true, stderr: `${LIFECYCLE_REMOTE_ENV} names the remote "${named}", and ${have}`, named };
43
+ }
44
+ if (names.length === 0) return null;
45
+ return { remote: names.includes("origin") ? "origin" : names[0] };
46
+ }
@@ -0,0 +1,149 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { afterAll, describe, expect, test } from "vitest";
6
+ import type { LedgerReadPort } from "./ledger-port";
7
+ import { writeBlobToPath } from "./git";
8
+ import { clearMemberLedgerCache } from "./member-ledger";
9
+ import { PLAN_STALE_FLOOR, PLAN_STALE_SCHEMA_ID, planStaleness } from "./plan-stale";
10
+ import { loadQueryData } from "./query";
11
+ import { planStaleDocument } from "../cli/handlers/plan";
12
+ import { loadAjv2020 } from "../workspace/ajv2020";
13
+ import planStaleSchema from "../workspace/plan-stale.schema.json";
14
+
15
+ /** A port over a map of `<dir>/<file>` to text, the shape `gitLedgerReadPort` reads. */
16
+ function port(files: Record<string, string>): LedgerReadPort {
17
+ const dirs = (): string[] => [...new Set(Object.keys(files).map((p) => p.slice(0, p.indexOf("/"))))];
18
+ return {
19
+ read: async (dir, file) => files[`${dir}/${file}`] ?? null,
20
+ list: async (dir) => Object.keys(files).filter((p) => p.startsWith(`${dir}/`)).map((p) => p.slice(dir.length + 1)),
21
+ trees: async () => dirs(),
22
+ };
23
+ }
24
+
25
+ const lines = (...rows: unknown[]): string => rows.map((r) => JSON.stringify(r)).join("\n") + "\n";
26
+ const P1 = `jcs1-sha256:${"1".repeat(64)}`;
27
+ const P2 = `jcs1-sha256:${"2".repeat(64)}`;
28
+ const P3 = `jcs1-sha256:${"3".repeat(64)}`;
29
+
30
+ /** The run that planned P1 reached gate `prod` of op `deploy` in env `prod` at 10:00. */
31
+ const planned = {
32
+ "_gates/deploy.jsonl": lines({ version: 1, kind: "pending", op: "deploy", gate: "prod", runId: "run-plan", gitSha: "a".repeat(40), timestamp: "2026-11-01T10:00:00Z", expiresAt: "2026-11-08T10:00:00Z", planDigest: P1 }),
33
+ "prod/runs__deploy.jsonl": lines({ version: 1, id: "run-plan", op: "deploy", env: "prod", started: "2026-11-01T09:59:00Z", ended: "2026-11-01T10:00:00Z", status: "gated", labels: { Env: "prod" }, outcomes: {}, phases: [], gate: { name: "prod", since: "2026-11-01T10:00:00Z" } }),
34
+ };
35
+
36
+ const applied = (op: string, planDigest: string, timestamp: string, runId: string) => ({ version: 1, kind: "applied", op, gate: "prod", planDigest, approvedAt: timestamp, approvedBy: "carol", timestamp, runId, commit: "b".repeat(40) });
37
+ const deploy = (env: string, timestamp: string, actor: string, runId: string) => ({ version: 1, component: "api", env, digest: "sha256:aa", gitSha: "c".repeat(40), runId, runOrigin: { forge: "github", url: `https://example.test/run/${runId}` }, timestamp, actor, approver: "dave" });
38
+
39
+ async function stale(files: Record<string, string>, digest = P1, member: string | null = null) {
40
+ const { data } = await loadQueryData([{ member, port: port(files) }]);
41
+ return planStaleness(data, digest, "0.0.0-test");
42
+ }
43
+
44
+ describe("chant plan stale (#4648)", () => {
45
+ test("an apply under an approval from another run after the plan makes it stale, and names who, when and which run", async () => {
46
+ const doc = await stale({
47
+ ...planned,
48
+ "_gates/deploy/applied.jsonl": lines(applied("deploy", P2, "2026-11-01T11:00:00Z", "run-laptop"), { version: 1, kind: "finished", op: "deploy", gate: "prod", planDigest: P2, applied: "2026-11-01T11:00:00Z", result: "failed", timestamp: "2026-11-01T11:05:00Z" }),
49
+ });
50
+ expect(doc).toMatchObject({
51
+ $schema: PLAN_STALE_SCHEMA_ID,
52
+ contract: 1,
53
+ digest: P1,
54
+ plan: { recordedAt: "2026-11-01T10:00:00Z", runId: "run-plan", gitSha: "a".repeat(40), targets: [{ member: null, op: "deploy", gate: "prod", environment: "prod" }] },
55
+ stale: true,
56
+ });
57
+ expect(!("error" in doc) && doc.applies).toEqual([
58
+ { source: "applies", member: null, op: "deploy", gate: "prod", environment: null, component: null, planDigest: P2, at: "2026-11-01T11:00:00Z", actor: null, approvedBy: "carol", runId: "run-laptop", runUrl: null, gitSha: "b".repeat(40), result: "failed" },
59
+ ]);
60
+ });
61
+
62
+ test("a deploy to the plan's environment after it makes it stale", async () => {
63
+ const doc = await stale({ ...planned, "prod/releases.jsonl": lines(deploy("prod", "2026-11-01T12:00:00Z", "laptop-alex", "ci-77")) });
64
+ expect(doc).toMatchObject({ stale: true, applies: [{ source: "deploys", environment: "prod", component: "api", actor: "laptop-alex", approvedBy: "dave", runId: "ci-77", runUrl: "https://example.test/run/ci-77", at: "2026-11-01T12:00:00Z" }] });
65
+ });
66
+
67
+ test("applies to unrelated targets, before the plan, or of the plan itself leave it current", async () => {
68
+ const doc = await stale({
69
+ ...planned,
70
+ // Another op, and this op before the plan was recorded.
71
+ "_gates/migrate/applied.jsonl": lines(applied("migrate", P3, "2026-11-01T11:00:00Z", "run-other")),
72
+ "_gates/deploy/applied.jsonl": lines(applied("deploy", P2, "2026-11-01T09:00:00Z", "run-earlier"), applied("deploy", P1, "2026-11-01T10:30:00Z", "run-this-plan")),
73
+ // Another environment, and this one before the plan.
74
+ "staging/releases.jsonl": lines(deploy("staging", "2026-11-01T12:00:00Z", "ci", "ci-1")),
75
+ "prod/releases.jsonl": lines(deploy("prod", "2026-11-01T09:30:00Z", "ci", "ci-0")),
76
+ });
77
+ expect(doc).toMatchObject({ stale: false, applies: [] });
78
+ });
79
+
80
+ test("another member's applies don't count", async () => {
81
+ const { data } = await loadQueryData([
82
+ { member: "app", port: port(planned) },
83
+ { member: "db", port: port({ "_gates/deploy/applied.jsonl": lines(applied("deploy", P2, "2026-11-01T11:00:00Z", "r")), "prod/releases.jsonl": lines(deploy("prod", "2026-11-01T12:00:00Z", "ci", "c")) }) },
84
+ ]);
85
+ expect(planStaleness(data, P1, "0.0.0-test")).toMatchObject({ plan: { targets: [{ member: "app" }] }, stale: false, applies: [] });
86
+ });
87
+
88
+ test("a component gate's own environment is the target, and a plan nobody recorded is null", async () => {
89
+ const component = {
90
+ "_gates/api.jsonl": lines({ version: 1, kind: "pending", op: "api", gate: "release", environment: "staging", timestamp: "2026-11-01T10:00:00Z", expiresAt: "2026-11-08T10:00:00Z", planDigest: P1 }),
91
+ "staging/releases.jsonl": lines(deploy("staging", "2026-11-01T10:01:00Z", "ci", "ci-2")),
92
+ };
93
+ expect(await stale(component)).toMatchObject({ plan: { targets: [{ op: "api", environment: "staging" }] }, stale: true, applies: [{ runId: "ci-2" }] });
94
+ expect(await stale(component, P3)).toMatchObject({ plan: null, stale: null, applies: [] });
95
+ });
96
+
97
+ test("its floor is the release it shipped in", () => {
98
+ expect(PLAN_STALE_FLOOR).toBe("0.124.63");
99
+ expect(planStaleSchema.description).toContain("written by chant 0.124.63 and newer");
100
+ });
101
+ });
102
+
103
+ describe("chant plan stale on a real ledger (#4648)", () => {
104
+ const scratch: string[] = [];
105
+ afterAll(() => {
106
+ for (const d of scratch) rmSync(d, { recursive: true, force: true });
107
+ });
108
+ const git = (args: string[], cwd: string): void => {
109
+ const r = spawnSync("git", args, { cwd, encoding: "utf-8" });
110
+ if (r.status !== 0) throw new Error(`git ${args.join(" ")}: ${r.stderr}`);
111
+ };
112
+
113
+ test("reads the local chant/lifecycle branch, and the document matches its schema", async () => {
114
+ clearMemberLedgerCache();
115
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), "chant-plan-stale-")));
116
+ scratch.push(dir);
117
+ git(["init", "-q", "-b", "main"], dir);
118
+ git(["config", "user.email", "test@chant.dev"], dir);
119
+ git(["config", "user.name", "Test"], dir);
120
+ writeFileSync(join(dir, "README.md"), "fixture\n");
121
+ git(["add", "README.md"], dir);
122
+ git(["commit", "-q", "-m", "init"], dir);
123
+ for (const [path, text] of Object.entries(planned)) {
124
+ const at = path.lastIndexOf("/");
125
+ await writeBlobToPath(path.slice(0, at), path.slice(at + 1), text, "fixture", { cwd: dir });
126
+ }
127
+ const Ajv = loadAjv2020();
128
+ const validate = new Ajv({ strict: false, allErrors: true }).compile(planStaleSchema) as ((d: unknown) => boolean) & { errors?: unknown };
129
+
130
+ const current = await planStaleDocument({ cwd: dir, digest: P1 });
131
+ expect(current).toMatchObject({ stale: false, applies: [] });
132
+ expect(validate(current), JSON.stringify(validate.errors)).toBe(true);
133
+
134
+ await writeBlobToPath("_gates/deploy", "applied.jsonl", lines(applied("deploy", P2, "2026-11-01T11:00:00Z", "run-other")), "Applied under prod", { cwd: dir });
135
+ const staled = await planStaleDocument({ cwd: dir, digest: P1 });
136
+ expect(staled).toMatchObject({ stale: true, applies: [{ source: "applies", runId: "run-other", approvedBy: "carol" }] });
137
+ expect(validate(staled), JSON.stringify(validate.errors)).toBe(true);
138
+
139
+ const unknown = await planStaleDocument({ cwd: dir, digest: P3 });
140
+ expect(unknown).toMatchObject({ plan: null, stale: null });
141
+ expect(validate(unknown), JSON.stringify(validate.errors)).toBe(true);
142
+
143
+ const nowhere = realpathSync(mkdtempSync(join(tmpdir(), "chant-plan-stale-nogit-")));
144
+ scratch.push(nowhere);
145
+ const failed = await planStaleDocument({ cwd: nowhere, digest: P1 });
146
+ expect(failed).toMatchObject({ error: { code: "not-a-git-repository" } });
147
+ expect(validate(failed), JSON.stringify(validate.errors)).toBe(true);
148
+ });
149
+ });
@@ -0,0 +1,172 @@
1
+ /**
2
+ * `chant plan stale <digest> --json` (#4648): whether anything applied to a
3
+ * plan's targets after the plan was recorded, so a platform can ask before it
4
+ * puts the plan in front of a person to approve. chant checks the digest
5
+ * again when the approved run applies; this read answers the same question
6
+ * earlier, and names the applies.
7
+ *
8
+ * The plan is the pending gate facts that record `digest` (`_gates/<op>.jsonl`).
9
+ * It was recorded at the earliest of them. Its targets are each fact's
10
+ * member, op and environment: the fact's own `environment` (a component
11
+ * gate's), else the `env` of the run that reached the gate.
12
+ *
13
+ * An apply touches a target when it was recorded after the plan and:
14
+ *
15
+ * - it is an apply under an approval (`_gates/<op>/applied.jsonl`, the
16
+ * `applies` table) of the same member and op, for another plan; or
17
+ * - it is a deploy record (`<env>/releases.jsonl`, the `deploys` table) of
18
+ * the same member and environment, of any component.
19
+ *
20
+ * An apply of this same plan doesn't make it stale. Neither does anything in
21
+ * another member or environment.
22
+ *
23
+ * Pure over the rows `chant query` loads (`./query.ts` {@link loadQueryData}):
24
+ * the caller reads the ledgers, and this reads no git and writes nothing.
25
+ */
26
+ import { samePlanDigest } from "./plan-digest";
27
+ import type { QueryData, QueryRow } from "./query";
28
+
29
+ /** The version of the `plan-stale` document this chant writes. */
30
+ export const PLAN_STALE_CONTRACT_VERSION = 1;
31
+
32
+ /** `$id` of the JSON Schema for `chant plan stale --json`. */
33
+ export const PLAN_STALE_SCHEMA_ID = "https://intentius.io/chant/schemas/workspace/plan-stale/v1/plan-stale.schema.json";
34
+
35
+ /** The first chant that answers `chant plan stale` (#4648). */
36
+ export const PLAN_STALE_FLOOR = "0.124.63";
37
+
38
+ /** Why the read stopped. Closed; each code is in `../workspace/reason-codes.ts`. */
39
+ export const PLAN_STALE_ERROR_CODES = ["not-a-git-repository", "ledger-unreadable"] as const;
40
+
41
+ /** One gate the plan waits at, and what it covers. */
42
+ export interface PlanStaleTarget {
43
+ member: string | null;
44
+ op: string;
45
+ gate: string;
46
+ /** The environment the plan is for, or null when neither the fact nor its run names one. */
47
+ environment: string | null;
48
+ }
49
+
50
+ /** One apply that touched a target after the plan was recorded. */
51
+ export interface PlanStaleApply {
52
+ /** Where it was read: `applies` for an apply under an approval, `deploys` for a deploy record. */
53
+ source: "applies" | "deploys";
54
+ member: string | null;
55
+ /** The op it applied under; null for a deploy record. */
56
+ op: string | null;
57
+ gate: string | null;
58
+ /** The environment; null for an apply under an approval, whose line names none. */
59
+ environment: string | null;
60
+ /** The component a deploy record deployed; null for an apply under an approval. */
61
+ component: string | null;
62
+ /** The plan it applied; null for a deploy record. */
63
+ planDigest: string | null;
64
+ /** When it was recorded. */
65
+ at: string;
66
+ /** Who ran it: a deploy record's `actor`; null for an apply under an approval, which names only its approver. */
67
+ actor: string | null;
68
+ approvedBy: string | null;
69
+ runId: string | null;
70
+ runUrl: string | null;
71
+ gitSha: string | null;
72
+ /** How an apply under an approval ended: `applied`, `failed`, or null while it has no finished line. Null for a deploy record. */
73
+ result: string | null;
74
+ }
75
+
76
+ export type PlanStaleDocument =
77
+ | {
78
+ $schema: string;
79
+ contract: number;
80
+ chant: string;
81
+ digest: string;
82
+ /** The plan, or null when no pending gate fact records the digest. */
83
+ plan: { recordedAt: string; runId: string | null; gitSha: string | null; targets: PlanStaleTarget[] } | null;
84
+ /** Whether any apply touched a target after the plan was recorded; null when there is no plan. */
85
+ stale: boolean | null;
86
+ /** Those applies, oldest first. */
87
+ applies: PlanStaleApply[];
88
+ }
89
+ | { $schema: string; contract: number; chant: string; error: { code: (typeof PLAN_STALE_ERROR_CODES)[number]; message: string } };
90
+
91
+ const text = (v: QueryRow[string] | undefined): string | null => (typeof v === "string" ? v : null);
92
+ const time = (iso: string): number => new Date(iso).getTime();
93
+
94
+ /** The document's head: `$schema`, `contract` and `chant`. */
95
+ export function planStaleHead(chant: string): { $schema: string; contract: number; chant: string } {
96
+ return { $schema: PLAN_STALE_SCHEMA_ID, contract: PLAN_STALE_CONTRACT_VERSION, chant };
97
+ }
98
+
99
+ /** Whether `digest`'s plan is stale, read from the rows of the `gates`, `runs`, `applies` and `deploys` tables. */
100
+ export function planStaleness(data: Pick<QueryData, "gates" | "runs" | "applies" | "deploys">, digest: string, chant: string): PlanStaleDocument {
101
+ const head = planStaleHead(chant);
102
+ const facts = data.gates.filter((g) => g.kind === "pending" && samePlanDigest(text(g.plan_digest) ?? undefined, digest) && typeof g.timestamp === "string");
103
+ if (facts.length === 0) return { ...head, digest, plan: null, stale: null, applies: [] };
104
+
105
+ const first = facts.reduce((a, b) => (time(String(b.timestamp)) < time(String(a.timestamp)) ? b : a));
106
+ const recordedAt = String(first.timestamp);
107
+ const since = time(recordedAt);
108
+ const runEnv = (member: string | null, runId: string | null): string | null => {
109
+ if (runId === null) return null;
110
+ const run = data.runs.find((r) => r.member === member && r.id === runId);
111
+ return run ? text(run.env) : null;
112
+ };
113
+ const targets: PlanStaleTarget[] = [];
114
+ for (const f of facts) {
115
+ const member = text(f.member);
116
+ const target = { member, op: String(f.op), gate: String(f.gate), environment: text(f.environment) ?? runEnv(member, text(f.run_id)) };
117
+ if (!targets.some((t) => t.member === target.member && t.op === target.op && t.gate === target.gate && t.environment === target.environment)) targets.push(target);
118
+ }
119
+
120
+ const applies: PlanStaleApply[] = [];
121
+ for (const a of data.applies) {
122
+ const at = text(a.timestamp);
123
+ if (at === null || !(time(at) > since)) continue;
124
+ if (samePlanDigest(text(a.plan_digest) ?? undefined, digest)) continue;
125
+ if (!targets.some((t) => t.member === text(a.member) && t.op === a.op)) continue;
126
+ applies.push({
127
+ source: "applies",
128
+ member: text(a.member),
129
+ op: text(a.op),
130
+ gate: text(a.gate),
131
+ environment: null,
132
+ component: null,
133
+ planDigest: text(a.plan_digest),
134
+ at,
135
+ actor: null,
136
+ approvedBy: text(a.approved_by),
137
+ runId: text(a.run_id),
138
+ runUrl: null,
139
+ gitSha: text(a.git_sha),
140
+ result: text(a.result),
141
+ });
142
+ }
143
+ for (const d of data.deploys) {
144
+ const at = text(d.timestamp);
145
+ if (at === null || !(time(at) > since)) continue;
146
+ if (!targets.some((t) => t.environment !== null && t.member === text(d.member) && t.environment === d.env)) continue;
147
+ applies.push({
148
+ source: "deploys",
149
+ member: text(d.member),
150
+ op: null,
151
+ gate: null,
152
+ environment: text(d.env),
153
+ component: text(d.component),
154
+ planDigest: null,
155
+ at,
156
+ actor: text(d.actor),
157
+ approvedBy: text(d.approver),
158
+ runId: text(d.run_id),
159
+ runUrl: text(d.run_url),
160
+ gitSha: text(d.git_sha),
161
+ result: null,
162
+ });
163
+ }
164
+ applies.sort((x, y) => time(x.at) - time(y.at));
165
+ return {
166
+ ...head,
167
+ digest,
168
+ plan: { recordedAt, runId: text(first.run_id), gitSha: text(first.git_sha), targets },
169
+ stale: applies.length > 0,
170
+ applies,
171
+ };
172
+ }
@@ -31,6 +31,8 @@ export const TOKEN_ENV_VARS = [
31
31
  "GITEA_TOKEN",
32
32
  "OCI_PASSWORD",
33
33
  "DOCKER_PASSWORD",
34
+ "VSCE_PAT",
35
+ "OVSX_PAT",
34
36
  ] as const;
35
37
 
36
38
  /** What a masked value is replaced with. */