@intentius/chant 0.89.0 → 0.91.0

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 (194) hide show
  1. package/dist/cli/handlers/components.d.ts +8 -0
  2. package/dist/cli/handlers/components.d.ts.map +1 -1
  3. package/dist/cli/handlers/operator.d.ts +14 -0
  4. package/dist/cli/handlers/operator.d.ts.map +1 -1
  5. package/dist/cli/handlers/run.d.ts.map +1 -1
  6. package/dist/cli/handlers/serve.d.ts.map +1 -1
  7. package/dist/cli/main.d.ts.map +1 -1
  8. package/dist/cli/mcp/server.d.ts +10 -5
  9. package/dist/cli/mcp/server.d.ts.map +1 -1
  10. package/dist/cli/mcp/types.d.ts +13 -5
  11. package/dist/cli/mcp/types.d.ts.map +1 -1
  12. package/dist/cli/mcp/workspace-tools.d.ts +55 -0
  13. package/dist/cli/mcp/workspace-tools.d.ts.map +1 -0
  14. package/dist/cli/registry.d.ts +31 -0
  15. package/dist/cli/registry.d.ts.map +1 -1
  16. package/dist/components/verbs/vuln-scan.d.ts +72 -0
  17. package/dist/components/verbs/vuln-scan.d.ts.map +1 -1
  18. package/dist/lifecycle/git.d.ts +40 -5
  19. package/dist/lifecycle/git.d.ts.map +1 -1
  20. package/dist/lifecycle/lease.d.ts +72 -16
  21. package/dist/lifecycle/lease.d.ts.map +1 -1
  22. package/dist/lifecycle/member-ledger.d.ts +3 -2
  23. package/dist/lifecycle/member-ledger.d.ts.map +1 -1
  24. package/dist/lifecycle/plan-ledger.d.ts +114 -0
  25. package/dist/lifecycle/plan-ledger.d.ts.map +1 -0
  26. package/dist/lifecycle/work-lease.d.ts +140 -0
  27. package/dist/lifecycle/work-lease.d.ts.map +1 -0
  28. package/dist/op/activities/activity-contracts.d.ts +2 -2
  29. package/dist/op/builders.d.ts.map +1 -1
  30. package/dist/op/discover.d.ts +25 -0
  31. package/dist/op/discover.d.ts.map +1 -1
  32. package/dist/op/index.d.ts +9 -3
  33. package/dist/op/index.d.ts.map +1 -1
  34. package/dist/op/lifecycle-receipt-store.d.ts +34 -0
  35. package/dist/op/lifecycle-receipt-store.d.ts.map +1 -0
  36. package/dist/op/local-executor.d.ts +19 -0
  37. package/dist/op/local-executor.d.ts.map +1 -1
  38. package/dist/op/local-output.d.ts.map +1 -1
  39. package/dist/op/op-ir.d.ts +10 -1
  40. package/dist/op/op-ir.d.ts.map +1 -1
  41. package/dist/op/op-verb-class.d.ts.map +1 -1
  42. package/dist/op/operator.d.ts +29 -0
  43. package/dist/op/operator.d.ts.map +1 -1
  44. package/dist/op/runtime.d.ts +9 -0
  45. package/dist/op/runtime.d.ts.map +1 -1
  46. package/dist/op/runtimes/local.d.ts.map +1 -1
  47. package/dist/op/step-output-ref.d.ts +2 -2
  48. package/dist/op/step-output-ref.d.ts.map +1 -1
  49. package/dist/op/steward.d.ts +140 -0
  50. package/dist/op/steward.d.ts.map +1 -0
  51. package/dist/op/types.d.ts +51 -0
  52. package/dist/op/types.d.ts.map +1 -1
  53. package/dist/op/work-lease-decl.d.ts +18 -0
  54. package/dist/op/work-lease-decl.d.ts.map +1 -0
  55. package/dist/op/work-lease-run.d.ts +173 -0
  56. package/dist/op/work-lease-run.d.ts.map +1 -0
  57. package/dist/workspace/box-isolation.d.ts +99 -0
  58. package/dist/workspace/box-isolation.d.ts.map +1 -0
  59. package/dist/workspace/checks/box-isolation.d.ts +18 -0
  60. package/dist/workspace/checks/box-isolation.d.ts.map +1 -0
  61. package/dist/workspace/checks/boxes.d.ts +71 -0
  62. package/dist/workspace/checks/boxes.d.ts.map +1 -0
  63. package/dist/workspace/checks/records.d.ts +1 -0
  64. package/dist/workspace/checks/records.d.ts.map +1 -1
  65. package/dist/workspace/checks.d.ts +10 -1
  66. package/dist/workspace/checks.d.ts.map +1 -1
  67. package/dist/workspace/conformance/index.d.ts +42 -2
  68. package/dist/workspace/conformance/index.d.ts.map +1 -1
  69. package/dist/workspace/conformance/vitest.d.ts.map +1 -1
  70. package/dist/workspace/decide.d.ts +184 -0
  71. package/dist/workspace/decide.d.ts.map +1 -0
  72. package/dist/workspace/decision-points.schema.json +137 -0
  73. package/dist/workspace/declaration.d.ts +51 -0
  74. package/dist/workspace/declaration.d.ts.map +1 -1
  75. package/dist/workspace/declaration.schema.json +172 -0
  76. package/dist/workspace/declared-kinds.d.ts +12 -0
  77. package/dist/workspace/declared-kinds.d.ts.map +1 -1
  78. package/dist/workspace/points-cli.d.ts +113 -0
  79. package/dist/workspace/points-cli.d.ts.map +1 -0
  80. package/dist/workspace/points.d.ts +320 -0
  81. package/dist/workspace/points.d.ts.map +1 -0
  82. package/dist/workspace/reason-codes.d.ts +29 -0
  83. package/dist/workspace/reason-codes.d.ts.map +1 -1
  84. package/dist/workspace/record-assets.d.ts.map +1 -1
  85. package/dist/workspace/records-cli.d.ts +12 -0
  86. package/dist/workspace/records-cli.d.ts.map +1 -1
  87. package/dist/workspace/records-write.d.ts +35 -3
  88. package/dist/workspace/records-write.d.ts.map +1 -1
  89. package/dist/workspace/records.d.ts +12 -3
  90. package/dist/workspace/records.d.ts.map +1 -1
  91. package/dist/workspace/source-block.d.ts +85 -0
  92. package/dist/workspace/source-block.d.ts.map +1 -0
  93. package/dist/workspace/status-stewards.d.ts +121 -0
  94. package/dist/workspace/status-stewards.d.ts.map +1 -0
  95. package/dist/workspace/status.d.ts +52 -1
  96. package/dist/workspace/status.d.ts.map +1 -1
  97. package/dist/workspace/work-cli.d.ts +78 -0
  98. package/dist/workspace/work-cli.d.ts.map +1 -0
  99. package/package.json +1 -1
  100. package/src/cli/handlers/components.test.ts +93 -0
  101. package/src/cli/handlers/components.ts +44 -3
  102. package/src/cli/handlers/operator.ts +107 -2
  103. package/src/cli/handlers/run.test.ts +19 -0
  104. package/src/cli/handlers/run.ts +53 -1
  105. package/src/cli/handlers/serve.ts +2 -1
  106. package/src/cli/main.test.ts +40 -0
  107. package/src/cli/main.ts +78 -2
  108. package/src/cli/mcp/docs-parity.test.ts +20 -2
  109. package/src/cli/mcp/server.ts +23 -6
  110. package/src/cli/mcp/types.ts +15 -2
  111. package/src/cli/mcp/workspace-tools.test.ts +211 -0
  112. package/src/cli/mcp/workspace-tools.ts +449 -0
  113. package/src/cli/registry.ts +31 -0
  114. package/src/components/verbs/vuln-scan.test.ts +124 -1
  115. package/src/components/verbs/vuln-scan.ts +142 -1
  116. package/src/lifecycle/git.ts +65 -15
  117. package/src/lifecycle/lease.test.ts +22 -0
  118. package/src/lifecycle/lease.ts +133 -29
  119. package/src/lifecycle/member-ledger.ts +3 -2
  120. package/src/lifecycle/plan-ledger.test.ts +148 -0
  121. package/src/lifecycle/plan-ledger.ts +158 -0
  122. package/src/lifecycle/work-lease.test.ts +236 -0
  123. package/src/lifecycle/work-lease.ts +426 -0
  124. package/src/op/builders.ts +5 -0
  125. package/src/op/discover.ts +71 -0
  126. package/src/op/index.ts +16 -3
  127. package/src/op/lifecycle-receipt-store.test.ts +60 -0
  128. package/src/op/lifecycle-receipt-store.ts +61 -0
  129. package/src/op/local-executor.ts +216 -18
  130. package/src/op/local-output.ts +13 -0
  131. package/src/op/op-ir.ts +14 -0
  132. package/src/op/op-verb-class.ts +6 -0
  133. package/src/op/operator.ts +75 -4
  134. package/src/op/runtime.ts +6 -0
  135. package/src/op/runtimes/local.ts +3 -0
  136. package/src/op/step-output-ref.ts +6 -2
  137. package/src/op/steward.test.ts +212 -0
  138. package/src/op/steward.ts +253 -0
  139. package/src/op/types.ts +53 -0
  140. package/src/op/work-lease-decl.ts +80 -0
  141. package/src/op/work-lease-run.test.ts +326 -0
  142. package/src/op/work-lease-run.ts +395 -0
  143. package/src/workspace/box-isolation.test.ts +261 -0
  144. package/src/workspace/box-isolation.ts +205 -0
  145. package/src/workspace/check-contract.test.ts +3 -1
  146. package/src/workspace/check.schema.json +15 -7
  147. package/src/workspace/checks/box-isolation.ts +68 -0
  148. package/src/workspace/checks/boxes.test.ts +197 -0
  149. package/src/workspace/checks/boxes.ts +307 -0
  150. package/src/workspace/checks/records.ts +25 -0
  151. package/src/workspace/checks.test.ts +7 -0
  152. package/src/workspace/checks.ts +19 -2
  153. package/src/workspace/conformance/__fixture__/decisions/decision.kind.mjs +4 -0
  154. package/src/workspace/conformance/__fixture__/decisions/decision.schema.json +100 -6
  155. package/src/workspace/conformance/index.mjs +3 -0
  156. package/src/workspace/conformance/index.ts +185 -7
  157. package/src/workspace/conformance/vitest.ts +17 -8
  158. package/src/workspace/decide.test.ts +224 -0
  159. package/src/workspace/decide.ts +576 -0
  160. package/src/workspace/decision-points.schema.json +137 -0
  161. package/src/workspace/declaration.schema.json +172 -0
  162. package/src/workspace/declaration.ts +137 -0
  163. package/src/workspace/declared-kinds.ts +25 -2
  164. package/src/workspace/intent.schema.json +4 -1
  165. package/src/workspace/point-answer.schema.json +95 -0
  166. package/src/workspace/points-cli.ts +273 -0
  167. package/src/workspace/points-write.schema.json +489 -0
  168. package/src/workspace/points.schema.json +710 -0
  169. package/src/workspace/points.test.ts +264 -0
  170. package/src/workspace/points.ts +564 -0
  171. package/src/workspace/read-contract.test.ts +18 -1
  172. package/src/workspace/reason-codes.test.ts +14 -1
  173. package/src/workspace/reason-codes.ts +36 -0
  174. package/src/workspace/record-assets.test.ts +3 -2
  175. package/src/workspace/record-assets.ts +4 -1
  176. package/src/workspace/records-amend.schema.json +2 -1
  177. package/src/workspace/records-cli.ts +15 -2
  178. package/src/workspace/records-close.schema.json +2 -1
  179. package/src/workspace/records-contract.test.ts +3 -2
  180. package/src/workspace/records-new.schema.json +4 -1
  181. package/src/workspace/records-review.schema.json +2 -1
  182. package/src/workspace/records-write.ts +85 -7
  183. package/src/workspace/records.schema.json +18 -0
  184. package/src/workspace/records.ts +61 -3
  185. package/src/workspace/source-block.test.ts +167 -0
  186. package/src/workspace/source-block.ts +129 -0
  187. package/src/workspace/status-contract.test.ts +178 -0
  188. package/src/workspace/status-stewards.ts +225 -0
  189. package/src/workspace/status.schema.json +230 -4
  190. package/src/workspace/status.ts +106 -5
  191. package/src/workspace/work-cli.test.ts +180 -0
  192. package/src/workspace/work-cli.ts +246 -0
  193. package/src/workspace/work-lease.schema.json +233 -0
  194. package/src/workspace/work-readiness-chud.test.ts +145 -0
