@warpgogol/forge 9.4.0 → 9.5.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 (167) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.md +4 -2
  3. package/README.uk.md +10 -8
  4. package/bin/cli.ts +152 -11
  5. package/dist/bin/cli.js +125 -5
  6. package/dist/bin/cli.js.map +1 -1
  7. package/dist/os/flow/dirty-classify.d.ts +11 -1
  8. package/dist/os/flow/dirty-classify.d.ts.map +1 -1
  9. package/dist/os/flow/dirty-classify.js +13 -0
  10. package/dist/os/flow/dirty-classify.js.map +1 -1
  11. package/dist/os/flow/flow.module.d.ts.map +1 -1
  12. package/dist/os/flow/flow.module.js +29 -3
  13. package/dist/os/flow/flow.module.js.map +1 -1
  14. package/dist/os/flow/handlers/flow-check.d.ts.map +1 -1
  15. package/dist/os/flow/handlers/flow-check.js +9 -9
  16. package/dist/os/flow/handlers/flow-check.js.map +1 -1
  17. package/dist/os/flow/handlers/flow-cut.d.ts.map +1 -1
  18. package/dist/os/flow/handlers/flow-cut.js +22 -8
  19. package/dist/os/flow/handlers/flow-cut.js.map +1 -1
  20. package/dist/os/flow/handlers/flow-integrate.d.ts +6 -0
  21. package/dist/os/flow/handlers/flow-integrate.d.ts.map +1 -1
  22. package/dist/os/flow/handlers/flow-integrate.js +155 -44
  23. package/dist/os/flow/handlers/flow-integrate.js.map +1 -1
  24. package/dist/os/flow/handlers/flow-open.d.ts.map +1 -1
  25. package/dist/os/flow/handlers/flow-open.js +14 -19
  26. package/dist/os/flow/handlers/flow-open.js.map +1 -1
  27. package/dist/os/flow/handlers/flow-peers.d.ts +24 -0
  28. package/dist/os/flow/handlers/flow-peers.d.ts.map +1 -0
  29. package/dist/os/flow/handlers/flow-peers.js +99 -0
  30. package/dist/os/flow/handlers/flow-peers.js.map +1 -0
  31. package/dist/os/flow/index.d.ts +3 -0
  32. package/dist/os/flow/index.d.ts.map +1 -1
  33. package/dist/os/flow/index.js +9 -4
  34. package/dist/os/flow/index.js.map +1 -1
  35. package/dist/os/flow/ops-registry.d.ts +33 -0
  36. package/dist/os/flow/ops-registry.d.ts.map +1 -0
  37. package/dist/os/flow/ops-registry.js +177 -0
  38. package/dist/os/flow/ops-registry.js.map +1 -0
  39. package/dist/os/flow/preflight.d.ts +70 -3
  40. package/dist/os/flow/preflight.d.ts.map +1 -1
  41. package/dist/os/flow/preflight.js +545 -49
  42. package/dist/os/flow/preflight.js.map +1 -1
  43. package/dist/os/flow/registry.d.ts +2 -2
  44. package/dist/os/flow/standalone-invoke.d.ts +11 -0
  45. package/dist/os/flow/standalone-invoke.d.ts.map +1 -0
  46. package/dist/os/flow/standalone-invoke.js +75 -0
  47. package/dist/os/flow/standalone-invoke.js.map +1 -0
  48. package/dist/os/gate-run/detach.d.ts +27 -0
  49. package/dist/os/gate-run/detach.d.ts.map +1 -0
  50. package/dist/os/gate-run/detach.js +85 -0
  51. package/dist/os/gate-run/detach.js.map +1 -0
  52. package/dist/os/gate-run/gate-run.module.d.ts +3 -0
  53. package/dist/os/gate-run/gate-run.module.d.ts.map +1 -0
  54. package/dist/os/gate-run/gate-run.module.js +23 -0
  55. package/dist/os/gate-run/gate-run.module.js.map +1 -0
  56. package/dist/os/gate-run/index.d.ts +7 -0
  57. package/dist/os/gate-run/index.d.ts.map +1 -0
  58. package/dist/os/gate-run/index.js +5 -0
  59. package/dist/os/gate-run/index.js.map +1 -0
  60. package/dist/os/gate-run/record.d.ts +47 -0
  61. package/dist/os/gate-run/record.d.ts.map +1 -0
  62. package/dist/os/gate-run/record.js +157 -0
  63. package/dist/os/gate-run/record.js.map +1 -0
  64. package/dist/os/gate-run/status.d.ts +41 -0
  65. package/dist/os/gate-run/status.d.ts.map +1 -0
  66. package/dist/os/gate-run/status.js +142 -0
  67. package/dist/os/gate-run/status.js.map +1 -0
  68. package/dist/os/gate-run/types.d.ts +47 -0
  69. package/dist/os/gate-run/types.d.ts.map +1 -0
  70. package/dist/os/gate-run/types.js +24 -0
  71. package/dist/os/gate-run/types.js.map +1 -0
  72. package/dist/os/mission/handlers/archive.d.ts.map +1 -1
  73. package/dist/os/mission/handlers/archive.js +12 -8
  74. package/dist/os/mission/handlers/archive.js.map +1 -1
  75. package/dist/os/mission/importer-block.d.ts +19 -0
  76. package/dist/os/mission/importer-block.d.ts.map +1 -0
  77. package/dist/os/mission/importer-block.js +124 -0
  78. package/dist/os/mission/importer-block.js.map +1 -0
  79. package/dist/os/mission/lockfile.d.ts +17 -0
  80. package/dist/os/mission/lockfile.d.ts.map +1 -1
  81. package/dist/os/mission/lockfile.js +38 -0
  82. package/dist/os/mission/lockfile.js.map +1 -1
  83. package/dist/os/rfc/evidence-annotation.d.ts +26 -0
  84. package/dist/os/rfc/evidence-annotation.d.ts.map +1 -0
  85. package/dist/os/rfc/evidence-annotation.js +52 -0
  86. package/dist/os/rfc/evidence-annotation.js.map +1 -0
  87. package/dist/os/rfc/handlers/fixed-inputs.d.ts.map +1 -1
  88. package/dist/os/rfc/handlers/fixed-inputs.js +7 -1
  89. package/dist/os/rfc/handlers/fixed-inputs.js.map +1 -1
  90. package/dist/os/rfc/handlers/implement-stamp.d.ts.map +1 -1
  91. package/dist/os/rfc/handlers/implement-stamp.js +21 -28
  92. package/dist/os/rfc/handlers/implement-stamp.js.map +1 -1
  93. package/dist/os/rfc/handlers/list-create.d.ts.map +1 -1
  94. package/dist/os/rfc/handlers/list-create.js +25 -3
  95. package/dist/os/rfc/handlers/list-create.js.map +1 -1
  96. package/dist/os/rfc/handlers/validate-rules.d.ts.map +1 -1
  97. package/dist/os/rfc/handlers/validate-rules.js +127 -7
  98. package/dist/os/rfc/handlers/validate-rules.js.map +1 -1
  99. package/dist/os/rfc/rfc.module.d.ts.map +1 -1
  100. package/dist/os/rfc/rfc.module.js +3 -2
  101. package/dist/os/rfc/rfc.module.js.map +1 -1
  102. package/dist/os/rfc/types.d.ts +9 -2
  103. package/dist/os/rfc/types.d.ts.map +1 -1
  104. package/dist/os/rfc/types.js +2 -2
  105. package/dist/os/rfc/types.js.map +1 -1
  106. package/dist/os/system/handlers/system-task-collect.d.ts.map +1 -1
  107. package/dist/os/system/handlers/system-task-collect.js +11 -5
  108. package/dist/os/system/handlers/system-task-collect.js.map +1 -1
  109. package/dist/src/cli-flags.d.ts.map +1 -1
  110. package/dist/src/cli-flags.js +6 -0
  111. package/dist/src/cli-flags.js.map +1 -1
  112. package/dist/src/onboarding/prettierignore.d.ts.map +1 -1
  113. package/dist/src/onboarding/prettierignore.js +2 -0
  114. package/dist/src/onboarding/prettierignore.js.map +1 -1
  115. package/dist/src/types.d.ts +7 -0
  116. package/dist/src/types.d.ts.map +1 -1
  117. package/dist/src/types.js +2 -8
  118. package/dist/src/types.js.map +1 -1
  119. package/os/flow/dirty-classify.ts +21 -0
  120. package/os/flow/flow.module.ts +31 -3
  121. package/os/flow/handlers/flow-check.ts +17 -18
  122. package/os/flow/handlers/flow-cut.ts +28 -11
  123. package/os/flow/handlers/flow-integrate.ts +229 -62
  124. package/os/flow/handlers/flow-open.ts +24 -31
  125. package/os/flow/handlers/flow-peers.ts +142 -0
  126. package/os/flow/index.ts +10 -8
  127. package/os/flow/ops-registry.ts +194 -0
  128. package/os/flow/preflight.ts +608 -55
  129. package/os/flow/standalone-invoke.ts +85 -0
  130. package/os/flow/tests/dirty-classify.test.ts +139 -4
  131. package/os/flow/tests/flow-cut.test.ts +21 -0
  132. package/os/flow/tests/flow-integrate.preflight.test.ts +34 -9
  133. package/os/flow/tests/flow-integrate.test.ts +433 -17
  134. package/os/flow/tests/lockfile-induced.test.ts +328 -0
  135. package/os/flow/tests/ops-registry.test.ts +136 -0
  136. package/os/gate-run/detach.ts +106 -0
  137. package/os/gate-run/gate-run.module.ts +25 -0
  138. package/os/gate-run/index.ts +16 -0
  139. package/os/gate-run/record.ts +194 -0
  140. package/os/gate-run/status.ts +168 -0
  141. package/os/gate-run/tests/gate-run-detach.test.ts +144 -0
  142. package/os/gate-run/tests/gate-run-record.test.ts +200 -0
  143. package/os/gate-run/types.ts +73 -0
  144. package/os/mission/handlers/archive.ts +22 -14
  145. package/os/mission/importer-block.ts +119 -0
  146. package/os/mission/lockfile.ts +41 -0
  147. package/os/rfc/evidence-annotation.ts +61 -0
  148. package/os/rfc/handlers/fixed-inputs.test.ts +70 -0
  149. package/os/rfc/handlers/fixed-inputs.ts +11 -1
  150. package/os/rfc/handlers/implement-stamp.ts +25 -28
  151. package/os/rfc/handlers/list-create.test.ts +58 -5
  152. package/os/rfc/handlers/list-create.ts +30 -3
  153. package/os/rfc/handlers/validate-evidence-shape.test.ts +218 -0
  154. package/os/rfc/handlers/validate-probe-meta.test.ts +71 -0
  155. package/os/rfc/handlers/validate-rules.ts +169 -17
  156. package/os/rfc/handlers/validate-transient-probes.test.ts +222 -0
  157. package/os/rfc/rfc-0000-template.md +10 -10
  158. package/os/rfc/rfc.module.ts +3 -2
  159. package/os/rfc/types.ts +5 -2
  160. package/os/system/handlers/system-task-collect.ts +11 -5
  161. package/os/system/tests/system-task-collect.test.ts +16 -0
  162. package/package.json +17 -1
  163. package/skills/fo/fo-session-retro/SKILL.md +12 -4
  164. package/src/cli-flags.ts +7 -0
  165. package/src/onboarding/prettierignore.ts +2 -0
  166. package/src/tests/prettierignore-manage.test.ts +11 -0
  167. package/src/types.ts +9 -8
