@hunsu/core 0.1.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.
@@ -0,0 +1,951 @@
1
+ import { createHash } from "node:crypto";
2
+ import { gzipSync, gunzipSync } from "node:zlib";
3
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
4
+ import { dirname, join } from "node:path";
5
+ import { createDefaultHarness, decodeArtifactActionDefinitionArray, harnessEntityFromSnapshot, err, ok, rootHarnessSnapshot, tryProjectBoard, tryApplyCommand, validateHarnessEntity, validateDomainEvent } from "@hunsu/protocol";
6
+ import { GitError } from "./errors.js";
7
+ import { ensureGitRepository, git } from "./git.js";
8
+ import { parseCommitSha, parseRuntimeChecksum } from "./primitives.js";
9
+ export const HUNSU_COMPLETED_DESTINATIONS_PATH = ".hunsu/completed-destinations.hunsu";
10
+ export const HUNSU_DESTINATIONS_PATH = ".hunsu/destinations.hunsu";
11
+ export const HUNSU_HARNESS_PATH = ".hunsu/harness.hunsu";
12
+ export const HUNSU_EXECUTORS_PATH = ".hunsu/executors.hunsu";
13
+ export const HUNSU_RESOURCES_PATH = ".hunsu/resources.hunsu";
14
+ export const HUNSU_ARTIFACT_ACTIONS_PATH = ".hunsu/artifact-actions.hunsu";
15
+ export const HUNSU_CURRENT_EXECUTION_PATH = ".hunsu/current-execution.hunsu";
16
+ export const HUNSU_PREVIOUS_EXECUTION_PATH = ".hunsu/previous-execution.hunsu";
17
+ export const HUNSU_HUNSU_DRAFT_PATH = ".hunsu/hunsu-draft.hunsu";
18
+ export const HUNSU_RUNTIME_PATHS = [HUNSU_COMPLETED_DESTINATIONS_PATH, HUNSU_DESTINATIONS_PATH, HUNSU_HARNESS_PATH, HUNSU_EXECUTORS_PATH, HUNSU_RESOURCES_PATH, HUNSU_ARTIFACT_ACTIONS_PATH];
19
+ export const HUNSU_LEGACY_STATE_PATH = ".hunsu/state.hunsu";
20
+ export const HUNSU_RUNTIME_ENCODING = "gzip+base64url";
21
+ export const HUNSU_DRAFT_RUNTIME_FILE_NAMES = ["destinations.json", "harness.json", "executors.json", "resources.json", "artifact-actions.json"];
22
+ export const HUNSU_SELF_COMMIT_REF = { type: "self" };
23
+ export const HUNSU_SELF_COMMIT_SENTINEL = "__HUNSU_SELF_COMMIT__";
24
+ const HUNSU_RUNTIME_HEADER = "HUNSU_RUNTIME_FILE_V1";
25
+ const LEGACY_STATE_HEADER = "HUNSU_STATE_V1";
26
+ const DOMAIN_EVENT_REF_PREFIX = "refs/hunsu/events";
27
+ const DOMAIN_EVENT_REF_FORMAT = "%(refname)\t%(objectname)\t%(objecttype)";
28
+ const DOMAIN_EVENT_REF_SEPARATOR = "\t";
29
+ export function loadDomainStore(cwd = process.cwd()) {
30
+ const root = ensureGitRepository(cwd);
31
+ const worktreeRuntime = readHunsuRuntimeStateFromWorktree(root);
32
+ const reachableRuntime = readLatestReachableHunsuRuntimeState(root);
33
+ if (worktreeRuntime && (!reachableRuntime || runtimeEventCount(worktreeRuntime.runtime) >= runtimeEventCount(reachableRuntime.runtime))) {
34
+ return domainStoreFromRuntime(root, worktreeRuntime.runtime, "worktree-runtime", [], worktreeRuntime.checksum);
35
+ }
36
+ if (reachableRuntime) {
37
+ return domainStoreFromRuntime(root, reachableRuntime.runtime, "reachable-runtime", [], reachableRuntime.checksum, reachableRuntime.commit);
38
+ }
39
+ const legacyState = readLegacyHunsuRuntimeStateFromWorktree(root) ?? readLegacyHunsuRuntimeStateAtRef(root, "HEAD");
40
+ if (legacyState) {
41
+ const runtime = runtimeFromEvents(legacyState.state.events, undefined, legacyState.state.events);
42
+ return domainStoreFromRuntime(root, runtime, "legacy-state", [], checksumRuntimeState(runtime));
43
+ }
44
+ const eventRefs = readDomainEventRefs(root);
45
+ if (eventRefs.length > 0) {
46
+ const events = eventRefs.map(ref => unwrapDomainStoreResult(readDomainEventObject(root, ref)));
47
+ const runtime = runtimeFromEvents(events, undefined, events);
48
+ return domainStoreFromRuntime(root, runtime, "legacy-refs", eventRefs, checksumRuntimeState(runtime));
49
+ }
50
+ const runtime = runtimeFromEvents([]);
51
+ return domainStoreFromRuntime(root, runtime, "empty", [], checksumRuntimeState(runtime));
52
+ }
53
+ export function initializeDomainStore(cwd = process.cwd(), options = {}) {
54
+ const root = ensureGitRepository(cwd);
55
+ const store = loadDomainStore(root);
56
+ if (store.source === "worktree-runtime") {
57
+ return store;
58
+ }
59
+ writeHunsuRuntimeState(root, store.runtime);
60
+ commitRuntimeStateIfRequested(root, options.commitMessage);
61
+ return {
62
+ ...store,
63
+ source: "worktree-runtime"
64
+ };
65
+ }
66
+ export function dryRunCommand(command, cwd = process.cwd()) {
67
+ return dryRunCommands([command], cwd);
68
+ }
69
+ export function dryRunCommands(commands, cwd = process.cwd()) {
70
+ const store = loadDomainStore(cwd);
71
+ const nextEvents = commands.reduce((events, command) => {
72
+ const result = tryApplyCommand(events, command);
73
+ if (!result.ok) {
74
+ throw new Error(result.error.message);
75
+ }
76
+ return result.value;
77
+ }, store.events);
78
+ const acceptedEvents = nextEvents.slice(store.events.length);
79
+ return { store, acceptedEvents, board: projectDomainEvents(nextEvents, "dry-run commands") };
80
+ }
81
+ export function writeCommand(command, options = {}) {
82
+ return writeCommands([command], options);
83
+ }
84
+ export function writeCommands(commands, options = {}) {
85
+ const cwd = options.cwd ?? process.cwd();
86
+ const { store, acceptedEvents, board } = dryRunCommands(commands, cwd);
87
+ if (acceptedEvents.length > 0) {
88
+ const nextRuntime = runtimeFromEvents([...store.events, ...acceptedEvents], store.runtime, acceptedEvents, options.previousExecution);
89
+ writeHunsuRuntimeState(store.root, nextRuntime, { selfCommitMoveIds: options.selfCommitMoveIds });
90
+ commitRuntimeStateIfRequested(store.root, options.commitMessage);
91
+ }
92
+ return { acceptedEvents, board };
93
+ }
94
+ export function encodeHunsuRuntimeFile(value) {
95
+ const json = `${JSON.stringify(value)}\n`;
96
+ const checksum = parseRuntimeChecksum(sha256(json));
97
+ const payload = gzipSync(Buffer.from(json, "utf8")).toString("base64url");
98
+ return {
99
+ checksum,
100
+ text: `${HUNSU_RUNTIME_HEADER}\nencoding: ${HUNSU_RUNTIME_ENCODING}\nchecksum: sha256:${checksum}\n\n${payload}\n`
101
+ };
102
+ }
103
+ export function decodeHunsuRuntimeFileText(text, source) {
104
+ const decoded = decodeRuntimeEnvelope(text, source, HUNSU_RUNTIME_HEADER);
105
+ if (!decoded.ok) {
106
+ return decoded;
107
+ }
108
+ return ok(decoded.value.value);
109
+ }
110
+ export function decodeRuntimeBundleToDraftFiles(runtime) {
111
+ const bundle = hunsuDraftRuntimeBundleFromRuntime(runtime);
112
+ return {
113
+ "destinations.json": bundle.destinations,
114
+ "harness.json": bundle.harness,
115
+ "executors.json": bundle.executors,
116
+ "resources.json": bundle.resources,
117
+ "artifact-actions.json": bundle.artifactActions
118
+ };
119
+ }
120
+ export function hunsuDraftRuntimeBundleFromRuntime(runtime) {
121
+ return {
122
+ destinations: cloneJson(runtime.destinations),
123
+ harness: cloneJson(runtime.harness),
124
+ executors: cloneJson(runtime.executors),
125
+ resources: cloneJson(runtime.resources),
126
+ artifactActions: cloneJson(runtime.artifactActions)
127
+ };
128
+ }
129
+ export function readDraftRuntimeBundle(cwd, dir) {
130
+ const root = ensureGitRepository(cwd);
131
+ const destinations = readDraftRuntimeJson(root, dir, "destinations.json");
132
+ if (!destinations.ok)
133
+ return destinations;
134
+ const harness = readDraftRuntimeJson(root, dir, "harness.json");
135
+ if (!harness.ok)
136
+ return harness;
137
+ const executors = readDraftRuntimeJson(root, dir, "executors.json");
138
+ if (!executors.ok)
139
+ return executors;
140
+ const resources = readDraftRuntimeJson(root, dir, "resources.json");
141
+ if (!resources.ok)
142
+ return resources;
143
+ const artifactActions = readDraftRuntimeJson(root, dir, "artifact-actions.json");
144
+ if (!artifactActions.ok)
145
+ return artifactActions;
146
+ return ok({
147
+ destinations: destinations.value,
148
+ harness: harness.value,
149
+ executors: executors.value,
150
+ resources: resources.value,
151
+ artifactActions: artifactActions.value
152
+ });
153
+ }
154
+ export function validateDraftRuntimeBundle(previous, request, sourceRuntime) {
155
+ const sourceBundle = hunsuDraftRuntimeBundleFromRuntime(sourceRuntime);
156
+ if (stableJson(previous) !== stableJson(sourceBundle)) {
157
+ return domainStoreError(".hunsu-prev no longer matches the source runtime bundle");
158
+ }
159
+ if (stableJson(request.destinations.compatibility) !== stableJson(sourceRuntime.destinations.compatibility)) {
160
+ return domainStoreError(".hunsu-request/destinations.json compatibility is Local-owned and must not be edited");
161
+ }
162
+ try {
163
+ const requestRuntime = validateRuntimeState({
164
+ completed: sourceRuntime.completed,
165
+ destinations: request.destinations,
166
+ harness: request.harness,
167
+ executors: request.executors,
168
+ resources: request.resources,
169
+ artifactActions: request.artifactActions,
170
+ currentExecution: sourceRuntime.currentExecution,
171
+ previousExecution: sourceRuntime.previousExecution,
172
+ eventLog: sourceRuntime.eventLog
173
+ }, "draft request runtime");
174
+ return ok({
175
+ previous: hunsuDraftRuntimeBundleFromRuntime(sourceRuntime),
176
+ request: hunsuDraftRuntimeBundleFromRuntime(requestRuntime),
177
+ requestRuntime
178
+ });
179
+ }
180
+ catch (error) {
181
+ return domainStoreError(error instanceof Error ? error.message : String(error));
182
+ }
183
+ }
184
+ export function encodeDraftRuntimeBundleToHunsuFiles(request) {
185
+ return {
186
+ [HUNSU_DESTINATIONS_PATH]: encodeHunsuRuntimeFile(request.destinations),
187
+ [HUNSU_HARNESS_PATH]: encodeHunsuRuntimeFile(request.harness),
188
+ [HUNSU_EXECUTORS_PATH]: encodeHunsuRuntimeFile(request.executors),
189
+ [HUNSU_RESOURCES_PATH]: encodeHunsuRuntimeFile(request.resources),
190
+ [HUNSU_ARTIFACT_ACTIONS_PATH]: encodeHunsuRuntimeFile(request.artifactActions)
191
+ };
192
+ }
193
+ export function readHunsuRuntimeStateFromWorktree(cwd = process.cwd()) {
194
+ const root = ensureGitRepository(cwd);
195
+ if (!HUNSU_RUNTIME_PATHS.every(path => existsSync(join(root, path)))) {
196
+ return undefined;
197
+ }
198
+ return readHunsuRuntimeStateFromSource(path => readFileSync(join(root, path), "utf8"), "worktree", currentHeadCommit(root));
199
+ }
200
+ export function readHunsuRuntimeStateAtRef(cwd = process.cwd(), ref = "HEAD") {
201
+ const root = ensureGitRepository(cwd);
202
+ try {
203
+ const commit = parseCommitSha(git(["rev-parse", "--verify", `${ref}^{commit}`], { cwd: root }).trim());
204
+ return readHunsuRuntimeStateFromSource(path => git(["show", `${commit}:${path}`], { cwd: root }), commit, commit);
205
+ }
206
+ catch (error) {
207
+ if (error instanceof GitError) {
208
+ return undefined;
209
+ }
210
+ throw error;
211
+ }
212
+ }
213
+ export function readReachableHunsuRuntimeStates(cwd = process.cwd()) {
214
+ const root = ensureGitRepository(cwd);
215
+ let commits;
216
+ try {
217
+ commits = git(["rev-list", "--date-order", "--all", "--", HUNSU_DESTINATIONS_PATH], { cwd: root })
218
+ .trim()
219
+ .split(/\r?\n/)
220
+ .filter(Boolean);
221
+ }
222
+ catch (error) {
223
+ if (error instanceof GitError) {
224
+ return [];
225
+ }
226
+ throw error;
227
+ }
228
+ return commits.flatMap(commit => {
229
+ const commitSha = parseCommitSha(commit);
230
+ const state = readHunsuRuntimeStateAtRef(root, commitSha);
231
+ return state ? [{ commit: commitSha, ...state }] : [];
232
+ });
233
+ }
234
+ export function readPreviousExecutionChain(cwd = process.cwd(), ref) {
235
+ const root = ensureGitRepository(cwd);
236
+ const visited = new Set();
237
+ const chain = [];
238
+ let nextRef = ref ?? readLatestReachableHunsuRuntimeState(root)?.commit ?? "HEAD";
239
+ while (nextRef) {
240
+ let commit;
241
+ try {
242
+ commit = parseCommitSha(git(["rev-parse", "--verify", `${nextRef}^{commit}`], { cwd: root }).trim());
243
+ }
244
+ catch (error) {
245
+ if (error instanceof GitError) {
246
+ break;
247
+ }
248
+ throw error;
249
+ }
250
+ if (visited.has(commit)) {
251
+ break;
252
+ }
253
+ visited.add(commit);
254
+ const state = readHunsuRuntimeStateAtRef(root, commit);
255
+ if (!state || state.runtime.previousExecution.type !== "present") {
256
+ break;
257
+ }
258
+ chain.push({ commit, execution: state.runtime.previousExecution.value });
259
+ nextRef = state.runtime.previousExecution.value.sourceMoveCommit;
260
+ }
261
+ return chain;
262
+ }
263
+ export function hasHunsuRuntimeState(cwd = process.cwd()) {
264
+ const root = ensureGitRepository(cwd);
265
+ return readHunsuRuntimeStateFromWorktree(root) !== undefined || readLatestReachableHunsuRuntimeState(root) !== undefined;
266
+ }
267
+ export function readDomainEventRefs(cwd = process.cwd()) {
268
+ const root = ensureGitRepository(cwd);
269
+ const output = git(["for-each-ref", `--format=${DOMAIN_EVENT_REF_FORMAT}`, DOMAIN_EVENT_REF_PREFIX], { cwd: root }).trim();
270
+ if (!output) {
271
+ return [];
272
+ }
273
+ return output
274
+ .split(/\r?\n/)
275
+ .map(parseDomainEventRef)
276
+ .filter(ref => ref.objectType === "blob")
277
+ .sort((left, right) => left.ordinal - right.ordinal || left.ref.localeCompare(right.ref));
278
+ }
279
+ export function readDomainEventObject(cwd, ref) {
280
+ const root = ensureGitRepository(cwd);
281
+ const text = git(["cat-file", "-p", ref.object], { cwd: root });
282
+ return decodeDomainEventText(text, ref.ref);
283
+ }
284
+ export function decodeDomainEventText(text, ref) {
285
+ const trimmed = text.trim();
286
+ if (!trimmed) {
287
+ return domainStoreError(`Empty Hunsu domain event object: ${ref}`);
288
+ }
289
+ let parsed;
290
+ try {
291
+ parsed = JSON.parse(trimmed);
292
+ }
293
+ catch (error) {
294
+ return domainStoreError(`Invalid Hunsu domain event JSON in ${ref}: ${error instanceof Error ? error.message : String(error)}`);
295
+ }
296
+ const validation = validateDomainEvent(parsed);
297
+ if (!validation.ok) {
298
+ return domainStoreError(`Invalid Hunsu domain event object in ${ref}: ${validation.error.message}`);
299
+ }
300
+ return ok(validation.value);
301
+ }
302
+ function runtimeFromEvents(events, previous, acceptedEvents = [], previousExecutionOverride) {
303
+ const board = projectDomainEvents(events, "runtime events");
304
+ const eventLog = {
305
+ events,
306
+ updatedAt: acceptedEvents.length > 0 ? new Date().toISOString() : previous?.eventLog.updatedAt
307
+ };
308
+ return {
309
+ completed: completedDestinationsFromEvents(board, previous?.completed, previous ? acceptedEvents : events),
310
+ destinations: {
311
+ schema: "hunsu.destinations.v1",
312
+ order: "queue-head-is-current",
313
+ destinations: pendingQueueFromBoard(board),
314
+ compatibility: {
315
+ events: eventLog.events,
316
+ updatedAt: eventLog.updatedAt
317
+ }
318
+ },
319
+ ...harnessExecutorsResourcesFilesFromBoard(board, previous),
320
+ artifactActions: artifactActionsFileFromBoard(board),
321
+ currentExecution: currentExecutionFromEvents(previous?.currentExecution, acceptedEvents),
322
+ previousExecution: previousExecutionFromEvents(previous?.previousExecution, acceptedEvents, previousExecutionOverride),
323
+ eventLog
324
+ };
325
+ }
326
+ function currentExecutionFromEvents(previous, acceptedEvents) {
327
+ if (acceptedEvents.some(event => event.type === "HunsuRecorded" || event.type === "LineForkedByHunsu" || event.type === "MoveRecorded")) {
328
+ return { type: "none" };
329
+ }
330
+ return previous ?? { type: "none" };
331
+ }
332
+ function previousExecutionFromEvents(previous, acceptedEvents, override) {
333
+ if (override) {
334
+ return override;
335
+ }
336
+ if (acceptedEvents.some(event => event.type === "HunsuRecorded" || event.type === "LineForkedByHunsu")) {
337
+ return { type: "none" };
338
+ }
339
+ if (acceptedEvents.some(event => event.type === "MoveRecorded")) {
340
+ return { type: "none" };
341
+ }
342
+ return previous ?? { type: "none" };
343
+ }
344
+ function completedDestinationsFromEvents(board, previous, acceptedEvents) {
345
+ const entries = previous ? [...previous.entries] : [];
346
+ for (const event of acceptedEvents) {
347
+ if (event.type !== "MoveRecorded" || event.move.outcome !== "arrived") {
348
+ continue;
349
+ }
350
+ for (const destinationId of event.move.reachedDestinationIds) {
351
+ if (entries.some(entry => entry.moveId === event.move.id && entry.destinationId === destinationId)) {
352
+ continue;
353
+ }
354
+ entries.push(completedEntryForMove(board, event.move, destinationId));
355
+ }
356
+ }
357
+ return {
358
+ schema: "hunsu.completed-destinations.v1",
359
+ order: "oldest-first-tail-append",
360
+ entries
361
+ };
362
+ }
363
+ function completedEntryForMove(board, move, destinationId) {
364
+ const destination = move.snapshot?.destinations.find(candidate => candidate.id === destinationId)
365
+ ?? board.destinations.find(candidate => candidate.id === destinationId);
366
+ return {
367
+ destinationId,
368
+ title: destination?.title ?? destinationId,
369
+ completedAt: move.recordedAt,
370
+ resultCommit: runtimeCommitRef(move.commit),
371
+ moveId: move.id,
372
+ harnessId: "default",
373
+ digest: {
374
+ summary: move.summary,
375
+ evidence: [...move.evidence],
376
+ risks: move.risks ? [...move.risks] : undefined
377
+ }
378
+ };
379
+ }
380
+ function pendingQueueFromBoard(board) {
381
+ return board.destinations
382
+ .filter(destination => destination.status !== "reached" && destination.status !== "canceled" && destination.status !== "superseded")
383
+ .sort((left, right) => (right.priority ?? 0) - (left.priority ?? 0) || left.id.localeCompare(right.id));
384
+ }
385
+ function harnessExecutorsResourcesFilesFromBoard(board, previous) {
386
+ const activeLine = board.lines.findLast(line => line.status === "active") ?? board.lines.at(-1);
387
+ const activeNode = activeLine ? board.nodes.find(node => node.id === activeLine.currentNodeId) : undefined;
388
+ const harnessGraph = activeNode?.harnessGraph
389
+ ?? (previous ? runtimeHarnessGraph(previous) : harnessEntityFromSnapshot(createDefaultHarness()));
390
+ return {
391
+ harness: {
392
+ schema: "hunsu.harness.v1",
393
+ origins: board.origins.map(origin => ({ ...origin })),
394
+ harness: {
395
+ name: "Default Harness",
396
+ rootTeamId: harnessGraph.rootTeamId,
397
+ guardrails: harnessGraph.guardrails.map(guardrail => ({ ...guardrail })),
398
+ lock: activeNode?.harnessLock ? { ...activeNode.harnessLock } : previous?.harness.harness.lock
399
+ }
400
+ },
401
+ executors: {
402
+ schema: "hunsu.executors.v1",
403
+ executors: cloneJson(harnessGraph.executors)
404
+ },
405
+ resources: {
406
+ schema: "hunsu.resources.v1",
407
+ resources: cloneJson(harnessGraph.resources),
408
+ bindings: board.destinations.map(destination => {
409
+ const previousBinding = previous?.resources.bindings.find(binding => binding.destinationId === destination.id);
410
+ return {
411
+ destinationId: destination.id,
412
+ executorPackageBindings: activeNode?.executorPackageBindings?.map(binding => ({ executorId: binding.executorId, lock: { ...binding.lock } })) ?? previousBinding?.executorPackageBindings,
413
+ resourcePackageBindings: activeNode?.resourcePackageBindings?.map(binding => ({ name: binding.name, lock: { ...binding.lock } })) ?? previousBinding?.resourcePackageBindings
414
+ };
415
+ })
416
+ }
417
+ };
418
+ }
419
+ function artifactActionsFileFromBoard(board) {
420
+ return {
421
+ schema: "hunsu.artifact-actions.v1",
422
+ order: "display-order",
423
+ actions: board.artifactActions
424
+ .map(cloneArtifactAction)
425
+ .sort((left, right) => left.displayOrder - right.displayOrder || String(left.id).localeCompare(String(right.id)))
426
+ };
427
+ }
428
+ function cloneArtifactAction(action) {
429
+ return {
430
+ ...action,
431
+ env: action.env ? Object.fromEntries(Object.entries(action.env).map(([key, value]) => [key, { ...value }])) : undefined,
432
+ runner: { ...action.runner },
433
+ aliases: action.aliases ? Object.fromEntries(Object.entries(action.aliases).map(([key, value]) => [key, { ...value }])) : undefined,
434
+ evidence: action.evidence ? { ...action.evidence, paths: action.evidence.paths?.slice() } : undefined
435
+ };
436
+ }
437
+ function readHunsuRuntimeStateFromSource(read, label, selfCommit) {
438
+ const completed = decodeRequiredRuntimeFile(read, HUNSU_COMPLETED_DESTINATIONS_PATH, label);
439
+ const destinations = decodeRequiredRuntimeFile(read, HUNSU_DESTINATIONS_PATH, label);
440
+ const harness = decodeRequiredRuntimeFile(read, HUNSU_HARNESS_PATH, label);
441
+ const executors = decodeRequiredRuntimeFile(read, HUNSU_EXECUTORS_PATH, label);
442
+ const resources = decodeRequiredRuntimeFile(read, HUNSU_RESOURCES_PATH, label);
443
+ const artifactActions = decodeRequiredRuntimeFile(read, HUNSU_ARTIFACT_ACTIONS_PATH, label);
444
+ if (!completed || !destinations || !harness || !executors || !resources || !artifactActions) {
445
+ return undefined;
446
+ }
447
+ const currentExecution = decodeOptionalRuntimeFile(read, HUNSU_CURRENT_EXECUTION_PATH, label);
448
+ const previousExecution = decodeOptionalRuntimeFile(read, HUNSU_PREVIOUS_EXECUTION_PATH, label);
449
+ const runtime = validateRuntimeState({
450
+ completed: completed.value,
451
+ destinations: destinations.value,
452
+ harness: harness.value,
453
+ executors: executors.value,
454
+ resources: resources.value,
455
+ artifactActions: artifactActions.value,
456
+ currentExecution: currentExecution ? { type: "present", value: currentExecution.value } : { type: "none" },
457
+ previousExecution: previousExecution ? { type: "present", value: previousExecution.value } : { type: "none" }
458
+ }, label, selfCommit);
459
+ return {
460
+ runtime,
461
+ checksum: parseRuntimeChecksum(sha256([completed.checksum, destinations.checksum, harness.checksum, executors.checksum, resources.checksum, artifactActions.checksum, currentExecution?.checksum ?? "none", previousExecution?.checksum ?? "none"].join("\n")))
462
+ };
463
+ }
464
+ function decodeRequiredRuntimeFile(read, path, label) {
465
+ try {
466
+ const decoded = decodeRuntimeEnvelope(read(path), `${label}:${path}`, HUNSU_RUNTIME_HEADER);
467
+ return decoded.ok ? { value: decoded.value.value, checksum: decoded.value.checksum } : unwrapDomainStoreResult(decoded);
468
+ }
469
+ catch (error) {
470
+ if (error instanceof GitError) {
471
+ return undefined;
472
+ }
473
+ throw error;
474
+ }
475
+ }
476
+ function decodeOptionalRuntimeFile(read, path, label) {
477
+ try {
478
+ const decoded = decodeRuntimeEnvelope(read(path), `${label}:${path}`, HUNSU_RUNTIME_HEADER);
479
+ return decoded.ok ? { value: decoded.value.value, checksum: decoded.value.checksum } : unwrapDomainStoreResult(decoded);
480
+ }
481
+ catch (error) {
482
+ if (error instanceof GitError || isMissingFileError(error)) {
483
+ return undefined;
484
+ }
485
+ throw error;
486
+ }
487
+ }
488
+ function validateRuntimeState(runtime, source, selfCommit) {
489
+ if (runtime.completed.schema !== "hunsu.completed-destinations.v1" || runtime.completed.order !== "oldest-first-tail-append" || !Array.isArray(runtime.completed.entries)) {
490
+ throw new Error(`Invalid completed Destinations runtime file in ${source}`);
491
+ }
492
+ if (runtime.destinations.schema !== "hunsu.destinations.v1" || runtime.destinations.order !== "queue-head-is-current" || !Array.isArray(runtime.destinations.destinations)) {
493
+ throw new Error(`Invalid pending Destinations runtime file in ${source}`);
494
+ }
495
+ if (!runtime.destinations.compatibility || !Array.isArray(runtime.destinations.compatibility.events)) {
496
+ throw new Error(`Invalid pending Destinations compatibility data in ${source}`);
497
+ }
498
+ const events = [];
499
+ for (const [index, event] of runtime.destinations.compatibility.events.entries()) {
500
+ const validation = validateDomainEvent(resolveRuntimeEventSelfCommit(event, selfCommit));
501
+ if (!validation.ok) {
502
+ throw new Error(`Invalid Hunsu runtime event ${index} in ${source}: ${validation.error.message}`);
503
+ }
504
+ events.push(validation.value);
505
+ }
506
+ const eventLog = {
507
+ events,
508
+ updatedAt: typeof runtime.destinations.compatibility.updatedAt === "string"
509
+ ? runtime.destinations.compatibility.updatedAt
510
+ : runtime.eventLog?.updatedAt
511
+ };
512
+ if (runtime.harness.schema !== "hunsu.harness.v1" || !runtime.harness.harness || typeof runtime.harness.harness.name !== "string") {
513
+ throw new Error(`Invalid Harness runtime file in ${source}`);
514
+ }
515
+ if (Object.prototype.hasOwnProperty.call(runtime.harness.harness, "executors")) {
516
+ throw new Error(`Invalid Harness runtime file in ${source}: Executor definitions are stored in executors.json`);
517
+ }
518
+ if (Object.prototype.hasOwnProperty.call(runtime.harness.harness, "members")) {
519
+ throw new Error(`Invalid Harness runtime file in ${source}: members is stored in executors.json, not harness.json`);
520
+ }
521
+ if (Object.prototype.hasOwnProperty.call(runtime.harness.harness, "plan")) {
522
+ throw new Error(`Invalid Harness runtime file in ${source}: root Team planner is stored in executors.json, not harness.json`);
523
+ }
524
+ if (typeof runtime.harness.harness.rootTeamId !== "string" || !runtime.harness.harness.rootTeamId.trim()) {
525
+ throw new Error(`Invalid Harness runtime file in ${source}: rootTeamId must reference the locked root Team`);
526
+ }
527
+ if (runtime.executors.schema !== "hunsu.executors.v1" || !Array.isArray(runtime.executors.executors)) {
528
+ throw new Error(`Invalid Executors runtime file in ${source}`);
529
+ }
530
+ if (runtime.resources.schema !== "hunsu.resources.v1" || !Array.isArray(runtime.resources.resources) || !Array.isArray(runtime.resources.bindings)) {
531
+ throw new Error(`Invalid Resources runtime file in ${source}`);
532
+ }
533
+ const artifactActions = validateArtifactActionsRuntimeFile(runtime.artifactActions, source);
534
+ const graph = runtimeHarnessGraph({
535
+ ...runtime,
536
+ artifactActions
537
+ }, source);
538
+ rootHarnessSnapshot(graph);
539
+ const currentExecution = validateCurrentExecutionState(runtime.currentExecution, source);
540
+ const previousExecution = validatePreviousExecutionState(runtime.previousExecution, source, selfCommit);
541
+ return {
542
+ completed: runtime.completed,
543
+ destinations: {
544
+ ...runtime.destinations,
545
+ compatibility: { ...runtime.destinations.compatibility, events }
546
+ },
547
+ harness: {
548
+ ...runtime.harness,
549
+ harness: {
550
+ name: runtime.harness.harness.name,
551
+ rootTeamId: graph.rootTeamId,
552
+ guardrails: graph.guardrails.map(guardrail => ({ ...guardrail })),
553
+ lock: runtime.harness.harness.lock
554
+ }
555
+ },
556
+ executors: {
557
+ ...runtime.executors,
558
+ executors: graph.executors
559
+ },
560
+ resources: {
561
+ ...runtime.resources,
562
+ resources: graph.resources
563
+ },
564
+ artifactActions,
565
+ currentExecution,
566
+ previousExecution,
567
+ eventLog
568
+ };
569
+ }
570
+ function runtimeHarnessGraph(runtime, source = "runtime") {
571
+ const graph = validateHarnessEntity({
572
+ rootTeamId: runtime.harness.harness.rootTeamId,
573
+ executors: runtime.executors.executors,
574
+ resources: runtime.resources.resources,
575
+ guardrails: runtime.harness.harness.guardrails ?? [],
576
+ artifactActions: runtime.artifactActions.actions
577
+ }, `${source} Harness graph`);
578
+ if (!graph.ok) {
579
+ throw new Error(`Invalid Harness runtime graph in ${source}: ${graph.error.message}`);
580
+ }
581
+ return graph.value;
582
+ }
583
+ function validateArtifactActionsRuntimeFile(value, source) {
584
+ if (value.schema !== "hunsu.artifact-actions.v1" || value.order !== "display-order" || !Array.isArray(value.actions)) {
585
+ throw new Error(`Invalid Artifact Actions runtime file in ${source}`);
586
+ }
587
+ const actions = decodeArtifactActionDefinitionArray(value.actions, "artifactActions.actions");
588
+ if (!actions.ok) {
589
+ throw new Error(`Invalid Artifact Actions runtime file in ${source}: ${actions.error.message}`);
590
+ }
591
+ return { ...value, actions: actions.value };
592
+ }
593
+ function validateCurrentExecutionState(value, source) {
594
+ if (!value || value.type === "none") {
595
+ return { type: "none" };
596
+ }
597
+ if (value.type !== "present" || !value.value || value.value.schema !== "hunsu.current-execution.v1") {
598
+ throw new Error(`Invalid current execution runtime file in ${source}`);
599
+ }
600
+ if (!value.value.execution || typeof value.value.execution !== "object") {
601
+ throw new Error(`Invalid current execution payload in ${source}`);
602
+ }
603
+ return value;
604
+ }
605
+ function validatePreviousExecutionState(value, source, selfCommit) {
606
+ if (!value || value.type === "none") {
607
+ return { type: "none" };
608
+ }
609
+ if (value.type !== "present" || !value.value || value.value.schema !== "hunsu.previous-execution.v1") {
610
+ throw new Error(`Invalid previous execution runtime file in ${source}`);
611
+ }
612
+ if (!value.value.sourceMoveCommit || !value.value.targetMoveId || !value.value.executeId || !value.value.runId || !value.value.lineId) {
613
+ throw new Error(`Invalid previous execution identity in ${source}`);
614
+ }
615
+ if (!value.value.plan || value.value.plan.nodeType !== "PlanNode") {
616
+ throw new Error(`Invalid previous execution PlanNode in ${source}`);
617
+ }
618
+ if (!Array.isArray(value.value.paths)) {
619
+ throw new Error(`Invalid previous execution PathNode list in ${source}`);
620
+ }
621
+ const moveFinalizerCommit = value.value.moveFinalizerCommit;
622
+ if (isSelfMoveCommitRef(moveFinalizerCommit)) {
623
+ if (!selfCommit) {
624
+ throw new Error(`Cannot resolve previous execution self commit in ${source}`);
625
+ }
626
+ return { type: "present", value: { ...value.value, moveFinalizerCommit: { type: "external", commit: selfCommit } } };
627
+ }
628
+ return value;
629
+ }
630
+ function resolveRuntimeEventSelfCommit(event, selfCommit) {
631
+ if (event.type !== "MoveRecorded") {
632
+ return event;
633
+ }
634
+ const commit = event.move.commit;
635
+ if (isSelfMoveCommitRef(commit)) {
636
+ if (!selfCommit) {
637
+ throw new Error("Cannot resolve self MOVE commit without containing commit");
638
+ }
639
+ return { ...event, move: { ...event.move, commit: selfCommit } };
640
+ }
641
+ if (commit === HUNSU_SELF_COMMIT_SENTINEL) {
642
+ if (!selfCommit) {
643
+ throw new Error("Cannot resolve self MOVE commit without containing commit");
644
+ }
645
+ return { ...event, move: { ...event.move, commit: selfCommit } };
646
+ }
647
+ return event;
648
+ }
649
+ function isSelfMoveCommitRef(value) {
650
+ return Boolean(value && typeof value === "object" && value.type === "self");
651
+ }
652
+ function runtimeCommitRef(value) {
653
+ if (isSelfMoveCommitRef(value)) {
654
+ return HUNSU_SELF_COMMIT_REF;
655
+ }
656
+ if (value === HUNSU_SELF_COMMIT_SENTINEL) {
657
+ return HUNSU_SELF_COMMIT_SENTINEL;
658
+ }
659
+ return parseCommitSha(String(value));
660
+ }
661
+ function writeHunsuRuntimeState(cwd, runtime, options = {}) {
662
+ const root = ensureGitRepository(cwd);
663
+ writeRuntimeFile(root, HUNSU_COMPLETED_DESTINATIONS_PATH, runtime.completed);
664
+ writeRuntimeFile(root, HUNSU_DESTINATIONS_PATH, destinationsForEncoding(runtime, options.selfCommitMoveIds ?? []));
665
+ writeRuntimeFile(root, HUNSU_HARNESS_PATH, runtime.harness);
666
+ writeRuntimeFile(root, HUNSU_EXECUTORS_PATH, runtime.executors);
667
+ writeRuntimeFile(root, HUNSU_RESOURCES_PATH, runtime.resources);
668
+ writeRuntimeFile(root, HUNSU_ARTIFACT_ACTIONS_PATH, runtime.artifactActions);
669
+ writeCurrentExecutionRuntimeFile(root, runtime.currentExecution);
670
+ writePreviousExecutionRuntimeFile(root, runtime.previousExecution, options.selfCommitMoveIds ?? []);
671
+ }
672
+ function writeRuntimeFile(root, path, value) {
673
+ const file = join(root, path);
674
+ mkdirSync(dirname(file), { recursive: true });
675
+ writeFileSync(file, encodeHunsuRuntimeFile(value).text, "utf8");
676
+ }
677
+ function writeCurrentExecutionRuntimeFile(root, state) {
678
+ const file = join(root, HUNSU_CURRENT_EXECUTION_PATH);
679
+ if (state.type === "none") {
680
+ if (existsSync(file)) {
681
+ rmSync(file, { force: true });
682
+ }
683
+ return;
684
+ }
685
+ writeRuntimeFile(root, HUNSU_CURRENT_EXECUTION_PATH, state.value);
686
+ }
687
+ function writePreviousExecutionRuntimeFile(root, state, selfCommitMoveIds) {
688
+ const file = join(root, HUNSU_PREVIOUS_EXECUTION_PATH);
689
+ if (state.type === "none") {
690
+ if (existsSync(file)) {
691
+ rmSync(file, { force: true });
692
+ }
693
+ return;
694
+ }
695
+ const value = previousExecutionForEncoding(state.value, selfCommitMoveIds);
696
+ writeRuntimeFile(root, HUNSU_PREVIOUS_EXECUTION_PATH, value);
697
+ }
698
+ function destinationsForEncoding(runtime, selfCommitMoveIds) {
699
+ return {
700
+ ...runtime.destinations,
701
+ compatibility: {
702
+ events: runtime.eventLog.events.map(event => eventForEncoding(event, selfCommitMoveIds)),
703
+ updatedAt: runtime.eventLog.updatedAt
704
+ }
705
+ };
706
+ }
707
+ function eventForEncoding(event, selfCommitMoveIds) {
708
+ if (event.type !== "MoveRecorded" || !selfCommitMoveIds.includes(String(event.move.id))) {
709
+ return event;
710
+ }
711
+ return { ...event, move: { ...event.move, commit: HUNSU_SELF_COMMIT_REF } };
712
+ }
713
+ function previousExecutionForEncoding(value, selfCommitMoveIds) {
714
+ if (!value.moveFinalizerCommit || value.moveFinalizerCommit.type !== "external" || !selfCommitMoveIds.includes(value.targetMoveId)) {
715
+ return value;
716
+ }
717
+ return { ...value, moveFinalizerCommit: HUNSU_SELF_COMMIT_REF };
718
+ }
719
+ function commitRuntimeStateIfRequested(cwd, commitMessage) {
720
+ if (!commitMessage) {
721
+ return;
722
+ }
723
+ const paths = stageableRuntimePaths(cwd);
724
+ if (paths.length === 0) {
725
+ return;
726
+ }
727
+ git(["add", "--all", "--", ...paths], { cwd });
728
+ const status = git(["status", "--porcelain=v1", "--", ...paths], { cwd }).trim();
729
+ if (!status) {
730
+ return;
731
+ }
732
+ git(["commit", "--only", "-m", commitMessage, "--", ...paths], { cwd });
733
+ }
734
+ function stageableRuntimePaths(cwd) {
735
+ return [...HUNSU_RUNTIME_PATHS, HUNSU_CURRENT_EXECUTION_PATH, HUNSU_PREVIOUS_EXECUTION_PATH].filter(path => existsSync(join(cwd, path)) || isTrackedPath(cwd, path));
736
+ }
737
+ function isTrackedPath(cwd, path) {
738
+ try {
739
+ git(["ls-files", "--error-unmatch", path], { cwd });
740
+ return true;
741
+ }
742
+ catch (error) {
743
+ if (error instanceof GitError) {
744
+ return false;
745
+ }
746
+ throw error;
747
+ }
748
+ }
749
+ function domainStoreFromRuntime(root, runtime, source, eventRefs, checksum, commit) {
750
+ const events = [...runtime.eventLog.events];
751
+ return {
752
+ root,
753
+ eventRefs,
754
+ events,
755
+ board: projectDomainEvents(events, source),
756
+ runtimePaths: HUNSU_RUNTIME_PATHS,
757
+ runtime,
758
+ source,
759
+ checksum,
760
+ commit
761
+ };
762
+ }
763
+ function projectDomainEvents(events, source) {
764
+ const projected = tryProjectBoard(events);
765
+ if (!projected.ok) {
766
+ throw new Error(`Invalid Hunsu domain event stream in ${source}: ${projected.error.message}`);
767
+ }
768
+ return projected.value;
769
+ }
770
+ function readLatestReachableHunsuRuntimeState(cwd) {
771
+ return readReachableHunsuRuntimeStates(cwd)
772
+ .sort((left, right) => runtimeEventCount(right.runtime) - runtimeEventCount(left.runtime))
773
+ .at(0);
774
+ }
775
+ function runtimeEventCount(runtime) {
776
+ return runtime.eventLog.events.length;
777
+ }
778
+ function checksumRuntimeState(runtime) {
779
+ return parseRuntimeChecksum(sha256([
780
+ encodeHunsuRuntimeFile(runtime.completed).checksum,
781
+ encodeHunsuRuntimeFile(destinationsForEncoding(runtime, [])).checksum,
782
+ encodeHunsuRuntimeFile(runtime.harness).checksum,
783
+ encodeHunsuRuntimeFile(runtime.executors).checksum,
784
+ encodeHunsuRuntimeFile(runtime.resources).checksum,
785
+ encodeHunsuRuntimeFile(runtime.artifactActions).checksum,
786
+ runtime.currentExecution.type === "present" ? encodeHunsuRuntimeFile(runtime.currentExecution.value).checksum : "none",
787
+ runtime.previousExecution.type === "present" ? encodeHunsuRuntimeFile(runtime.previousExecution.value).checksum : "none"
788
+ ].join("\n")));
789
+ }
790
+ function decodeRuntimeEnvelope(text, source, expectedHeader) {
791
+ const normalized = text.replace(/\r\n/g, "\n");
792
+ const separator = normalized.indexOf("\n\n");
793
+ if (separator === -1) {
794
+ return domainStoreError(`Invalid Hunsu runtime envelope in ${source}`);
795
+ }
796
+ const header = normalized.slice(0, separator).split("\n");
797
+ const payload = normalized.slice(separator + 2).trim();
798
+ if (header[0] !== expectedHeader) {
799
+ return domainStoreError(`Invalid Hunsu runtime header in ${source}`);
800
+ }
801
+ const metadata = new Map(header.slice(1).map(line => {
802
+ const index = line.indexOf(":");
803
+ return index === -1 ? [line.trim(), ""] : [line.slice(0, index).trim(), line.slice(index + 1).trim()];
804
+ }));
805
+ if (metadata.get("encoding") !== HUNSU_RUNTIME_ENCODING) {
806
+ return domainStoreError(`Unsupported Hunsu runtime encoding in ${source}: ${metadata.get("encoding") ?? "missing"}`);
807
+ }
808
+ const expectedChecksum = metadata.get("checksum")?.replace(/^sha256:/, "");
809
+ if (!expectedChecksum) {
810
+ return domainStoreError(`Missing Hunsu runtime checksum in ${source}`);
811
+ }
812
+ let json;
813
+ try {
814
+ json = gunzipSync(Buffer.from(payload, "base64url")).toString("utf8");
815
+ }
816
+ catch (error) {
817
+ return domainStoreError(`Invalid Hunsu runtime payload in ${source}: ${error instanceof Error ? error.message : String(error)}`);
818
+ }
819
+ const actualChecksum = sha256(json);
820
+ if (actualChecksum !== expectedChecksum) {
821
+ return domainStoreError(`Hunsu runtime checksum mismatch in ${source}`);
822
+ }
823
+ try {
824
+ return ok({ value: JSON.parse(json), checksum: parseRuntimeChecksum(actualChecksum) });
825
+ }
826
+ catch (error) {
827
+ return domainStoreError(`Invalid Hunsu runtime JSON in ${source}: ${error instanceof Error ? error.message : String(error)}`);
828
+ }
829
+ }
830
+ function readLegacyHunsuRuntimeStateFromWorktree(cwd) {
831
+ const root = ensureGitRepository(cwd);
832
+ const path = join(root, HUNSU_LEGACY_STATE_PATH);
833
+ if (!existsSync(path)) {
834
+ return undefined;
835
+ }
836
+ const state = unwrapDomainStoreResult(decodeLegacyHunsuRuntimeStateText(readFileSync(path, "utf8"), path));
837
+ return { state, checksum: checksumLegacyRuntimeState(state) };
838
+ }
839
+ function readLegacyHunsuRuntimeStateAtRef(cwd, ref) {
840
+ const root = ensureGitRepository(cwd);
841
+ try {
842
+ const text = git(["show", `${ref}:${HUNSU_LEGACY_STATE_PATH}`], { cwd: root });
843
+ const state = unwrapDomainStoreResult(decodeLegacyHunsuRuntimeStateText(text, `${ref}:${HUNSU_LEGACY_STATE_PATH}`));
844
+ return { state, checksum: checksumLegacyRuntimeState(state) };
845
+ }
846
+ catch (error) {
847
+ if (error instanceof GitError) {
848
+ return undefined;
849
+ }
850
+ throw error;
851
+ }
852
+ }
853
+ function decodeLegacyHunsuRuntimeStateText(text, source) {
854
+ const decoded = decodeRuntimeEnvelope(text, source, LEGACY_STATE_HEADER);
855
+ if (!decoded.ok) {
856
+ return decoded;
857
+ }
858
+ const value = decoded.value.value;
859
+ if (!value || typeof value !== "object") {
860
+ return domainStoreError(`Invalid legacy Hunsu runtime state JSON in ${source}: expected object`);
861
+ }
862
+ const record = value;
863
+ if (record.version !== 1 || !Array.isArray(record.events)) {
864
+ return domainStoreError(`Invalid legacy Hunsu runtime state in ${source}`);
865
+ }
866
+ const events = [];
867
+ for (const [index, event] of record.events.entries()) {
868
+ const validation = validateDomainEvent(event);
869
+ if (!validation.ok) {
870
+ return domainStoreError(`Invalid legacy Hunsu runtime state event ${index} in ${source}: ${validation.error.message}`);
871
+ }
872
+ events.push(validation.value);
873
+ }
874
+ return ok({
875
+ version: 1,
876
+ events,
877
+ ...(typeof record.updatedAt === "string" ? { updatedAt: record.updatedAt } : {})
878
+ });
879
+ }
880
+ function checksumLegacyRuntimeState(state) {
881
+ return parseRuntimeChecksum(sha256(`${JSON.stringify(state)}\n`));
882
+ }
883
+ function domainStoreError(message) {
884
+ return err({ type: "DomainStoreError", message });
885
+ }
886
+ function readDraftRuntimeJson(root, dir, fileName) {
887
+ const path = join(root, dir, fileName);
888
+ try {
889
+ return ok(JSON.parse(readFileSync(path, "utf8")));
890
+ }
891
+ catch (error) {
892
+ return domainStoreError(`Cannot read ${dir}/${fileName}: ${error instanceof Error ? error.message : String(error)}`);
893
+ }
894
+ }
895
+ function cloneJson(value) {
896
+ return JSON.parse(JSON.stringify(value));
897
+ }
898
+ function stableJson(value) {
899
+ return JSON.stringify(sortJson(value));
900
+ }
901
+ function sortJson(value) {
902
+ if (Array.isArray(value)) {
903
+ return value.map(sortJson);
904
+ }
905
+ if (value && typeof value === "object") {
906
+ return Object.fromEntries(Object.entries(value)
907
+ .sort(([left], [right]) => left.localeCompare(right))
908
+ .map(([key, entry]) => [key, sortJson(entry)]));
909
+ }
910
+ return value;
911
+ }
912
+ function unwrapDomainStoreResult(result) {
913
+ if (result.ok) {
914
+ return result.value;
915
+ }
916
+ throw new Error(result.error.message);
917
+ }
918
+ function currentHeadCommit(cwd) {
919
+ try {
920
+ return parseCommitSha(git(["rev-parse", "--verify", "HEAD^{commit}"], { cwd }).trim());
921
+ }
922
+ catch (error) {
923
+ if (error instanceof GitError) {
924
+ return undefined;
925
+ }
926
+ throw error;
927
+ }
928
+ }
929
+ function isMissingFileError(error) {
930
+ if (!(error instanceof Error)) {
931
+ return false;
932
+ }
933
+ return "code" in error && error.code === "ENOENT";
934
+ }
935
+ function sha256(text) {
936
+ return createHash("sha256").update(text).digest("hex");
937
+ }
938
+ function parseDomainEventRef(line) {
939
+ const [ref, object, objectType] = line.split(DOMAIN_EVENT_REF_SEPARATOR);
940
+ return {
941
+ ref,
942
+ object,
943
+ objectType,
944
+ ordinal: parseDomainEventOrdinal(ref)
945
+ };
946
+ }
947
+ function parseDomainEventOrdinal(ref) {
948
+ const leaf = ref.slice(ref.lastIndexOf("/") + 1);
949
+ const match = leaf.match(/^E(\d+)(?:-|$)/);
950
+ return match ? Number.parseInt(match[1], 10) : Number.MAX_SAFE_INTEGER;
951
+ }