@@ -0,0 +1,148 @@
1
+ import { describe, test, expect } from "vitest";
2
+ import { withTestDir } from "@intentius/chant-test-utils";
3
+ import { spawnSync } from "node:child_process";
4
+ import { writeFileSync, mkdirSync } from "node:fs";
5
+ import { join } from "node:path";
6
+ import { persistReleasePlan, readReleasePlan, InvalidReleasePlanError, type ReleasePlan } from "./plan-ledger";
7
+ import { readRefSha } from "./git";
8
+
9
+ function git(args: string[], cwd: string): { stdout: string; exitCode: number } {
10
+ const r = spawnSync("git", args, { cwd, encoding: "utf-8" });
11
+ return { stdout: r.stdout ?? "", exitCode: r.status ?? -1 };
12
+ }
13
+
14
+ async function initRepo(dir: string): Promise<void> {
15
+ git(["init", "-q", "-b", "main"], dir);
16
+ git(["config", "user.email", "test@chant.dev"], dir);
17
+ git(["config", "user.name", "Test"], dir);
18
+ writeFileSync(join(dir, "README.md"), "fixture\n");
19
+ git(["add", "README.md"], dir);
20
+ git(["commit", "-q", "-m", "init"], dir);
21
+ }
22
+
23
+ function makePlan(digest: string, extra: Record<string, unknown> = {}): ReleasePlan {
24
+ return { digest, release: "r-abc12345", units: [{ id: "w-1", contract: "c-1" }], evidence: [], ...extra };
25
+ }
26
+
27
+ describe("lifecycle/plan-ledger", () => {
28
+ describe("persistReleasePlan / readReleasePlan", () => {
29
+ test("round-trips a plan by its own digest", async () => {
30
+ await withTestDir(async (dir) => {
31
+ await initRepo(dir);
32
+ const plan = makePlan("sha256:" + "1".repeat(64));
33
+
34
+ const { commit, written } = await persistReleasePlan(plan, { cwd: dir });
35
+ expect(written).toBe(true);
36
+ expect(commit).toMatch(/^[0-9a-f]{40}$/);
37
+
38
+ const readBack = await readReleasePlan(plan.digest, { cwd: dir });
39
+ expect(readBack).toEqual(plan);
40
+ });
41
+ });
42
+
43
+ test("readReleasePlan returns null for an unknown digest", async () => {
44
+ await withTestDir(async (dir) => {
45
+ await initRepo(dir);
46
+ expect(await readReleasePlan("sha256:doesnotexist", { cwd: dir })).toBeNull();
47
+ });
48
+ });
49
+
50
+ test("a plan already written is never rewritten: no second commit, content unchanged", async () => {
51
+ await withTestDir(async (dir) => {
52
+ await initRepo(dir);
53
+ const plan = makePlan("sha256:" + "2".repeat(64));
54
+
55
+ const first = await persistReleasePlan(plan, { cwd: dir });
56
+ expect(first.written).toBe(true);
57
+ const tipAfterFirst = await readRefSha("refs/heads/chant/lifecycle", { cwd: dir });
58
+
59
+ const second = await persistReleasePlan(plan, { cwd: dir });
60
+ expect(second.written).toBe(false);
61
+ expect(second.commit).toBeNull();
62
+ const tipAfterSecond = await readRefSha("refs/heads/chant/lifecycle", { cwd: dir });
63
+
64
+ // Not a new commit — the branch tip is unchanged.
65
+ expect(tipAfterSecond).toBe(tipAfterFirst);
66
+ expect(await readReleasePlan(plan.digest, { cwd: dir })).toEqual(plan);
67
+ });
68
+ });
69
+
70
+ test("a plan with a different digest is a separate entry, coexisting with the first", async () => {
71
+ await withTestDir(async (dir) => {
72
+ await initRepo(dir);
73
+ const planA = makePlan("sha256:" + "a".repeat(64), { release: "r-a" });
74
+ const planB = makePlan("sha256:" + "b".repeat(64), { release: "r-b" });
75
+
76
+ await persistReleasePlan(planA, { cwd: dir });
77
+ await persistReleasePlan(planB, { cwd: dir });
78
+
79
+ expect(await readReleasePlan(planA.digest, { cwd: dir })).toEqual(planA);
80
+ expect(await readReleasePlan(planB.digest, { cwd: dir })).toEqual(planB);
81
+ });
82
+ });
83
+
84
+ test("refuses a plan with no digest field", async () => {
85
+ await withTestDir(async (dir) => {
86
+ await initRepo(dir);
87
+ const plan = { release: "r-nodigest" } as unknown as ReleasePlan;
88
+ await expect(persistReleasePlan(plan, { cwd: dir })).rejects.toThrow(InvalidReleasePlanError);
89
+ });
90
+ });
91
+
92
+ test("release ledger and plan store coexist on the same orphan branch", async () => {
93
+ const { appendReleaseRecord, readReleaseLedger } = await import("./release-ledger");
94
+ await withTestDir(async (dir) => {
95
+ await initRepo(dir);
96
+ const plan = makePlan("sha256:" + "3".repeat(64));
97
+ await persistReleasePlan(plan, { cwd: dir });
98
+ await appendReleaseRecord(
99
+ {
100
+ component: "svc",
101
+ env: "prod",
102
+ digest: plan.digest,
103
+ gitSha: "deadbeef",
104
+ runId: "run-1",
105
+ timestamp: "2026-01-01T00:00:00.000Z",
106
+ actor: "ci-bot",
107
+ },
108
+ { cwd: dir },
109
+ );
110
+
111
+ expect(await readReleasePlan(plan.digest, { cwd: dir })).toEqual(plan);
112
+ const { records } = await readReleaseLedger("prod", { cwd: dir });
113
+ expect(records).toHaveLength(1);
114
+ expect(records[0].digest).toBe(plan.digest);
115
+ });
116
+ });
117
+
118
+ test("a member's plan lives under _members/<member>/_plans/ (#2524 D7), reached via the prefix readReleasePlan takes", async () => {
119
+ await withTestDir(async (dir) => {
120
+ await initRepo(dir);
121
+ mkdirSync(join(dir, "apps", "web"), { recursive: true });
122
+ writeFileSync(join(dir, "chant.workspace.json"), JSON.stringify({
123
+ name: "acme",
124
+ schema: 1,
125
+ members: [{ name: "web", dir: "apps/web", kind: "chant" }],
126
+ }));
127
+ writeFileSync(join(dir, "apps", "web", "chant.config.ts"), "");
128
+ git(["add", "-A"], dir);
129
+ git(["commit", "-q", "-m", "workspace"], dir);
130
+
131
+ const plan = makePlan("sha256:" + "4".repeat(64));
132
+ // Persisted from inside the member's own directory, the way `chant
133
+ // components release` runs there — writeBlobToPath resolves the
134
+ // _members/web/ prefix automatically from cwd.
135
+ const webDir = join(dir, "apps", "web");
136
+ await persistReleasePlan(plan, { cwd: webDir });
137
+
138
+ // readReleasePlan reads it back two ways: with the matching prefix
139
+ // (as ../workspace/status.ts resolves it for a "members"-layout
140
+ // release), and directly at the branch path it actually landed on.
141
+ expect(await readReleasePlan(plan.digest, { cwd: dir, prefix: "_members/web/" })).toEqual(plan);
142
+ const raw = git(["show", `chant/lifecycle:_members/web/_plans/sha256_${"4".repeat(64)}.json`], dir);
143
+ expect(raw.exitCode).toBe(0);
144
+ expect(JSON.parse(raw.stdout)).toEqual(plan);
145
+ });
146
+ });
147
+ });
148
+ });
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Release plan store (ws-055, #2733, part of the chud retirement epic
3
+ * #2715): persists a release plan — the work items and evidence a release
4
+ * ships — to the `chant/lifecycle` orphan branch, content-addressed by the
5
+ * plan's own digest.
6
+ *
7
+ * **Why this exists.** ws-055 (docs/design/decisions/ws-055-dev-model-
8
+ * ledgers.md) decided where a development model's plans live: "a release
9
+ * plan is written content-addressed to `_plans/<digest>.json` on
10
+ * chant/lifecycle, and the release ledger record already names that
11
+ * digest." A `ReleaseRecord.digest` (../lifecycle/release-ledger.ts) is
12
+ * ordinarily an artifact digest; for a release a runner (the studio kit
13
+ * today, chud before it) plans work-item by work-item, that same field
14
+ * *is* the plan's own digest — the release ledger needs no new field to
15
+ * point at it, it already names the plan. Reading a release through the
16
+ * read contract (../workspace/status.ts) resolves that digest to the plan
17
+ * exactly the way it already resolves a build archive digest to a
18
+ * `BuildArchiveManifest` (./build-ledger-store.ts) — this module is that
19
+ * store's plan-shaped sibling, same plumbing, same directory-per-kind
20
+ * convention on the one orphan branch.
21
+ *
22
+ * **Storage.** Reuses `writeBlobToPath`/`readBlobFromPath` (./git.ts) —
23
+ * the identical hash-object -> mktree -> commit-tree -> update-ref
24
+ * pipeline `writeSnapshot`/`persistBuildManifest` already use. Plans live
25
+ * under a fixed top-level `_plans/` directory, a peer of `_builds/` and the
26
+ * per-env directories, never nested inside one — a plan is not env-scoped,
27
+ * it is named by its own content. Per #2524 D7 / #2538, `writeBlobToPath`'s
28
+ * `ledgerDir` already folds a workspace member's own `_members/<member>/`
29
+ * prefix in ahead of `_plans/`, so a member's plans live at
30
+ * `_members/<member>/_plans/<digest>.json` the same way its build records
31
+ * live at `_members/<member>/_builds/` — this module does nothing itself
32
+ * to earn that; it falls out of reusing the shared plumbing.
33
+ *
34
+ * **Content-addressed, keyed by the plan's own `digest`.** One file per
35
+ * plan, `_plans/<digest-with-":"->"_">.json` (`:` is not usable in a git
36
+ * tree entry name the way `readBlobFromPath`'s `<ref>:<path>` spelling
37
+ * reads it back, the same reason `./build-ledger-store.ts` substitutes it
38
+ * for `_builds/`). The digest is computed by whoever plans the release —
39
+ * the release Op, or a runner like the studio kit — not by chant; this
40
+ * module only trusts and stores it, exactly as `persistBuildManifest`
41
+ * trusts a manifest's own `manifestDigest`.
42
+ *
43
+ * **A plan already written is never rewritten (#2733 acceptance).**
44
+ * Unlike `persistBuildManifest`, which writes unconditionally every call
45
+ * (safe only because identical content produces an identical blob and,
46
+ * usually, an identical tree — but still a new, redundant commit on the
47
+ * branch each time), `persistReleasePlan` reads the path first and returns
48
+ * without writing when a plan is already stored under that digest. A plan
49
+ * is immutable by construction (it is named by a hash of its own content),
50
+ * so there is never a reason to overwrite one — only ever a reason to skip
51
+ * the write.
52
+ */
53
+
54
+ import { sortedJsonReplacer } from "../utils";
55
+ import { writeBlobToPath, readBlobFromPath, RefCASConflictError } from "./git";
56
+
57
+ /** Fixed top-level directory on the `chant/lifecycle` orphan branch that holds every persisted release plan — a peer of `_builds/` and the per-env directories, never nested inside one (see module doc for why). */
58
+ const PLANS_DIR = "_plans";
59
+
60
+ /**
61
+ * A release plan (ws-055): the work items and evidence a release ships.
62
+ * chant does not own this shape — it is a runner's own record, the way a
63
+ * record kind's schema is the kind's own (../workspace/records.ts) — only
64
+ * `digest` is required, since it is the storage key. Every other field is
65
+ * read back and returned exactly as written.
66
+ */
67
+ export interface ReleasePlan {
68
+ /**
69
+ * Content-addressed digest of this plan (`sha256:...`) — the same digest
70
+ * the release ledger record names (`ReleaseRecord.digest`,
71
+ * ../lifecycle/release-ledger.ts), so a record leads to its plan.
72
+ * Computed by the caller before persisting; this module trusts it rather
73
+ * than recomputing it, the same way `persistBuildManifest` trusts a
74
+ * manifest's own `manifestDigest`.
75
+ */
76
+ digest: string;
77
+ [key: string]: unknown;
78
+ }
79
+
80
+ /** Thrown by `persistReleasePlan` when the plan carries no usable `digest` — a plan can't be content-addressed without one. */
81
+ export class InvalidReleasePlanError extends Error {
82
+ constructor(message: string) {
83
+ super(message);
84
+ this.name = "InvalidReleasePlanError";
85
+ }
86
+ }
87
+
88
+ /** Turn a `sha256:...`-style digest into a filesystem/git-tree-safe filename stem. */
89
+ function digestToFilenameStem(digest: string): string {
90
+ return digest.replace(/:/g, "_");
91
+ }
92
+
93
+ function planFilename(digest: string): string {
94
+ return `${digestToFilenameStem(digest)}.json`;
95
+ }
96
+
97
+ /**
98
+ * Persist a release plan to the orphan branch, keyed by its own `digest`.
99
+ * Does not push to the remote — call `pushLifecycle` (./git.ts) afterward,
100
+ * the same two-step (`write` then `push`) shape `appendReleaseRecord`/
101
+ * `persistBuildManifest` use, so a caller persisting a plan alongside the
102
+ * release record it names can batch both into one push.
103
+ *
104
+ * Never rewrites a plan already stored under `plan.digest` (#2733
105
+ * acceptance) — reads the path first, and returns `{ commit: null, written:
106
+ * false }` without writing when it is already there. A `RefCASConflictError`
107
+ * from a genuine race (another writer persisted the same digest's plan
108
+ * between this call's read and its write) is treated the same way: the
109
+ * plan is content-addressed, so whatever is already at that path under this
110
+ * digest is authoritative, never overwritten.
111
+ */
112
+ export async function persistReleasePlan(
113
+ plan: ReleasePlan,
114
+ opts?: { cwd?: string },
115
+ ): Promise<{ commit: string | null; written: boolean }> {
116
+ if (typeof plan.digest !== "string" || plan.digest.length === 0) {
117
+ throw new InvalidReleasePlanError("release plan is missing its own \"digest\" field — a release plan is content-addressed by its own digest");
118
+ }
119
+ const filename = planFilename(plan.digest);
120
+ const existing = await readBlobFromPath(PLANS_DIR, filename, opts);
121
+ if (existing !== null) return { commit: null, written: false };
122
+
123
+ const json = JSON.stringify(plan, sortedJsonReplacer);
124
+ try {
125
+ const commit = await writeBlobToPath(PLANS_DIR, filename, json, "Release plan", { ...opts, expectPriorPathSha: null });
126
+ return { commit, written: true };
127
+ } catch (err) {
128
+ if (err instanceof RefCASConflictError) return { commit: null, written: false };
129
+ throw err;
130
+ }
131
+ }
132
+
133
+ /**
134
+ * Read a persisted release plan back by its own digest — the same digest a
135
+ * `ReleaseRecord.digest` names. Returns `null` when no plan was ever
136
+ * persisted under that digest (never throws — most releases carry no plan
137
+ * at all, and reading one for status is a normal, expected miss), and when
138
+ * the stored blob fails to parse as JSON.
139
+ *
140
+ * `prefix` lets a multi-member reader (../workspace/status.ts) resolve a
141
+ * specific member's plan directory directly, the same way
142
+ * `readReleaseLedgerLines` is handed an already-member-prefixed path there
143
+ * — `cwd` alone can't do it, since one status read walks every member from
144
+ * one process without changing directory per member.
145
+ */
146
+ export async function readReleasePlan(
147
+ digest: string,
148
+ opts?: { cwd?: string; prefix?: string },
149
+ ): Promise<ReleasePlan | null> {
150
+ const dir = `${opts?.prefix ?? ""}${PLANS_DIR}`;
151
+ const content = await readBlobFromPath(dir, planFilename(digest), opts);
152
+ if (!content) return null;
153
+ try {
154
+ return JSON.parse(content) as ReleasePlan;
155
+ } catch {
156
+ return null;
157
+ }
158
+ }
@@ -0,0 +1,236 @@
1
+ /**
2
+ * #2732 — the work lease: the operator lease under `work/<id>`, with a
3
+ * `_leases/<id>.jsonl` history, coordinating workers in one clone and across
4
+ * clones through a bare remote.
5
+ */
6
+ import { afterAll, describe, expect, test } from "vitest";
7
+ import { execFileSync } from "node:child_process";
8
+ import { mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
9
+ import { tmpdir } from "node:os";
10
+ import { join } from "node:path";
11
+ import {
12
+ claimWorkLease,
13
+ listWorkLeases,
14
+ readLeaseHistory,
15
+ releaseWorkLease,
16
+ renewWorkLease,
17
+ workLeaseRef,
18
+ leaseHistoryPath,
19
+ } from "./work-lease";
20
+ import { readRefSha } from "./git";
21
+
22
+ const dirs: string[] = [];
23
+ afterAll(() => {
24
+ for (const d of dirs) rmSync(d, { recursive: true, force: true });
25
+ });
26
+
27
+ function tmp(prefix: string): string {
28
+ const d = realpathSync(mkdtempSync(join(tmpdir(), prefix)));
29
+ dirs.push(d);
30
+ return d;
31
+ }
32
+
33
+ function git(cwd: string, ...args: string[]): string {
34
+ return execFileSync("git", args, { cwd, encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"] }).trim();
35
+ }
36
+
37
+ function configure(dir: string): void {
38
+ git(dir, "config", "user.email", "test@chant.dev");
39
+ git(dir, "config", "user.name", "Test");
40
+ git(dir, "config", "commit.gpgsign", "false");
41
+ }
42
+
43
+ function initRepo(): string {
44
+ const dir = tmp("chant-work-lease-");
45
+ git(dir, "init", "-q", "-b", "main");
46
+ configure(dir);
47
+ writeFileSync(join(dir, "README.md"), "# t\n");
48
+ git(dir, "add", "README.md");
49
+ git(dir, "commit", "-q", "-m", "init");
50
+ return dir;
51
+ }
52
+
53
+ const at = (iso: string) => () => new Date(iso);
54
+
55
+ describe("a work lease in one clone", () => {
56
+ test("a claim takes a free item, and a second claim is refused with the holder named, the same holder's included", async () => {
57
+ const cwd = initRepo();
58
+ const first = await claimWorkLease("W-001", "alice", { cwd, ttlMs: 60_000 });
59
+ expect(first.ok).toBe(true);
60
+ if (!first.ok) return;
61
+ expect(first.lease).toMatchObject({ item: "W-001", holder: "alice" });
62
+ expect(await readRefSha(workLeaseRef("W-001"), { cwd })).not.toBeNull();
63
+
64
+ const second = await claimWorkLease("W-001", "bob", { cwd });
65
+ expect(second).toMatchObject({ ok: false, reason: "lease-held", heldBy: { holder: "alice", token: first.lease.token } });
66
+ if (!second.ok) expect(second.message).toContain("alice");
67
+
68
+ const again = await claimWorkLease("W-001", "alice", { cwd });
69
+ expect(again).toMatchObject({ ok: false, reason: "lease-held" });
70
+ });
71
+
72
+ test("a renew moves the expiry and keeps the token; an expired lease can be claimed, with a new token", async () => {
73
+ const cwd = initRepo();
74
+ const claim = await claimWorkLease("W-002", "alice", { cwd, ttlMs: 60_000, now: at("2026-09-25T10:00:00.000Z") });
75
+ if (!claim.ok) throw new Error(claim.message);
76
+ expect(claim.lease.expiresAt).toBe("2026-09-25T10:01:00.000Z");
77
+
78
+ const renew = await renewWorkLease("W-002", "alice", { cwd, ttlMs: 60_000, token: claim.lease.token, now: at("2026-09-25T10:00:30.000Z") });
79
+ if (!renew.ok) throw new Error(renew.message);
80
+ expect(renew.lease.token).toBe(claim.lease.token);
81
+ expect(renew.lease.acquiredAt).toBe(claim.lease.acquiredAt);
82
+ expect(renew.lease.expiresAt).toBe("2026-09-25T10:01:30.000Z");
83
+
84
+ // Another holder can't renew it, and a stale token is refused.
85
+ expect(await renewWorkLease("W-002", "bob", { cwd, now: at("2026-09-25T10:00:40.000Z") })).toMatchObject({ ok: false, reason: "lease-held" });
86
+ expect(await renewWorkLease("W-002", "alice", { cwd, token: "stale", now: at("2026-09-25T10:00:40.000Z") })).toMatchObject({ ok: false, reason: "lease-token-mismatch" });
87
+
88
+ // Past its expiry: renew is refused, and a claim by anyone mints a new token.
89
+ const late = at("2026-09-25T10:02:00.000Z");
90
+ expect(await renewWorkLease("W-002", "alice", { cwd, now: late })).toMatchObject({ ok: false, reason: "lease-not-held" });
91
+ const reclaim = await claimWorkLease("W-002", "bob", { cwd, ttlMs: 60_000, now: late });
92
+ if (!reclaim.ok) throw new Error(reclaim.message);
93
+ expect(reclaim.lease.holder).toBe("bob");
94
+ expect(reclaim.lease.token).not.toBe(claim.lease.token);
95
+ });
96
+
97
+ test("release: the holder gives a live lease back; someone else can't, but anyone closes out an expired one", async () => {
98
+ const cwd = initRepo();
99
+ const t0 = "2026-09-25T10:00:00.000Z";
100
+ const claim = await claimWorkLease("W-003", "alice", { cwd, ttlMs: 60_000, now: at(t0) });
101
+ if (!claim.ok) throw new Error(claim.message);
102
+ expect(await releaseWorkLease("W-003", "bob", { cwd, now: at(t0) })).toMatchObject({ ok: false, reason: "lease-held", heldBy: { holder: "alice" } });
103
+ const released = await releaseWorkLease("W-003", "alice", { cwd, outcome: "done", now: at(t0) });
104
+ expect(released.ok).toBe(true);
105
+ expect(await readRefSha(workLeaseRef("W-003"), { cwd })).toBeNull();
106
+ expect(await releaseWorkLease("W-003", "alice", { cwd })).toMatchObject({ ok: false, reason: "lease-not-held" });
107
+
108
+ const again = await claimWorkLease("W-003", "carol", { cwd, ttlMs: 1_000, now: at(t0) });
109
+ if (!again.ok) throw new Error(again.message);
110
+ const closed = await releaseWorkLease("W-003", "dispatcher", { cwd, outcome: "expired", now: at("2026-09-25T11:00:00.000Z") });
111
+ expect(closed).toMatchObject({ ok: true, lease: { holder: "carol" } });
112
+ });
113
+
114
+ test("the history has one line per claim, renew and release, on chant/lifecycle", async () => {
115
+ const cwd = initRepo();
116
+ const claim = await claimWorkLease("W-004", "alice", { cwd, note: "starting" });
117
+ if (!claim.ok) throw new Error(claim.message);
118
+ expect(claim.history.path).toBe(leaseHistoryPath("W-004"));
119
+ expect(claim.history.pushed).toBe(false);
120
+ await renewWorkLease("W-004", "alice", { cwd });
121
+ await renewWorkLease("W-004", "alice", { cwd });
122
+ await releaseWorkLease("W-004", "alice", { cwd, outcome: "done" });
123
+
124
+ const { records, malformed } = await readLeaseHistory("W-004", { cwd });
125
+ expect(malformed).toBe(0);
126
+ expect(records.map((r) => r.event)).toEqual(["claim", "renew", "renew", "release"]);
127
+ expect(new Set(records.map((r) => r.token)).size).toBe(1);
128
+ expect(records[0]).toMatchObject({ version: 1, item: "W-004", holder: "alice", by: "alice", note: "starting" });
129
+ expect(records[3]).toMatchObject({ outcome: "done" });
130
+ expect(git(cwd, "show", `chant/lifecycle:_leases/W-004.jsonl`).split("\n")).toHaveLength(4);
131
+ });
132
+
133
+ test("listWorkLeases reports active and expired leases and leaves released ones out", async () => {
134
+ const cwd = initRepo();
135
+ const t0 = "2026-09-25T10:00:00.000Z";
136
+ await claimWorkLease("W-010", "alice", { cwd, ttlMs: 60_000, now: at(t0) });
137
+ await claimWorkLease("W-011", "bob", { cwd, ttlMs: 1_000, now: at(t0) });
138
+ await claimWorkLease("W-012", "carol", { cwd, ttlMs: 60_000, now: at(t0) });
139
+ await releaseWorkLease("W-012", "carol", { cwd, now: at(t0) });
140
+ const leases = await listWorkLeases({ cwd, memberPrefix: "", now: new Date("2026-09-25T10:00:30.000Z") });
141
+ expect(leases.map((l) => [l.item, l.holder, l.state])).toEqual([
142
+ ["W-010", "alice", "active"],
143
+ ["W-011", "bob", "expired"],
144
+ ]);
145
+ expect(leases[0].ref).toBe("refs/chant/lease/work/W-010");
146
+ });
147
+
148
+ test("an id that can't be one ref segment is refused", async () => {
149
+ const cwd = initRepo();
150
+ await expect(claimWorkLease("../x", "alice", { cwd })).rejects.toThrow(/can't key a work lease/);
151
+ await expect(claimWorkLease("a/b", "alice", { cwd })).rejects.toThrow(/can't key a work lease/);
152
+ });
153
+
154
+ test("a workspace member's leases and history sit under _members/<member>/ (D7)", async () => {
155
+ const cwd = initRepo();
156
+ writeFileSync(join(cwd, "chant.workspace.json"), JSON.stringify({ name: "acme", schema: 1, members: [{ name: "api", dir: "api", kind: "other", because: "t" }] }));
157
+ execFileSync("mkdir", ["-p", join(cwd, "api")]);
158
+ const member = join(cwd, "api");
159
+ const claim = await claimWorkLease("W-020", "alice", { cwd: member });
160
+ if (!claim.ok) throw new Error(claim.message);
161
+ expect(await readRefSha("refs/chant/lease/_members/api/work/W-020", { cwd })).not.toBeNull();
162
+ expect(await readRefSha("refs/chant/lease/work/W-020", { cwd })).toBeNull();
163
+ expect(claim.history.path).toBe("_members/api/_leases/W-020.jsonl");
164
+ expect(git(cwd, "show", "chant/lifecycle:_members/api/_leases/W-020.jsonl")).toContain('"event":"claim"');
165
+ expect((await listWorkLeases({ cwd, memberPrefix: "_members/api/" })).map((l) => l.item)).toEqual(["W-020"]);
166
+ expect(await listWorkLeases({ cwd, memberPrefix: "" })).toEqual([]);
167
+ });
168
+ });
169
+
170
+ describe("a work lease across clones, through a bare remote", () => {
171
+ function setup(): { remote: string; a: string; b: string } {
172
+ const root = tmp("chant-work-lease-remote-");
173
+ const remote = join(root, "remote.git");
174
+ git(root, "init", "-q", "--bare", "-b", "main", remote);
175
+ const a = join(root, "a");
176
+ git(root, "clone", "-q", remote, a);
177
+ configure(a);
178
+ writeFileSync(join(a, "README.md"), "# t\n");
179
+ git(a, "add", "README.md");
180
+ git(a, "commit", "-q", "-m", "init");
181
+ git(a, "push", "-q", "origin", "main");
182
+ const b = join(root, "b");
183
+ git(root, "clone", "-q", remote, b);
184
+ configure(b);
185
+ return { remote, a, b };
186
+ }
187
+
188
+ test("A claims; B is refused with A named; A renews and releases on the remote; then B claims and A is refused", async () => {
189
+ const { remote, a, b } = setup();
190
+ const claim = await claimWorkLease("W-001", "worker-a", { cwd: a, ttlMs: 60_000 });
191
+ if (!claim.ok) throw new Error(claim.message);
192
+ expect(git(remote, "rev-parse", workLeaseRef("W-001"))).toBe(await readRefSha(workLeaseRef("W-001"), { cwd: a }));
193
+
194
+ const refused = await claimWorkLease("W-001", "worker-b", { cwd: b });
195
+ expect(refused).toMatchObject({ ok: false, reason: "lease-held", heldBy: { holder: "worker-a", token: claim.lease.token } });
196
+
197
+ // A renew reaches the remote: the push expects the value A last pushed, not "absent".
198
+ const renew = await renewWorkLease("W-001", "worker-a", { cwd: a, ttlMs: 120_000 });
199
+ if (!renew.ok) throw new Error(renew.message);
200
+ expect(git(remote, "rev-parse", workLeaseRef("W-001"))).toBe(await readRefSha(workLeaseRef("W-001"), { cwd: a }));
201
+ const seen = await claimWorkLease("W-001", "worker-b", { cwd: b });
202
+ expect(seen).toMatchObject({ ok: false, heldBy: { expiresAt: renew.lease.expiresAt } });
203
+ // B's read-only listing now shows the remote's lease as last fetched.
204
+ expect((await listWorkLeases({ cwd: b, memberPrefix: "" })).map((l) => l.holder)).toEqual(["worker-a"]);
205
+
206
+ const released = await releaseWorkLease("W-001", "worker-a", { cwd: a, outcome: "done" });
207
+ expect(released.ok).toBe(true);
208
+ expect(() => git(remote, "rev-parse", "--verify", workLeaseRef("W-001"))).toThrow();
209
+
210
+ const taken = await claimWorkLease("W-001", "worker-b", { cwd: b, ttlMs: 60_000 });
211
+ if (!taken.ok) throw new Error(taken.message);
212
+ expect(taken.lease.token).not.toBe(claim.lease.token);
213
+ expect(await claimWorkLease("W-001", "worker-a", { cwd: a })).toMatchObject({ ok: false, reason: "lease-held", heldBy: { holder: "worker-b" } });
214
+
215
+ // Both clones' histories reached the remote's chant/lifecycle.
216
+ expect(claim.history.pushed).toBe(true);
217
+ const lines = git(remote, "show", "chant/lifecycle:_leases/W-001.jsonl").split("\n").map((l) => JSON.parse(l).event);
218
+ expect(lines).toEqual(["claim", "renew", "release", "claim"]);
219
+ });
220
+
221
+ test("a claim the remote refuses is undone locally: two clones can't both hold one item", async () => {
222
+ const { remote, a, b } = setup();
223
+ // B fetches from an empty remote, so it can't see A's claim, but pushes to the real one.
224
+ const blind = join(tmp("chant-work-lease-blind-"), "blind.git");
225
+ git(a, "init", "-q", "--bare", "-b", "main", blind);
226
+ git(b, "remote", "set-url", "origin", blind);
227
+ git(b, "remote", "set-url", "--push", "origin", remote);
228
+
229
+ const claim = await claimWorkLease("W-005", "worker-a", { cwd: a });
230
+ if (!claim.ok) throw new Error(claim.message);
231
+ const lost = await claimWorkLease("W-005", "worker-b", { cwd: b });
232
+ expect(lost).toMatchObject({ ok: false, reason: "lease-push-rejected" });
233
+ expect(await readRefSha(workLeaseRef("W-005"), { cwd: b })).toBeNull();
234
+ expect(git(remote, "rev-parse", workLeaseRef("W-005"))).toBe(await readRefSha(workLeaseRef("W-005"), { cwd: a }));
235
+ });
236
+ });