@@ -0,0 +1,142 @@
1
+ /*
2
+ <MODULE_CONTRACT>
3
+ <purpose>flow.peers — the read-only live resource map (RFC-1543). Reports the
4
+ integrate.lock holder, live op-claims grouped by checkout, open missions per
5
+ worktree, and registered in-flight branches so an operator (or a second
6
+ agent session) can see who owns a shared checkout before flow.integrate
7
+ waits or refuses on it.</purpose>
8
+ <non-goals>
9
+ <item>No mutation authority — peers observes; it never breaks locks, releases claims, or closes missions.</item>
10
+ </non-goals>
11
+ </MODULE_CONTRACT>
12
+ <CHANGE_SUMMARY>
13
+ <item>RFC-1543: flow.peers — forge/peers@1 report over lock holder, live claims, open missions, in-flight branches</item>
14
+ <item>RFC-1543: attribute shared-checkout dirt to live ops and expose peers (RFC-1543)</item>
15
+ </CHANGE_SUMMARY>
16
+ */
17
+
18
+ import { join } from "node:path";
19
+ import type {
20
+ ForgeCommandInput,
21
+ ForgeCommandResult,
22
+ ForgeRuntimeContext,
23
+ } from "../../../src/types.ts";
24
+ import { resolveIo } from "../../../src/utils/io.ts";
25
+ import { openMissionsIn } from "../../mission/open-missions.ts";
26
+ import { commonGitDir, INTEGRATE_LOCK_RELATIVE_PATH, readRegistry } from "../registry.ts";
27
+ import { requireGit, topLevel } from "../git.ts";
28
+ import { describeHeldLock } from "../locks.ts";
29
+ import { isClaimLive, liveClaimsReadOnly, type OpClaim } from "../ops-registry.ts";
30
+
31
+ export const PEERS_SCHEMA = "forge/peers@1";
32
+
33
+ interface LockHolder {
34
+ pid: number;
35
+ host?: string;
36
+ at?: string;
37
+ bootId?: string;
38
+ }
39
+
40
+ export interface PeersReport {
41
+ schema: typeof PEERS_SCHEMA;
42
+ integrateLock: (LockHolder & { disposition: "live" | "dead-holder" | "stale" }) | null;
43
+ claimsByCheckout: { workspaceRoot: string; claims: OpClaim[] }[];
44
+ openMissions: string[];
45
+ branchesInFlight: string[];
46
+ }
47
+
48
+ /** Read + liveness-check the integrate.lock holder — shared with ops sweeps. */
49
+ async function integrateLockHolder(
50
+ io: ReturnType<typeof resolveIo>,
51
+ common: string,
52
+ ): Promise<PeersReport["integrateLock"]> {
53
+ let parsed: LockHolder | null = null;
54
+ try {
55
+ const raw = JSON.parse(await io.readFile(join(common, INTEGRATE_LOCK_RELATIVE_PATH))) as Record<
56
+ string,
57
+ unknown
58
+ >;
59
+ if (typeof raw["pid"] === "number") {
60
+ parsed = {
61
+ pid: raw["pid"],
62
+ host: typeof raw["host"] === "string" ? raw["host"] : undefined,
63
+ at: typeof raw["at"] === "string" ? raw["at"] : undefined,
64
+ bootId: typeof raw["bootId"] === "string" ? raw["bootId"] : undefined,
65
+ };
66
+ }
67
+ } catch {
68
+ return null;
69
+ }
70
+ if (parsed === null) return null;
71
+ const d = describeHeldLock(
72
+ { pid: parsed.pid, host: parsed.host, at: parsed.at ?? "", bootId: parsed.bootId },
73
+ 10 * 60_000,
74
+ );
75
+ return { ...parsed, disposition: d.disposition };
76
+ }
77
+
78
+ export async function runFlowPeers(
79
+ _input: ForgeCommandInput,
80
+ context: ForgeRuntimeContext,
81
+ ): Promise<ForgeCommandResult<PeersReport>> {
82
+ const { workspaceRoot, logger, outputFormat } = context;
83
+ const io = resolveIo(context.io);
84
+ await requireGit(io);
85
+
86
+ const repoRoot = await topLevel(workspaceRoot, io);
87
+ if (repoRoot === null) {
88
+ throw new Error("flow.peers must run inside a git repository");
89
+ }
90
+
91
+ const common = await commonGitDir(io, repoRoot);
92
+ const [lock, claims, openMissions, registry] = await Promise.all([
93
+ integrateLockHolder(io, common),
94
+ liveClaimsReadOnly(repoRoot, io),
95
+ openMissionsIn(repoRoot, io),
96
+ readRegistry(io, repoRoot).catch(() => null),
97
+ ]);
98
+
99
+ const byRoot = new Map<string, OpClaim[]>();
100
+ for (const c of claims.filter((c) => isClaimLive(c))) {
101
+ byRoot.set(c.workspaceRoot, [...(byRoot.get(c.workspaceRoot) ?? []), c]);
102
+ }
103
+
104
+ const report: PeersReport = {
105
+ schema: PEERS_SCHEMA,
106
+ integrateLock: lock,
107
+ claimsByCheckout: [...byRoot.entries()].map(([root, list]) => ({
108
+ workspaceRoot: root,
109
+ claims: list,
110
+ })),
111
+ openMissions,
112
+ branchesInFlight: (registry?.branches ?? []).map((b) => b.name),
113
+ };
114
+
115
+ if (outputFormat === "pretty") {
116
+ logger.section("flow.peers");
117
+ logger.info(
118
+ lock === null
119
+ ? " integrate.lock: free"
120
+ : ` integrate.lock: pid ${lock.pid} on ${lock.host ?? "?"} since ${lock.at ?? "?"} (${lock.disposition})`,
121
+ );
122
+ for (const g of report.claimsByCheckout) {
123
+ for (const c of g.claims) {
124
+ logger.info(
125
+ ` claim ${c.opId}: ${c.command} (pid ${c.pid}, started ${c.startedAt}) on ${g.workspaceRoot} — ${c.paths.length} path(s)`,
126
+ );
127
+ }
128
+ }
129
+ if (report.openMissions.length > 0) {
130
+ logger.info(` open missions: ${report.openMissions.join(", ")}`);
131
+ }
132
+ if (report.branchesInFlight.length > 0) {
133
+ logger.info(` branches in flight: ${report.branchesInFlight.join(", ")}`);
134
+ }
135
+ }
136
+
137
+ return {
138
+ data: report,
139
+ exitCode: 0,
140
+ summary: `[flow.peers] ${lock === null ? "lock free" : `lock ${lock.disposition}`}, ${claims.length} live claim(s), ${report.openMissions.length} open mission(s)`,
141
+ };
142
+ }
package/os/flow/index.ts CHANGED
@@ -15,12 +15,14 @@ reachable, else the version-file value.</purpose>
15
15
  <item>Untagged is not an error — it resolves to the version-file value; only a missing or unparsable version file throws.</item>
16
16
  </KEY_DECISIONS>
17
17
  <CHANGE_SUMMARY>
18
- <item>RFC-1493: step 1 — forge public release-line version reader</item>
19
- <item>RFC-1494: step 1 — isFlowAdopted public export</item>
20
18
  <item>RFC-1495: step 1 - forge state roots</item>
21
19
  <item>RFC-1495: steps 2-3 - workshop paths resolver and call-site migration</item>
22
20
  <item>RFC-1519: add advisory gate-verdict store for scoped pass reuse across reruns and the commit-integrate boundary</item>
23
- <history>RFC-1493</history>
21
+ <item>RFC-1549: route generated onboarding-status commits through session flow on fixed branches
22
+
23
+ commitWerkstattSideEffects skips git add+commit when classifyBranch() yields non-flow (protected/nonconforming), reports written outputPaths; status-hook and deploy/leitstand results propagate onboardingStatus metadata; leitstand.promote surfaces an optional session-worktree integration nextStep. Flow-branch commit behavior unchanged; mission-open fixture rebased to conforming auto/task-YYMMDD-NN branch. AC-1..AC-3 checked.</item>
24
+ <item>RFC-1568: durable gate-run records, --detach mechanics, and forge CLI wiring</item>
25
+ <history>RFC-1493, RFC-1494</history>
24
26
  </CHANGE_SUMMARY>
25
27
  */
26
28
 
@@ -30,11 +32,7 @@ import { hasManagedBlock, PRECOMMIT_FILE } from "./guard-files.ts";
30
32
  import { deriveLineVersion } from "./line-version.ts";
31
33
  import { detectRepoKind } from "./repo-kind.ts";
32
34
  import { discoverReleaseLines } from "./release-lines.ts";
33
- import {
34
- primaryWorktree,
35
- resolveStateRoots,
36
- type StateRoots,
37
- } from "./worktree-path.ts";
35
+ import { primaryWorktree, resolveStateRoots, type StateRoots } from "./worktree-path.ts";
38
36
 
39
37
  // RFC-1495: state-root resolution — Forge owns the roots (mission.archive,
40
38
  // werkstatt.lock.recover build state paths and Forge must not import
@@ -43,6 +41,10 @@ export { primaryWorktree, resolveStateRoots, worktreeList };
43
41
  export { FORGE_STATE_FILES } from "./git.ts";
44
42
  export type { StateRoots };
45
43
  export type { FlowWorktree } from "./git.ts";
44
+ export { classifyBranch } from "./branch-name.ts";
45
+ export type { BranchClass } from "./branch-name.ts";
46
+ // RFC-1568: gate-run hosts share the common-git-dir resolution.
47
+ export { commonGitDir } from "./registry.ts";
46
48
 
47
49
  export interface RepositoryLineVersion {
48
50
  /** "6.451.0+12.ab12cd34e" for a tagged line, "6.451.0" from the version file otherwise. */
@@ -0,0 +1,194 @@
1
+ /*
2
+ <MODULE_CONTRACT>
3
+ <purpose>Shared operation-claims registry (RFC-1543) — long-running ops that
4
+ write git-visible state in a checkout they do not own journal a
5
+ `forge/op-claim@1` record under the shared git dir before mutating, so
6
+ `classifyDirt` can attribute otherwise-foreign dirt to a live holder instead
7
+ of refusing blind. Liveness (pid alive on this host+bootId, heartbeat
8
+ ≤5×cadence), not deletion, is authoritative — a crashed op's record is
9
+ reclaimed by the next reader, never trusted.</purpose>
10
+ <non-goals>
11
+ <item>No cross-host coordination — claims are machine-local, same trust model as integrate.lock.</item>
12
+ <item>No mutation authority — readers may sweep dead records; they never edit claims or block on them directly.</item>
13
+ </non-goals>
14
+ </MODULE_CONTRACT>
15
+ <KEY_DECISIONS>
16
+ <item>Claims live at &lt;git-common-dir&gt;/forge/ops/&lt;opId&gt;.yaml — worktrees share one git dir, so a claim written from a session worktree is visible to the primary by construction.</item>
17
+ <item>Claim-write failure degrades to unclaimed behavior (fail-safe): the op proceeds and classification keeps the old refusal semantics — a registry outage must never become a write blocker.</item>
18
+ </KEY_DECISIONS>
19
+ <CHANGE_SUMMARY>
20
+ <item>RFC-1543: op-claim registry — claim/release/liveClaims, pid+bootId+heartbeat liveness, lazy dead-record sweep</item>
21
+ <item>RFC-1543: attribute shared-checkout dirt to live ops and expose peers (RFC-1543)</item>
22
+ </CHANGE_SUMMARY>
23
+ */
24
+
25
+ import { hostname } from "node:os";
26
+ import { join } from "node:path";
27
+ import { parse as yamlParse, stringify as yamlStringify } from "yaml";
28
+ import type { WorkspaceIO } from "../../src/types.ts";
29
+ import { currentBootId, holderIsDead } from "../core/lock-holder.ts";
30
+ import { git } from "./git.ts";
31
+
32
+ export const OP_CLAIM_SCHEMA = "forge/op-claim@1";
33
+ /** Expected heartbeat write cadence — a claim goes stale at 5× this age. */
34
+ export const HEARTBEAT_CADENCE_MS = 30_000;
35
+
36
+ export interface OpClaim {
37
+ schema: typeof OP_CLAIM_SCHEMA;
38
+ opId: string;
39
+ command: string;
40
+ pid: number;
41
+ host: string;
42
+ bootId?: string;
43
+ startedAt: string;
44
+ heartbeatAt: string;
45
+ workspaceRoot: string;
46
+ /** Exact paths or directory prefixes the op legitimately dirties. */
47
+ paths: string[];
48
+ }
49
+
50
+ /** `<git-common-dir>/forge/ops` — shared across linked worktrees. */
51
+ async function opsDir(repo: string, io: WorkspaceIO): Promise<string | null> {
52
+ let r;
53
+ try {
54
+ r = await git(repo, io, ["rev-parse", "--git-common-dir"]);
55
+ } catch {
56
+ return null;
57
+ }
58
+ if (r.exitCode !== 0) return null;
59
+ const dir = r.stdout.trim();
60
+ return join(dir.startsWith("/") ? dir : join(repo, dir), "forge", "ops");
61
+ }
62
+
63
+ /** Liveness (AC-2): pid alive on this host+bootId AND heartbeat ≤5×cadence. */
64
+ export function isClaimLive(claim: OpClaim, now: number = Date.now()): boolean {
65
+ if (holderIsDead(claim, currentBootId())) return false;
66
+ const beat = Date.parse(claim.heartbeatAt);
67
+ if (!Number.isFinite(beat) || now - beat > 5 * HEARTBEAT_CADENCE_MS) return false;
68
+ return true;
69
+ }
70
+
71
+ /** True when `path` equals or sits under a declared claim path/prefix. */
72
+ export function claimCoversPath(claim: OpClaim, path: string): boolean {
73
+ return claim.paths.some((p) => {
74
+ const prefix = p.endsWith("/") ? p : `${p}/`;
75
+ return path === p || path.startsWith(prefix);
76
+ });
77
+ }
78
+
79
+ /** Write a claim before the op's first shared-checkout mutation — best-effort. */
80
+ export async function claimOp(
81
+ repo: string,
82
+ io: WorkspaceIO,
83
+ claim: Omit<OpClaim, "schema" | "pid" | "host" | "bootId" | "startedAt" | "heartbeatAt"> & {
84
+ startedAt?: string;
85
+ },
86
+ ): Promise<boolean> {
87
+ const dir = await opsDir(repo, io);
88
+ if (dir === null) return false;
89
+ const now = new Date().toISOString();
90
+ const record: OpClaim = {
91
+ schema: OP_CLAIM_SCHEMA,
92
+ pid: process.pid,
93
+ host: hostname(),
94
+ bootId: currentBootId(),
95
+ heartbeatAt: now,
96
+ startedAt: claim.startedAt ?? now,
97
+ ...claim,
98
+ };
99
+ try {
100
+ await io.mkdir(dir);
101
+ await io.writeFile(join(dir, `${record.opId}.yaml`), yamlStringify(record));
102
+ return true;
103
+ } catch {
104
+ return false;
105
+ }
106
+ }
107
+
108
+ /** Refresh a live claim's heartbeat — best-effort, same path. */
109
+ export async function heartbeatOp(repo: string, io: WorkspaceIO, opId: string): Promise<void> {
110
+ const dir = await opsDir(repo, io);
111
+ if (dir === null) return;
112
+ const file = join(dir, `${opId}.yaml`);
113
+ try {
114
+ const parsed = yamlParse(await io.readFile(file)) as Partial<OpClaim> | null;
115
+ if (!parsed || parsed.schema !== OP_CLAIM_SCHEMA) return;
116
+ parsed.heartbeatAt = new Date().toISOString();
117
+ await io.writeFile(file, yamlStringify(parsed));
118
+ } catch {
119
+ /* best-effort */
120
+ }
121
+ }
122
+
123
+ /** Best-effort removal — liveness, not deletion, is authoritative. */
124
+ export async function releaseOp(repo: string, io: WorkspaceIO, opId: string): Promise<void> {
125
+ const dir = await opsDir(repo, io);
126
+ if (dir === null) return;
127
+ try {
128
+ await io.rm(join(dir, `${opId}.yaml`));
129
+ } catch {
130
+ /* already gone */
131
+ }
132
+ }
133
+
134
+ function parseClaim(raw: string): OpClaim | null {
135
+ let parsed: unknown;
136
+ try {
137
+ parsed = yamlParse(raw);
138
+ } catch {
139
+ return null;
140
+ }
141
+ if (typeof parsed !== "object" || parsed === null) return null;
142
+ const c = parsed as Partial<OpClaim>;
143
+ if (
144
+ c.schema !== OP_CLAIM_SCHEMA ||
145
+ typeof c.opId !== "string" ||
146
+ typeof c.command !== "string" ||
147
+ typeof c.pid !== "number" ||
148
+ typeof c.host !== "string" ||
149
+ typeof c.startedAt !== "string" ||
150
+ typeof c.heartbeatAt !== "string" ||
151
+ typeof c.workspaceRoot !== "string" ||
152
+ !Array.isArray(c.paths)
153
+ ) {
154
+ return null;
155
+ }
156
+ return c as OpClaim;
157
+ }
158
+
159
+ /**
160
+ * Live claims for `repo`, sweeping dead/stale records lazily as a side
161
+ * effect. Malformed files sweep too — a record we cannot read cannot be
162
+ * liveness-checked and must never grant tolerance.
163
+ */
164
+ async function readClaims(repo: string, io: WorkspaceIO): Promise<{ live: OpClaim[]; dead: string[] }> {
165
+ const dir = await opsDir(repo, io);
166
+ if (dir === null || !(await io.exists(dir))) return { live: [], dead: [] };
167
+ const files = (await io.glob("*.yaml", { cwd: dir })).filter((f) => !f.endsWith("/"));
168
+ const live: OpClaim[] = [];
169
+ const dead: string[] = [];
170
+ for (const f of files) {
171
+ const abs = join(dir, f);
172
+ const claim = parseClaim(await io.readFile(abs));
173
+ if (claim !== null && isClaimLive(claim)) live.push(claim);
174
+ else dead.push(abs);
175
+ }
176
+ return { live, dead };
177
+ }
178
+
179
+ /** Read-only variant for surfaces that must not mutate (flow.peers). */
180
+ export async function liveClaimsReadOnly(repo: string, io: WorkspaceIO): Promise<OpClaim[]> {
181
+ return (await readClaims(repo, io)).live;
182
+ }
183
+
184
+ export async function liveClaims(repo: string, io: WorkspaceIO): Promise<OpClaim[]> {
185
+ const { live, dead } = await readClaims(repo, io);
186
+ for (const abs of dead) {
187
+ try {
188
+ await io.rm(abs);
189
+ } catch {
190
+ /* sweep is best-effort */
191
+ }
192
+ }
193
+ return live;
194
+ }