sentinelayer-cli 0.6.2 → 0.8.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 (159) hide show
  1. package/README.md +996 -996
  2. package/bin/create-sentinelayer.js +5 -5
  3. package/bin/sentinelayer-cli.js +4 -4
  4. package/bin/sl.js +5 -5
  5. package/package.json +64 -63
  6. package/src/agents/jules/config/definition.js +160 -160
  7. package/src/agents/jules/config/system-prompt.js +182 -182
  8. package/src/agents/jules/error-intake.js +51 -51
  9. package/src/agents/jules/fix-cycle.js +17 -17
  10. package/src/agents/jules/loop.js +457 -450
  11. package/src/agents/jules/pulse.js +10 -10
  12. package/src/agents/jules/stream.js +187 -186
  13. package/src/agents/jules/swarm/file-scanner.js +74 -74
  14. package/src/agents/jules/swarm/index.js +11 -11
  15. package/src/agents/jules/swarm/orchestrator.js +362 -362
  16. package/src/agents/jules/swarm/pattern-hunter.js +123 -123
  17. package/src/agents/jules/swarm/sub-agent.js +311 -309
  18. package/src/agents/jules/tools/aidenid-email.js +189 -189
  19. package/src/agents/jules/tools/auth-audit.js +1699 -1691
  20. package/src/agents/jules/tools/dispatch.js +340 -335
  21. package/src/agents/jules/tools/file-edit.js +2 -2
  22. package/src/agents/jules/tools/file-read.js +2 -2
  23. package/src/agents/jules/tools/frontend-analyze.js +570 -570
  24. package/src/agents/jules/tools/glob.js +2 -2
  25. package/src/agents/jules/tools/grep.js +2 -2
  26. package/src/agents/jules/tools/index.js +29 -29
  27. package/src/agents/jules/tools/path-guards.js +2 -2
  28. package/src/agents/jules/tools/runtime-audit.js +507 -507
  29. package/src/agents/jules/tools/shell.js +2 -2
  30. package/src/agents/jules/tools/url-policy.js +100 -100
  31. package/src/agents/persona-visuals.js +64 -61
  32. package/src/agents/shared-tools/dispatch-core.js +320 -315
  33. package/src/agents/shared-tools/file-edit.js +180 -180
  34. package/src/agents/shared-tools/file-read.js +100 -100
  35. package/src/agents/shared-tools/glob.js +168 -168
  36. package/src/agents/shared-tools/grep.js +228 -228
  37. package/src/agents/shared-tools/index.js +46 -46
  38. package/src/agents/shared-tools/path-guards.js +161 -161
  39. package/src/agents/shared-tools/shell.js +383 -383
  40. package/src/ai/aidenid.js +1021 -1009
  41. package/src/ai/client.js +553 -553
  42. package/src/ai/domain-target-store.js +268 -268
  43. package/src/ai/identity-store.js +270 -270
  44. package/src/ai/proxy.js +137 -137
  45. package/src/ai/site-store.js +145 -145
  46. package/src/audit/agents/architecture.js +180 -180
  47. package/src/audit/agents/compliance.js +179 -179
  48. package/src/audit/agents/documentation.js +165 -165
  49. package/src/audit/agents/performance.js +145 -145
  50. package/src/audit/agents/security.js +215 -215
  51. package/src/audit/agents/testing.js +172 -172
  52. package/src/audit/orchestrator.js +557 -557
  53. package/src/audit/package.js +204 -204
  54. package/src/audit/registry.js +284 -284
  55. package/src/audit/replay.js +103 -103
  56. package/src/auth/gate.js +400 -371
  57. package/src/auth/http.js +681 -611
  58. package/src/auth/service.js +1106 -1106
  59. package/src/auth/session-store.js +813 -813
  60. package/src/cli.js +257 -252
  61. package/src/commands/ai/identity-lifecycle.js +1338 -1338
  62. package/src/commands/ai/provision-governance.js +1272 -1272
  63. package/src/commands/ai/shared.js +147 -147
  64. package/src/commands/ai.js +11 -11
  65. package/src/commands/apply.js +12 -12
  66. package/src/commands/audit.js +1171 -1166
  67. package/src/commands/auth.js +419 -419
  68. package/src/commands/chat.js +191 -191
  69. package/src/commands/config.js +184 -184
  70. package/src/commands/cost.js +311 -311
  71. package/src/commands/daemon/core.js +850 -850
  72. package/src/commands/daemon/extended.js +1048 -1048
  73. package/src/commands/daemon/shared.js +213 -213
  74. package/src/commands/daemon.js +11 -11
  75. package/src/commands/guide.js +174 -174
  76. package/src/commands/ingest.js +58 -58
  77. package/src/commands/init.js +55 -55
  78. package/src/commands/legacy-args.js +10 -10
  79. package/src/commands/mcp.js +461 -461
  80. package/src/commands/omargate.js +29 -29
  81. package/src/commands/persona.js +20 -20
  82. package/src/commands/plugin.js +260 -260
  83. package/src/commands/policy.js +132 -132
  84. package/src/commands/prompt.js +238 -238
  85. package/src/commands/review.js +704 -704
  86. package/src/commands/scan.js +872 -872
  87. package/src/commands/session.js +590 -0
  88. package/src/commands/spec.js +778 -716
  89. package/src/commands/swarm.js +651 -651
  90. package/src/commands/telemetry.js +202 -202
  91. package/src/commands/watch.js +511 -511
  92. package/src/config/agent-dictionary.js +182 -182
  93. package/src/config/io.js +56 -56
  94. package/src/config/paths.js +18 -18
  95. package/src/config/schema.js +55 -55
  96. package/src/config/service.js +184 -184
  97. package/src/cost/budget.js +235 -235
  98. package/src/cost/history.js +188 -188
  99. package/src/cost/tracker.js +171 -171
  100. package/src/daemon/artifact-lineage.js +534 -534
  101. package/src/daemon/assignment-ledger.js +966 -770
  102. package/src/daemon/ast-parser-layer.js +258 -258
  103. package/src/daemon/budget-governor.js +633 -633
  104. package/src/daemon/callgraph-overlay.js +646 -646
  105. package/src/daemon/error-worker.js +1209 -626
  106. package/src/daemon/fix-cycle.js +384 -377
  107. package/src/daemon/hybrid-mapper.js +929 -929
  108. package/src/daemon/ingest-refresh.js +10 -9
  109. package/src/daemon/jira-lifecycle.js +767 -632
  110. package/src/daemon/operator-control.js +657 -657
  111. package/src/daemon/pulse.js +327 -327
  112. package/src/daemon/reliability-lane.js +471 -471
  113. package/src/daemon/scope-engine.js +1068 -0
  114. package/src/daemon/watchdog.js +971 -971
  115. package/src/events/schema.js +190 -0
  116. package/src/guide/generator.js +316 -316
  117. package/src/ingest/engine.js +918 -918
  118. package/src/interactive/index.js +97 -97
  119. package/src/legacy-cli.js +3161 -2994
  120. package/src/mcp/registry.js +695 -695
  121. package/src/memory/blackboard.js +301 -301
  122. package/src/memory/retrieval.js +581 -581
  123. package/src/plugin/manifest.js +553 -553
  124. package/src/policy/packs.js +144 -144
  125. package/src/prompt/generator.js +136 -118
  126. package/src/review/ai-review.js +679 -679
  127. package/src/review/local-review.js +1351 -1305
  128. package/src/review/omargate-interactive.js +68 -68
  129. package/src/review/omargate-orchestrator.js +404 -300
  130. package/src/review/persona-prompts.js +296 -296
  131. package/src/review/replay.js +235 -235
  132. package/src/review/report.js +664 -664
  133. package/src/review/scan-modes.js +48 -42
  134. package/src/review/spec-binding.js +487 -487
  135. package/src/scaffold/generator.js +67 -67
  136. package/src/scaffold/templates.js +150 -150
  137. package/src/scan/generator.js +418 -418
  138. package/src/scan/gh-secrets.js +107 -107
  139. package/src/session/agent-registry.js +352 -0
  140. package/src/session/daemon.js +801 -0
  141. package/src/session/paths.js +33 -0
  142. package/src/session/runtime-bridge.js +739 -0
  143. package/src/session/store.js +388 -0
  144. package/src/session/stream.js +325 -0
  145. package/src/spec/generator.js +619 -519
  146. package/src/spec/regenerate.js +237 -237
  147. package/src/spec/templates.js +91 -91
  148. package/src/swarm/dashboard.js +247 -247
  149. package/src/swarm/factory.js +363 -363
  150. package/src/swarm/pentest.js +934 -934
  151. package/src/swarm/registry.js +419 -419
  152. package/src/swarm/report.js +158 -158
  153. package/src/swarm/runtime.js +576 -576
  154. package/src/swarm/scenario-dsl.js +272 -272
  155. package/src/telemetry/ledger.js +302 -302
  156. package/src/telemetry/session-tracker.js +234 -234
  157. package/src/telemetry/sync.js +203 -203
  158. package/src/ui/command-hints.js +13 -13
  159. package/src/ui/markdown.js +220 -220
@@ -1,770 +1,966 @@
1
- import fsp from "node:fs/promises";
2
- import path from "node:path";
3
-
4
- import { WORK_ITEM_STATUSES, resolveErrorDaemonStorage } from "./error-worker.js";
5
-
6
- const LEDGER_SCHEMA_VERSION = "1.0.0";
7
- const QUEUE_SCHEMA_VERSION = "1.0.0";
8
-
9
- export const ASSIGNMENT_STATUSES = Object.freeze([
10
- "QUEUED",
11
- "CLAIMED",
12
- "IN_PROGRESS",
13
- "RELEASED",
14
- "DONE",
15
- "BLOCKED",
16
- "SQUASHED",
17
- ]);
18
-
19
- const ASSIGNMENT_STATUS_SET = new Set(ASSIGNMENT_STATUSES);
20
- const WORK_ITEM_STATUS_SET = new Set(WORK_ITEM_STATUSES);
21
- const ACTIVE_ASSIGNMENT_STATUSES = new Set(["CLAIMED", "IN_PROGRESS"]);
22
- const RELEASE_TARGET_STATUSES = new Set(["QUEUED", "DONE", "BLOCKED", "SQUASHED"]);
23
-
24
- function normalizeString(value) {
25
- return String(value || "").trim();
26
- }
27
-
28
- function normalizeIsoTimestamp(value, fallbackIso = new Date().toISOString()) {
29
- const normalized = normalizeString(value);
30
- if (!normalized) {
31
- return fallbackIso;
32
- }
33
- const epoch = Date.parse(normalized);
34
- if (!Number.isFinite(epoch)) {
35
- return fallbackIso;
36
- }
37
- return new Date(epoch).toISOString();
38
- }
39
-
40
- function normalizePositiveInteger(value, fallbackValue = 1) {
41
- if (value === undefined || value === null || normalizeString(value) === "") {
42
- return fallbackValue;
43
- }
44
- const normalized = Number(value);
45
- if (!Number.isFinite(normalized) || normalized <= 0) {
46
- throw new Error("Value must be a positive integer.");
47
- }
48
- return Math.floor(normalized);
49
- }
50
-
51
- function normalizeMetadata(value) {
52
- if (!value || typeof value !== "object" || Array.isArray(value)) {
53
- return {};
54
- }
55
- return { ...value };
56
- }
57
-
58
- function normalizeAssignmentStatus(value, fallbackValue = "QUEUED") {
59
- const normalized = normalizeString(value).toUpperCase();
60
- if (ASSIGNMENT_STATUS_SET.has(normalized)) {
61
- return normalized;
62
- }
63
- return fallbackValue;
64
- }
65
-
66
- function normalizeWorkItemStatus(value, fallbackValue = "QUEUED") {
67
- const normalized = normalizeString(value).toUpperCase();
68
- if (WORK_ITEM_STATUS_SET.has(normalized)) {
69
- return normalized;
70
- }
71
- return fallbackValue;
72
- }
73
-
74
- function toIsoAfterSeconds(nowIso, seconds) {
75
- const baseEpoch = Date.parse(normalizeIsoTimestamp(nowIso, new Date().toISOString())) || Date.now();
76
- return new Date(baseEpoch + seconds * 1000).toISOString();
77
- }
78
-
79
- function parseStatusList(statuses = []) {
80
- if (!Array.isArray(statuses)) {
81
- return null;
82
- }
83
- const normalized = statuses
84
- .map((item) => normalizeString(item).toUpperCase())
85
- .filter(Boolean)
86
- .filter((item) => ASSIGNMENT_STATUS_SET.has(item));
87
- if (normalized.length === 0) {
88
- return null;
89
- }
90
- return new Set(normalized);
91
- }
92
-
93
- function createInitialLedger(nowIso = new Date().toISOString()) {
94
- return {
95
- schemaVersion: LEDGER_SCHEMA_VERSION,
96
- generatedAt: normalizeIsoTimestamp(nowIso, nowIso),
97
- assignments: [],
98
- };
99
- }
100
-
101
- function createInitialQueue(nowIso = new Date().toISOString()) {
102
- return {
103
- schemaVersion: QUEUE_SCHEMA_VERSION,
104
- generatedAt: normalizeIsoTimestamp(nowIso, nowIso),
105
- items: [],
106
- };
107
- }
108
-
109
- function normalizeAssignmentRecord(record = {}, nowIso = new Date().toISOString()) {
110
- const updatedAt = normalizeIsoTimestamp(record.updatedAt, nowIso);
111
- return {
112
- workItemId: normalizeString(record.workItemId),
113
- assignedAgentIdentity: normalizeString(record.assignedAgentIdentity) || null,
114
- leasedAt: record.leasedAt ? normalizeIsoTimestamp(record.leasedAt, updatedAt) : null,
115
- leaseTtlSeconds: Math.max(1, normalizePositiveInteger(record.leaseTtlSeconds, 1800)),
116
- leaseExpiresAt: record.leaseExpiresAt ? normalizeIsoTimestamp(record.leaseExpiresAt, updatedAt) : null,
117
- status: normalizeAssignmentStatus(record.status),
118
- stage: normalizeString(record.stage) || "triage",
119
- runId: normalizeString(record.runId) || null,
120
- jiraIssueKey: normalizeString(record.jiraIssueKey) || null,
121
- budgetSnapshot: normalizeMetadata(record.budgetSnapshot),
122
- heartbeatAt: record.heartbeatAt ? normalizeIsoTimestamp(record.heartbeatAt, updatedAt) : null,
123
- releasedAt: record.releasedAt ? normalizeIsoTimestamp(record.releasedAt, updatedAt) : null,
124
- releaseReason: normalizeString(record.releaseReason) || null,
125
- updatedAt,
126
- };
127
- }
128
-
129
- function isAssignmentExpired(record = {}, nowIso = new Date().toISOString()) {
130
- if (!record || !ACTIVE_ASSIGNMENT_STATUSES.has(normalizeAssignmentStatus(record.status))) {
131
- return false;
132
- }
133
- const expiry = Date.parse(String(record.leaseExpiresAt || ""));
134
- const now = Date.parse(normalizeIsoTimestamp(nowIso, new Date().toISOString()));
135
- if (!Number.isFinite(expiry) || !Number.isFinite(now)) {
136
- return false;
137
- }
138
- return expiry <= now;
139
- }
140
-
141
- function normalizeQueueItem(item = {}, nowIso = new Date().toISOString()) {
142
- return {
143
- ...item,
144
- workItemId: normalizeString(item.workItemId),
145
- status: normalizeWorkItemStatus(item.status),
146
- updatedAt: normalizeIsoTimestamp(item.updatedAt, nowIso),
147
- metadata: normalizeMetadata(item.metadata),
148
- };
149
- }
150
-
151
- async function loadJsonFile(filePath, defaultFactory) {
152
- try {
153
- const raw = await fsp.readFile(filePath, "utf-8");
154
- return JSON.parse(raw);
155
- } catch (error) {
156
- if (error && typeof error === "object" && error.code === "ENOENT") {
157
- return defaultFactory();
158
- }
159
- throw error;
160
- }
161
- }
162
-
163
- async function writeJsonFile(filePath, payload = {}) {
164
- await fsp.mkdir(path.dirname(filePath), { recursive: true });
165
- await fsp.writeFile(filePath, `${JSON.stringify(payload, null, 2)}\n`, "utf-8");
166
- }
167
-
168
- async function appendEvent(filePath, payload = {}) {
169
- await fsp.mkdir(path.dirname(filePath), { recursive: true });
170
- await fsp.appendFile(filePath, `${JSON.stringify(payload)}\n`, "utf-8");
171
- }
172
-
173
- async function loadLedger(ledgerPath, nowIso = new Date().toISOString()) {
174
- const parsed = await loadJsonFile(ledgerPath, () => createInitialLedger(nowIso));
175
- return {
176
- schemaVersion: normalizeString(parsed.schemaVersion) || LEDGER_SCHEMA_VERSION,
177
- generatedAt: normalizeIsoTimestamp(parsed.generatedAt, nowIso),
178
- assignments: Array.isArray(parsed.assignments)
179
- ? parsed.assignments
180
- .map((record) => normalizeAssignmentRecord(record, nowIso))
181
- .filter((record) => normalizeString(record.workItemId))
182
- : [],
183
- };
184
- }
185
-
186
- async function writeLedger(ledgerPath, ledger = {}, nowIso = new Date().toISOString()) {
187
- const normalized = {
188
- schemaVersion: LEDGER_SCHEMA_VERSION,
189
- generatedAt: normalizeIsoTimestamp(nowIso, nowIso),
190
- assignments: Array.isArray(ledger.assignments)
191
- ? ledger.assignments
192
- .map((record) => normalizeAssignmentRecord(record, nowIso))
193
- .filter((record) => normalizeString(record.workItemId))
194
- : [],
195
- };
196
- await writeJsonFile(ledgerPath, normalized);
197
- return normalized;
198
- }
199
-
200
- async function loadQueue(queuePath, nowIso = new Date().toISOString()) {
201
- const parsed = await loadJsonFile(queuePath, () => createInitialQueue(nowIso));
202
- return {
203
- schemaVersion: normalizeString(parsed.schemaVersion) || QUEUE_SCHEMA_VERSION,
204
- generatedAt: normalizeIsoTimestamp(parsed.generatedAt, nowIso),
205
- items: Array.isArray(parsed.items)
206
- ? parsed.items.map((item) => normalizeQueueItem(item, nowIso)).filter((item) => item.workItemId)
207
- : [],
208
- };
209
- }
210
-
211
- async function writeQueue(queuePath, queue = {}, nowIso = new Date().toISOString()) {
212
- const normalized = {
213
- schemaVersion: QUEUE_SCHEMA_VERSION,
214
- generatedAt: normalizeIsoTimestamp(nowIso, nowIso),
215
- items: Array.isArray(queue.items)
216
- ? queue.items.map((item) => normalizeQueueItem(item, nowIso)).filter((item) => item.workItemId)
217
- : [],
218
- };
219
- await writeJsonFile(queuePath, normalized);
220
- return normalized;
221
- }
222
-
223
- function getAssignmentStoragePaths(baseStorage = {}) {
224
- return {
225
- ...baseStorage,
226
- ledgerPath: path.join(baseStorage.baseDir, "assignment-ledger.json"),
227
- eventsPath: path.join(baseStorage.baseDir, "assignment-events.ndjson"),
228
- };
229
- }
230
-
231
- async function loadLedgerAndQueue(storage, nowIso) {
232
- const [ledger, queue] = await Promise.all([
233
- loadLedger(storage.ledgerPath, nowIso),
234
- loadQueue(storage.queuePath, nowIso),
235
- ]);
236
- return { ledger, queue };
237
- }
238
-
239
- function findQueueItem(queue = {}, workItemId = "") {
240
- return queue.items.find((item) => item.workItemId === workItemId) || null;
241
- }
242
-
243
- function updateQueueItem({
244
- queue,
245
- workItemId,
246
- status,
247
- assignedAgentIdentity = null,
248
- stage = "",
249
- runId = null,
250
- jiraIssueKey = null,
251
- nowIso,
252
- } = {}) {
253
- const index = queue.items.findIndex((item) => item.workItemId === workItemId);
254
- if (index < 0) {
255
- throw new Error(`Work item '${workItemId}' was not found in daemon queue.`);
256
- }
257
- const existing = queue.items[index];
258
- queue.items[index] = normalizeQueueItem(
259
- {
260
- ...existing,
261
- status: normalizeWorkItemStatus(status, existing.status),
262
- updatedAt: nowIso,
263
- metadata: {
264
- ...normalizeMetadata(existing.metadata),
265
- assignedAgentIdentity: assignedAgentIdentity || null,
266
- stage: normalizeString(stage) || null,
267
- runId: normalizeString(runId) || null,
268
- jiraIssueKey: normalizeString(jiraIssueKey) || null,
269
- },
270
- },
271
- nowIso
272
- );
273
- return queue.items[index];
274
- }
275
-
276
- function findAssignmentIndex(ledger = {}, workItemId = "") {
277
- return ledger.assignments.findIndex((record) => record.workItemId === workItemId);
278
- }
279
-
280
- function requireAgentIdentity(value, fieldName = "agentIdentity") {
281
- const normalized = normalizeString(value);
282
- if (!normalized) {
283
- throw new Error(`${fieldName} is required.`);
284
- }
285
- return normalized;
286
- }
287
-
288
- function normalizeReleaseTargetStatus(value) {
289
- const normalized = normalizeString(value).toUpperCase();
290
- if (!RELEASE_TARGET_STATUSES.has(normalized)) {
291
- throw new Error(
292
- `status must be one of: ${[...RELEASE_TARGET_STATUSES].join(", ")}.`
293
- );
294
- }
295
- return normalized;
296
- }
297
-
298
- export async function resolveAssignmentLedgerStorage({
299
- targetPath = ".",
300
- outputDir = "",
301
- env,
302
- homeDir,
303
- } = {}) {
304
- const daemonStorage = await resolveErrorDaemonStorage({
305
- targetPath,
306
- outputDir,
307
- env,
308
- homeDir,
309
- });
310
- return getAssignmentStoragePaths(daemonStorage);
311
- }
312
-
313
- export async function claimAssignment({
314
- targetPath = ".",
315
- outputDir = "",
316
- workItemId,
317
- agentIdentity,
318
- leaseTtlSeconds = 1800,
319
- stage = "triage",
320
- runId = "",
321
- jiraIssueKey = "",
322
- budgetSnapshot = {},
323
- env,
324
- homeDir,
325
- nowIso = new Date().toISOString(),
326
- } = {}) {
327
- const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
328
- const normalizedWorkItemId = normalizeString(workItemId);
329
- if (!normalizedWorkItemId) {
330
- throw new Error("workItemId is required.");
331
- }
332
- const normalizedAgentIdentity = requireAgentIdentity(agentIdentity);
333
- const normalizedTtl = normalizePositiveInteger(leaseTtlSeconds, 1800);
334
- const storage = await resolveAssignmentLedgerStorage({
335
- targetPath,
336
- outputDir,
337
- env,
338
- homeDir,
339
- });
340
- const { ledger, queue } = await loadLedgerAndQueue(storage, normalizedNow);
341
-
342
- const queueItem = findQueueItem(queue, normalizedWorkItemId);
343
- if (!queueItem) {
344
- throw new Error(`Work item '${normalizedWorkItemId}' was not found in daemon queue.`);
345
- }
346
-
347
- const assignmentIndex = findAssignmentIndex(ledger, normalizedWorkItemId);
348
- const existingAssignment = assignmentIndex >= 0 ? ledger.assignments[assignmentIndex] : null;
349
- if (
350
- existingAssignment &&
351
- ACTIVE_ASSIGNMENT_STATUSES.has(existingAssignment.status) &&
352
- !isAssignmentExpired(existingAssignment, normalizedNow) &&
353
- existingAssignment.assignedAgentIdentity !== normalizedAgentIdentity
354
- ) {
355
- throw new Error(
356
- `Work item '${normalizedWorkItemId}' is currently leased by '${existingAssignment.assignedAgentIdentity}'.`
357
- );
358
- }
359
-
360
- const leaseExpiresAt = toIsoAfterSeconds(normalizedNow, normalizedTtl);
361
- const nextRecord = normalizeAssignmentRecord(
362
- {
363
- workItemId: normalizedWorkItemId,
364
- assignedAgentIdentity: normalizedAgentIdentity,
365
- leasedAt: normalizedNow,
366
- leaseTtlSeconds: normalizedTtl,
367
- leaseExpiresAt,
368
- status: "CLAIMED",
369
- stage,
370
- runId,
371
- jiraIssueKey,
372
- budgetSnapshot: normalizeMetadata(budgetSnapshot),
373
- heartbeatAt: null,
374
- releasedAt: null,
375
- releaseReason: null,
376
- updatedAt: normalizedNow,
377
- },
378
- normalizedNow
379
- );
380
-
381
- if (assignmentIndex >= 0) {
382
- ledger.assignments[assignmentIndex] = nextRecord;
383
- } else {
384
- ledger.assignments.push(nextRecord);
385
- }
386
- updateQueueItem({
387
- queue,
388
- workItemId: normalizedWorkItemId,
389
- status: "ASSIGNED",
390
- assignedAgentIdentity: normalizedAgentIdentity,
391
- stage,
392
- runId,
393
- jiraIssueKey,
394
- nowIso: normalizedNow,
395
- });
396
-
397
- const [savedLedger, savedQueue] = await Promise.all([
398
- writeLedger(storage.ledgerPath, ledger, normalizedNow),
399
- writeQueue(storage.queuePath, queue, normalizedNow),
400
- ]);
401
-
402
- await appendEvent(storage.eventsPath, {
403
- timestamp: normalizedNow,
404
- eventType: "claim",
405
- workItemId: normalizedWorkItemId,
406
- agentIdentity: normalizedAgentIdentity,
407
- leaseTtlSeconds: normalizedTtl,
408
- leaseExpiresAt,
409
- stage: normalizeString(stage) || "triage",
410
- runId: normalizeString(runId) || null,
411
- jiraIssueKey: normalizeString(jiraIssueKey) || null,
412
- });
413
-
414
- return {
415
- ...storage,
416
- ledger: savedLedger,
417
- queue: savedQueue,
418
- assignment: nextRecord,
419
- };
420
- }
421
-
422
- export async function heartbeatAssignment({
423
- targetPath = ".",
424
- outputDir = "",
425
- workItemId,
426
- agentIdentity,
427
- leaseTtlSeconds = 1800,
428
- stage = "",
429
- runId = "",
430
- jiraIssueKey = "",
431
- budgetSnapshot = {},
432
- env,
433
- homeDir,
434
- nowIso = new Date().toISOString(),
435
- } = {}) {
436
- const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
437
- const normalizedWorkItemId = normalizeString(workItemId);
438
- if (!normalizedWorkItemId) {
439
- throw new Error("workItemId is required.");
440
- }
441
- const normalizedAgentIdentity = requireAgentIdentity(agentIdentity);
442
- const normalizedTtl = normalizePositiveInteger(leaseTtlSeconds, 1800);
443
- const storage = await resolveAssignmentLedgerStorage({
444
- targetPath,
445
- outputDir,
446
- env,
447
- homeDir,
448
- });
449
- const { ledger, queue } = await loadLedgerAndQueue(storage, normalizedNow);
450
-
451
- const assignmentIndex = findAssignmentIndex(ledger, normalizedWorkItemId);
452
- if (assignmentIndex < 0) {
453
- throw new Error(`No assignment exists for work item '${normalizedWorkItemId}'.`);
454
- }
455
- const existing = ledger.assignments[assignmentIndex];
456
- if (existing.assignedAgentIdentity !== normalizedAgentIdentity) {
457
- throw new Error(
458
- `Work item '${normalizedWorkItemId}' is assigned to '${existing.assignedAgentIdentity}', not '${normalizedAgentIdentity}'.`
459
- );
460
- }
461
-
462
- const leaseExpiresAt = toIsoAfterSeconds(normalizedNow, normalizedTtl);
463
- const next = normalizeAssignmentRecord(
464
- {
465
- ...existing,
466
- status: "IN_PROGRESS",
467
- leaseTtlSeconds: normalizedTtl,
468
- leaseExpiresAt,
469
- heartbeatAt: normalizedNow,
470
- stage: normalizeString(stage) || existing.stage,
471
- runId: normalizeString(runId) || existing.runId,
472
- jiraIssueKey: normalizeString(jiraIssueKey) || existing.jiraIssueKey,
473
- budgetSnapshot:
474
- Object.keys(normalizeMetadata(budgetSnapshot)).length > 0
475
- ? normalizeMetadata(budgetSnapshot)
476
- : existing.budgetSnapshot,
477
- updatedAt: normalizedNow,
478
- },
479
- normalizedNow
480
- );
481
- ledger.assignments[assignmentIndex] = next;
482
- updateQueueItem({
483
- queue,
484
- workItemId: normalizedWorkItemId,
485
- status: "IN_PROGRESS",
486
- assignedAgentIdentity: normalizedAgentIdentity,
487
- stage: next.stage,
488
- runId: next.runId,
489
- jiraIssueKey: next.jiraIssueKey,
490
- nowIso: normalizedNow,
491
- });
492
-
493
- const [savedLedger, savedQueue] = await Promise.all([
494
- writeLedger(storage.ledgerPath, ledger, normalizedNow),
495
- writeQueue(storage.queuePath, queue, normalizedNow),
496
- ]);
497
-
498
- await appendEvent(storage.eventsPath, {
499
- timestamp: normalizedNow,
500
- eventType: "heartbeat",
501
- workItemId: normalizedWorkItemId,
502
- agentIdentity: normalizedAgentIdentity,
503
- stage: next.stage,
504
- leaseExpiresAt,
505
- });
506
-
507
- return {
508
- ...storage,
509
- ledger: savedLedger,
510
- queue: savedQueue,
511
- assignment: next,
512
- };
513
- }
514
-
515
- export async function releaseAssignment({
516
- targetPath = ".",
517
- outputDir = "",
518
- workItemId,
519
- agentIdentity = "",
520
- status = "QUEUED",
521
- stage = "",
522
- runId = "",
523
- jiraIssueKey = "",
524
- reason = "",
525
- budgetSnapshot = {},
526
- env,
527
- homeDir,
528
- nowIso = new Date().toISOString(),
529
- } = {}) {
530
- const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
531
- const normalizedWorkItemId = normalizeString(workItemId);
532
- if (!normalizedWorkItemId) {
533
- throw new Error("workItemId is required.");
534
- }
535
- const normalizedStatus = normalizeReleaseTargetStatus(status);
536
- const normalizedAgentIdentity = normalizeString(agentIdentity) || null;
537
- const storage = await resolveAssignmentLedgerStorage({
538
- targetPath,
539
- outputDir,
540
- env,
541
- homeDir,
542
- });
543
- const { ledger, queue } = await loadLedgerAndQueue(storage, normalizedNow);
544
-
545
- const assignmentIndex = findAssignmentIndex(ledger, normalizedWorkItemId);
546
- if (assignmentIndex < 0) {
547
- throw new Error(`No assignment exists for work item '${normalizedWorkItemId}'.`);
548
- }
549
- const existing = ledger.assignments[assignmentIndex];
550
- if (
551
- normalizedAgentIdentity &&
552
- normalizeString(existing.assignedAgentIdentity) &&
553
- existing.assignedAgentIdentity !== normalizedAgentIdentity
554
- ) {
555
- throw new Error(
556
- `Work item '${normalizedWorkItemId}' is assigned to '${existing.assignedAgentIdentity}', not '${normalizedAgentIdentity}'.`
557
- );
558
- }
559
-
560
- const next = normalizeAssignmentRecord(
561
- {
562
- ...existing,
563
- status: normalizedStatus,
564
- stage: normalizeString(stage) || existing.stage,
565
- runId: normalizeString(runId) || existing.runId,
566
- jiraIssueKey: normalizeString(jiraIssueKey) || existing.jiraIssueKey,
567
- budgetSnapshot:
568
- Object.keys(normalizeMetadata(budgetSnapshot)).length > 0
569
- ? normalizeMetadata(budgetSnapshot)
570
- : existing.budgetSnapshot,
571
- releasedAt: normalizedNow,
572
- releaseReason: normalizeString(reason) || null,
573
- updatedAt: normalizedNow,
574
- },
575
- normalizedNow
576
- );
577
- ledger.assignments[assignmentIndex] = next;
578
- updateQueueItem({
579
- queue,
580
- workItemId: normalizedWorkItemId,
581
- status: normalizedStatus,
582
- assignedAgentIdentity: next.assignedAgentIdentity,
583
- stage: next.stage,
584
- runId: next.runId,
585
- jiraIssueKey: next.jiraIssueKey,
586
- nowIso: normalizedNow,
587
- });
588
-
589
- const [savedLedger, savedQueue] = await Promise.all([
590
- writeLedger(storage.ledgerPath, ledger, normalizedNow),
591
- writeQueue(storage.queuePath, queue, normalizedNow),
592
- ]);
593
-
594
- await appendEvent(storage.eventsPath, {
595
- timestamp: normalizedNow,
596
- eventType: "release",
597
- workItemId: normalizedWorkItemId,
598
- agentIdentity: next.assignedAgentIdentity,
599
- status: normalizedStatus,
600
- reason: next.releaseReason,
601
- });
602
-
603
- return {
604
- ...storage,
605
- ledger: savedLedger,
606
- queue: savedQueue,
607
- assignment: next,
608
- };
609
- }
610
-
611
- export async function reassignAssignment({
612
- targetPath = ".",
613
- outputDir = "",
614
- workItemId,
615
- fromAgentIdentity = "",
616
- toAgentIdentity,
617
- leaseTtlSeconds = 1800,
618
- stage = "triage",
619
- runId = "",
620
- jiraIssueKey = "",
621
- budgetSnapshot = {},
622
- env,
623
- homeDir,
624
- nowIso = new Date().toISOString(),
625
- } = {}) {
626
- const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
627
- const normalizedWorkItemId = normalizeString(workItemId);
628
- if (!normalizedWorkItemId) {
629
- throw new Error("workItemId is required.");
630
- }
631
- const normalizedToAgent = requireAgentIdentity(toAgentIdentity, "toAgentIdentity");
632
- const normalizedFromAgent = normalizeString(fromAgentIdentity) || null;
633
- const normalizedTtl = normalizePositiveInteger(leaseTtlSeconds, 1800);
634
- const storage = await resolveAssignmentLedgerStorage({
635
- targetPath,
636
- outputDir,
637
- env,
638
- homeDir,
639
- });
640
- const { ledger, queue } = await loadLedgerAndQueue(storage, normalizedNow);
641
-
642
- const assignmentIndex = findAssignmentIndex(ledger, normalizedWorkItemId);
643
- if (assignmentIndex < 0) {
644
- throw new Error(`No assignment exists for work item '${normalizedWorkItemId}'.`);
645
- }
646
- const existing = ledger.assignments[assignmentIndex];
647
- if (
648
- normalizedFromAgent &&
649
- normalizeString(existing.assignedAgentIdentity) &&
650
- existing.assignedAgentIdentity !== normalizedFromAgent
651
- ) {
652
- throw new Error(
653
- `Work item '${normalizedWorkItemId}' is assigned to '${existing.assignedAgentIdentity}', not '${normalizedFromAgent}'.`
654
- );
655
- }
656
-
657
- const leaseExpiresAt = toIsoAfterSeconds(normalizedNow, normalizedTtl);
658
- const next = normalizeAssignmentRecord(
659
- {
660
- ...existing,
661
- assignedAgentIdentity: normalizedToAgent,
662
- leasedAt: normalizedNow,
663
- leaseTtlSeconds: normalizedTtl,
664
- leaseExpiresAt,
665
- status: "CLAIMED",
666
- stage: normalizeString(stage) || existing.stage,
667
- runId: normalizeString(runId) || existing.runId,
668
- jiraIssueKey: normalizeString(jiraIssueKey) || existing.jiraIssueKey,
669
- budgetSnapshot:
670
- Object.keys(normalizeMetadata(budgetSnapshot)).length > 0
671
- ? normalizeMetadata(budgetSnapshot)
672
- : existing.budgetSnapshot,
673
- heartbeatAt: null,
674
- releasedAt: null,
675
- releaseReason: null,
676
- updatedAt: normalizedNow,
677
- },
678
- normalizedNow
679
- );
680
- ledger.assignments[assignmentIndex] = next;
681
- updateQueueItem({
682
- queue,
683
- workItemId: normalizedWorkItemId,
684
- status: "ASSIGNED",
685
- assignedAgentIdentity: normalizedToAgent,
686
- stage: next.stage,
687
- runId: next.runId,
688
- jiraIssueKey: next.jiraIssueKey,
689
- nowIso: normalizedNow,
690
- });
691
-
692
- const [savedLedger, savedQueue] = await Promise.all([
693
- writeLedger(storage.ledgerPath, ledger, normalizedNow),
694
- writeQueue(storage.queuePath, queue, normalizedNow),
695
- ]);
696
-
697
- await appendEvent(storage.eventsPath, {
698
- timestamp: normalizedNow,
699
- eventType: "reassign",
700
- workItemId: normalizedWorkItemId,
701
- fromAgentIdentity: existing.assignedAgentIdentity,
702
- toAgentIdentity: normalizedToAgent,
703
- leaseTtlSeconds: normalizedTtl,
704
- leaseExpiresAt,
705
- stage: next.stage,
706
- });
707
-
708
- return {
709
- ...storage,
710
- ledger: savedLedger,
711
- queue: savedQueue,
712
- assignment: next,
713
- };
714
- }
715
-
716
- export async function listAssignments({
717
- targetPath = ".",
718
- outputDir = "",
719
- statuses = [],
720
- agentIdentity = "",
721
- includeExpired = true,
722
- limit = 50,
723
- env,
724
- homeDir,
725
- nowIso = new Date().toISOString(),
726
- } = {}) {
727
- const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
728
- const normalizedLimit = normalizePositiveInteger(limit, 50);
729
- const normalizedAgent = normalizeString(agentIdentity);
730
- const statusFilter = parseStatusList(statuses);
731
- const storage = await resolveAssignmentLedgerStorage({
732
- targetPath,
733
- outputDir,
734
- env,
735
- homeDir,
736
- });
737
- const ledger = await loadLedger(storage.ledgerPath, normalizedNow);
738
- const records = ledger.assignments
739
- .map((record) => {
740
- const expired = isAssignmentExpired(record, normalizedNow);
741
- return {
742
- ...record,
743
- expired,
744
- };
745
- })
746
- .filter((record) => {
747
- if (statusFilter && !statusFilter.has(record.status)) {
748
- return false;
749
- }
750
- if (normalizedAgent && record.assignedAgentIdentity !== normalizedAgent) {
751
- return false;
752
- }
753
- if (!includeExpired && record.expired) {
754
- return false;
755
- }
756
- return true;
757
- })
758
- .sort((left, right) => {
759
- const leftEpoch = Date.parse(String(left.updatedAt || "")) || 0;
760
- const rightEpoch = Date.parse(String(right.updatedAt || "")) || 0;
761
- return rightEpoch - leftEpoch;
762
- });
763
-
764
- return {
765
- ...storage,
766
- totalCount: ledger.assignments.length,
767
- visibleCount: records.length,
768
- assignments: records.slice(0, normalizedLimit),
769
- };
770
- }
1
+ import fsp from "node:fs/promises";
2
+ import path from "node:path";
3
+
4
+ import { WORK_ITEM_STATUSES, resolveErrorDaemonStorage } from "./error-worker.js";
5
+
6
+ const LEDGER_SCHEMA_VERSION = "1.0.0";
7
+ const QUEUE_SCHEMA_VERSION = "1.0.0";
8
+
9
+ export const ASSIGNMENT_STATUSES = Object.freeze([
10
+ "QUEUED",
11
+ "CLAIMED",
12
+ "IN_PROGRESS",
13
+ "RELEASED",
14
+ "DONE",
15
+ "BLOCKED",
16
+ "SQUASHED",
17
+ ]);
18
+
19
+ const ASSIGNMENT_STATUS_SET = new Set(ASSIGNMENT_STATUSES);
20
+ const WORK_ITEM_STATUS_SET = new Set(WORK_ITEM_STATUSES);
21
+ const ACTIVE_ASSIGNMENT_STATUSES = new Set(["CLAIMED", "IN_PROGRESS"]);
22
+ const RELEASE_TARGET_STATUSES = new Set(["QUEUED", "DONE", "BLOCKED", "SQUASHED"]);
23
+
24
+ function normalizeString(value) {
25
+ return String(value || "").trim();
26
+ }
27
+
28
+ function normalizeIsoTimestamp(value, fallbackIso = new Date().toISOString()) {
29
+ const normalized = normalizeString(value);
30
+ if (!normalized) {
31
+ return fallbackIso;
32
+ }
33
+ const epoch = Date.parse(normalized);
34
+ if (!Number.isFinite(epoch)) {
35
+ return fallbackIso;
36
+ }
37
+ return new Date(epoch).toISOString();
38
+ }
39
+
40
+ function normalizePositiveInteger(value, fallbackValue = 1) {
41
+ if (value === undefined || value === null || normalizeString(value) === "") {
42
+ return fallbackValue;
43
+ }
44
+ const normalized = Number(value);
45
+ if (!Number.isFinite(normalized) || normalized <= 0) {
46
+ throw new Error("Value must be a positive integer.");
47
+ }
48
+ return Math.floor(normalized);
49
+ }
50
+
51
+ function normalizeMetadata(value) {
52
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
53
+ return {};
54
+ }
55
+ return { ...value };
56
+ }
57
+
58
+ function normalizeAssignmentStatus(value, fallbackValue = "QUEUED") {
59
+ const normalized = normalizeString(value).toUpperCase();
60
+ if (ASSIGNMENT_STATUS_SET.has(normalized)) {
61
+ return normalized;
62
+ }
63
+ return fallbackValue;
64
+ }
65
+
66
+ function normalizeWorkItemStatus(value, fallbackValue = "QUEUED") {
67
+ const normalized = normalizeString(value).toUpperCase();
68
+ if (WORK_ITEM_STATUS_SET.has(normalized)) {
69
+ return normalized;
70
+ }
71
+ return fallbackValue;
72
+ }
73
+
74
+ function toIsoAfterSeconds(nowIso, seconds) {
75
+ const baseEpoch = Date.parse(normalizeIsoTimestamp(nowIso, new Date().toISOString())) || Date.now();
76
+ return new Date(baseEpoch + seconds * 1000).toISOString();
77
+ }
78
+
79
+ function parseStatusList(statuses = []) {
80
+ if (!Array.isArray(statuses)) {
81
+ return null;
82
+ }
83
+ const normalized = statuses
84
+ .map((item) => normalizeString(item).toUpperCase())
85
+ .filter(Boolean)
86
+ .filter((item) => ASSIGNMENT_STATUS_SET.has(item));
87
+ if (normalized.length === 0) {
88
+ return null;
89
+ }
90
+ return new Set(normalized);
91
+ }
92
+
93
+ function createInitialLedger(nowIso = new Date().toISOString()) {
94
+ return {
95
+ schemaVersion: LEDGER_SCHEMA_VERSION,
96
+ generatedAt: normalizeIsoTimestamp(nowIso, nowIso),
97
+ assignments: [],
98
+ };
99
+ }
100
+
101
+ function createInitialQueue(nowIso = new Date().toISOString()) {
102
+ return {
103
+ schemaVersion: QUEUE_SCHEMA_VERSION,
104
+ generatedAt: normalizeIsoTimestamp(nowIso, nowIso),
105
+ items: [],
106
+ };
107
+ }
108
+
109
+ function normalizeAssignmentRecord(record = {}, nowIso = new Date().toISOString()) {
110
+ const updatedAt = normalizeIsoTimestamp(record.updatedAt, nowIso);
111
+ return {
112
+ sessionId: normalizeString(record.sessionId) || null,
113
+ workItemId: normalizeString(record.workItemId),
114
+ assignedAgentIdentity: normalizeString(record.assignedAgentIdentity) || null,
115
+ leasedAt: record.leasedAt ? normalizeIsoTimestamp(record.leasedAt, updatedAt) : null,
116
+ leaseTtlSeconds: Math.max(1, normalizePositiveInteger(record.leaseTtlSeconds, 1800)),
117
+ leaseExpiresAt: record.leaseExpiresAt ? normalizeIsoTimestamp(record.leaseExpiresAt, updatedAt) : null,
118
+ status: normalizeAssignmentStatus(record.status),
119
+ stage: normalizeString(record.stage) || "triage",
120
+ runId: normalizeString(record.runId) || null,
121
+ jiraIssueKey: normalizeString(record.jiraIssueKey) || null,
122
+ budgetSnapshot: normalizeMetadata(record.budgetSnapshot),
123
+ heartbeatAt: record.heartbeatAt ? normalizeIsoTimestamp(record.heartbeatAt, updatedAt) : null,
124
+ releasedAt: record.releasedAt ? normalizeIsoTimestamp(record.releasedAt, updatedAt) : null,
125
+ releaseReason: normalizeString(record.releaseReason) || null,
126
+ updatedAt,
127
+ };
128
+ }
129
+
130
+ function isAssignmentExpired(record = {}, nowIso = new Date().toISOString()) {
131
+ if (!record || !ACTIVE_ASSIGNMENT_STATUSES.has(normalizeAssignmentStatus(record.status))) {
132
+ return false;
133
+ }
134
+ const expiry = Date.parse(String(record.leaseExpiresAt || ""));
135
+ const now = Date.parse(normalizeIsoTimestamp(nowIso, new Date().toISOString()));
136
+ if (!Number.isFinite(expiry) || !Number.isFinite(now)) {
137
+ return false;
138
+ }
139
+ return expiry <= now;
140
+ }
141
+
142
+ function normalizeQueueItem(item = {}, nowIso = new Date().toISOString()) {
143
+ return {
144
+ ...item,
145
+ workItemId: normalizeString(item.workItemId),
146
+ status: normalizeWorkItemStatus(item.status),
147
+ updatedAt: normalizeIsoTimestamp(item.updatedAt, nowIso),
148
+ metadata: normalizeMetadata(item.metadata),
149
+ };
150
+ }
151
+
152
+ async function loadJsonFile(filePath, defaultFactory) {
153
+ try {
154
+ const raw = await fsp.readFile(filePath, "utf-8");
155
+ return JSON.parse(raw);
156
+ } catch (error) {
157
+ if (error && typeof error === "object" && error.code === "ENOENT") {
158
+ return defaultFactory();
159
+ }
160
+ throw error;
161
+ }
162
+ }
163
+
164
+ async function writeJsonFile(filePath, payload = {}) {
165
+ await fsp.mkdir(path.dirname(filePath), { recursive: true });
166
+ await fsp.writeFile(filePath, `${JSON.stringify(payload, null, 2)}\n`, "utf-8");
167
+ }
168
+
169
+ async function appendEvent(filePath, payload = {}) {
170
+ await fsp.mkdir(path.dirname(filePath), { recursive: true });
171
+ await fsp.appendFile(filePath, `${JSON.stringify(payload)}\n`, "utf-8");
172
+ }
173
+
174
+ async function loadLedger(ledgerPath, nowIso = new Date().toISOString()) {
175
+ const parsed = await loadJsonFile(ledgerPath, () => createInitialLedger(nowIso));
176
+ return {
177
+ schemaVersion: normalizeString(parsed.schemaVersion) || LEDGER_SCHEMA_VERSION,
178
+ generatedAt: normalizeIsoTimestamp(parsed.generatedAt, nowIso),
179
+ assignments: Array.isArray(parsed.assignments)
180
+ ? parsed.assignments
181
+ .map((record) => normalizeAssignmentRecord(record, nowIso))
182
+ .filter((record) => normalizeString(record.workItemId))
183
+ : [],
184
+ };
185
+ }
186
+
187
+ async function writeLedger(ledgerPath, ledger = {}, nowIso = new Date().toISOString()) {
188
+ const normalized = {
189
+ schemaVersion: LEDGER_SCHEMA_VERSION,
190
+ generatedAt: normalizeIsoTimestamp(nowIso, nowIso),
191
+ assignments: Array.isArray(ledger.assignments)
192
+ ? ledger.assignments
193
+ .map((record) => normalizeAssignmentRecord(record, nowIso))
194
+ .filter((record) => normalizeString(record.workItemId))
195
+ : [],
196
+ };
197
+ await writeJsonFile(ledgerPath, normalized);
198
+ return normalized;
199
+ }
200
+
201
+ async function loadQueue(queuePath, nowIso = new Date().toISOString()) {
202
+ const parsed = await loadJsonFile(queuePath, () => createInitialQueue(nowIso));
203
+ return {
204
+ schemaVersion: normalizeString(parsed.schemaVersion) || QUEUE_SCHEMA_VERSION,
205
+ generatedAt: normalizeIsoTimestamp(parsed.generatedAt, nowIso),
206
+ items: Array.isArray(parsed.items)
207
+ ? parsed.items.map((item) => normalizeQueueItem(item, nowIso)).filter((item) => item.workItemId)
208
+ : [],
209
+ };
210
+ }
211
+
212
+ async function writeQueue(queuePath, queue = {}, nowIso = new Date().toISOString()) {
213
+ const normalized = {
214
+ schemaVersion: QUEUE_SCHEMA_VERSION,
215
+ generatedAt: normalizeIsoTimestamp(nowIso, nowIso),
216
+ items: Array.isArray(queue.items)
217
+ ? queue.items.map((item) => normalizeQueueItem(item, nowIso)).filter((item) => item.workItemId)
218
+ : [],
219
+ };
220
+ await writeJsonFile(queuePath, normalized);
221
+ return normalized;
222
+ }
223
+
224
+ function getAssignmentStoragePaths(baseStorage = {}) {
225
+ return {
226
+ ...baseStorage,
227
+ ledgerPath: path.join(baseStorage.baseDir, "assignment-ledger.json"),
228
+ eventsPath: path.join(baseStorage.baseDir, "assignment-events.ndjson"),
229
+ };
230
+ }
231
+
232
+ async function loadLedgerAndQueue(storage, nowIso) {
233
+ const [ledger, queue] = await Promise.all([
234
+ loadLedger(storage.ledgerPath, nowIso),
235
+ loadQueue(storage.queuePath, nowIso),
236
+ ]);
237
+ return { ledger, queue };
238
+ }
239
+
240
+ function findQueueItem(queue = {}, workItemId = "") {
241
+ return queue.items.find((item) => item.workItemId === workItemId) || null;
242
+ }
243
+
244
+ function updateQueueItem({
245
+ queue,
246
+ workItemId,
247
+ status,
248
+ assignedAgentIdentity = null,
249
+ stage = "",
250
+ runId = null,
251
+ jiraIssueKey = null,
252
+ nowIso,
253
+ } = {}) {
254
+ const index = queue.items.findIndex((item) => item.workItemId === workItemId);
255
+ if (index < 0) {
256
+ throw new Error(`Work item '${workItemId}' was not found in daemon queue.`);
257
+ }
258
+ const existing = queue.items[index];
259
+ queue.items[index] = normalizeQueueItem(
260
+ {
261
+ ...existing,
262
+ status: normalizeWorkItemStatus(status, existing.status),
263
+ updatedAt: nowIso,
264
+ metadata: {
265
+ ...normalizeMetadata(existing.metadata),
266
+ assignedAgentIdentity: assignedAgentIdentity || null,
267
+ stage: normalizeString(stage) || null,
268
+ runId: normalizeString(runId) || null,
269
+ jiraIssueKey: normalizeString(jiraIssueKey) || null,
270
+ },
271
+ },
272
+ nowIso
273
+ );
274
+ return queue.items[index];
275
+ }
276
+
277
+ function findAssignmentIndex(ledger = {}, workItemId = "") {
278
+ return ledger.assignments.findIndex((record) => record.workItemId === workItemId);
279
+ }
280
+
281
+ function requireAgentIdentity(value, fieldName = "agentIdentity") {
282
+ const normalized = normalizeString(value);
283
+ if (!normalized) {
284
+ throw new Error(`${fieldName} is required.`);
285
+ }
286
+ return normalized;
287
+ }
288
+
289
+ function normalizeSessionId(value) {
290
+ const normalized = normalizeString(value);
291
+ return normalized || null;
292
+ }
293
+
294
+ function requireSessionId(value, fieldName = "sessionId") {
295
+ const normalized = normalizeString(value);
296
+ if (!normalized) {
297
+ throw new Error(`${fieldName} is required.`);
298
+ }
299
+ return normalized;
300
+ }
301
+
302
+ function assertSessionBinding(existingAssignment, expectedSessionId, workItemId) {
303
+ const normalizedExpected = normalizeSessionId(expectedSessionId);
304
+ if (!normalizedExpected) {
305
+ return;
306
+ }
307
+ const normalizedExisting = normalizeSessionId(existingAssignment?.sessionId);
308
+ if (!normalizedExisting || normalizedExisting === normalizedExpected) {
309
+ return;
310
+ }
311
+ throw new Error(
312
+ `Work item '${normalizeString(workItemId)}' is bound to session '${normalizedExisting}', not '${normalizedExpected}'.`
313
+ );
314
+ }
315
+
316
+ function normalizeReleaseTargetStatus(value) {
317
+ const normalized = normalizeString(value).toUpperCase();
318
+ if (!RELEASE_TARGET_STATUSES.has(normalized)) {
319
+ throw new Error(
320
+ `status must be one of: ${[...RELEASE_TARGET_STATUSES].join(", ")}.`
321
+ );
322
+ }
323
+ return normalized;
324
+ }
325
+
326
+ export async function resolveAssignmentLedgerStorage({
327
+ targetPath = ".",
328
+ outputDir = "",
329
+ env,
330
+ homeDir,
331
+ } = {}) {
332
+ const daemonStorage = await resolveErrorDaemonStorage({
333
+ targetPath,
334
+ outputDir,
335
+ env,
336
+ homeDir,
337
+ });
338
+ return getAssignmentStoragePaths(daemonStorage);
339
+ }
340
+
341
+ export async function claimAssignment({
342
+ targetPath = ".",
343
+ outputDir = "",
344
+ sessionId = "",
345
+ workItemId,
346
+ agentIdentity,
347
+ leaseTtlSeconds = 1800,
348
+ stage = "triage",
349
+ runId = "",
350
+ jiraIssueKey = "",
351
+ budgetSnapshot = {},
352
+ env,
353
+ homeDir,
354
+ nowIso = new Date().toISOString(),
355
+ } = {}) {
356
+ const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
357
+ const normalizedWorkItemId = normalizeString(workItemId);
358
+ if (!normalizedWorkItemId) {
359
+ throw new Error("workItemId is required.");
360
+ }
361
+ const normalizedSessionId = normalizeSessionId(sessionId);
362
+ const normalizedAgentIdentity = requireAgentIdentity(agentIdentity);
363
+ const normalizedTtl = normalizePositiveInteger(leaseTtlSeconds, 1800);
364
+ const storage = await resolveAssignmentLedgerStorage({
365
+ targetPath,
366
+ outputDir,
367
+ env,
368
+ homeDir,
369
+ });
370
+ const { ledger, queue } = await loadLedgerAndQueue(storage, normalizedNow);
371
+
372
+ const queueItem = findQueueItem(queue, normalizedWorkItemId);
373
+ if (!queueItem) {
374
+ throw new Error(`Work item '${normalizedWorkItemId}' was not found in daemon queue.`);
375
+ }
376
+
377
+ const assignmentIndex = findAssignmentIndex(ledger, normalizedWorkItemId);
378
+ const existingAssignment = assignmentIndex >= 0 ? ledger.assignments[assignmentIndex] : null;
379
+ assertSessionBinding(existingAssignment, normalizedSessionId, normalizedWorkItemId);
380
+ if (
381
+ existingAssignment &&
382
+ ACTIVE_ASSIGNMENT_STATUSES.has(existingAssignment.status) &&
383
+ !isAssignmentExpired(existingAssignment, normalizedNow) &&
384
+ existingAssignment.assignedAgentIdentity !== normalizedAgentIdentity
385
+ ) {
386
+ throw new Error(
387
+ `Work item '${normalizedWorkItemId}' is currently leased by '${existingAssignment.assignedAgentIdentity}'.`
388
+ );
389
+ }
390
+
391
+ const leaseExpiresAt = toIsoAfterSeconds(normalizedNow, normalizedTtl);
392
+ const nextRecord = normalizeAssignmentRecord(
393
+ {
394
+ workItemId: normalizedWorkItemId,
395
+ sessionId: normalizedSessionId || normalizeSessionId(existingAssignment?.sessionId),
396
+ assignedAgentIdentity: normalizedAgentIdentity,
397
+ leasedAt: normalizedNow,
398
+ leaseTtlSeconds: normalizedTtl,
399
+ leaseExpiresAt,
400
+ status: "CLAIMED",
401
+ stage,
402
+ runId,
403
+ jiraIssueKey,
404
+ budgetSnapshot: normalizeMetadata(budgetSnapshot),
405
+ heartbeatAt: null,
406
+ releasedAt: null,
407
+ releaseReason: null,
408
+ updatedAt: normalizedNow,
409
+ },
410
+ normalizedNow
411
+ );
412
+
413
+ if (assignmentIndex >= 0) {
414
+ ledger.assignments[assignmentIndex] = nextRecord;
415
+ } else {
416
+ ledger.assignments.push(nextRecord);
417
+ }
418
+ updateQueueItem({
419
+ queue,
420
+ workItemId: normalizedWorkItemId,
421
+ status: "ASSIGNED",
422
+ assignedAgentIdentity: normalizedAgentIdentity,
423
+ stage,
424
+ runId,
425
+ jiraIssueKey,
426
+ nowIso: normalizedNow,
427
+ });
428
+
429
+ const [savedLedger, savedQueue] = await Promise.all([
430
+ writeLedger(storage.ledgerPath, ledger, normalizedNow),
431
+ writeQueue(storage.queuePath, queue, normalizedNow),
432
+ ]);
433
+
434
+ await appendEvent(storage.eventsPath, {
435
+ timestamp: normalizedNow,
436
+ eventType: "claim",
437
+ sessionId: nextRecord.sessionId,
438
+ workItemId: normalizedWorkItemId,
439
+ agentIdentity: normalizedAgentIdentity,
440
+ leaseTtlSeconds: normalizedTtl,
441
+ leaseExpiresAt,
442
+ stage: normalizeString(stage) || "triage",
443
+ runId: normalizeString(runId) || null,
444
+ jiraIssueKey: normalizeString(jiraIssueKey) || null,
445
+ });
446
+
447
+ return {
448
+ ...storage,
449
+ ledger: savedLedger,
450
+ queue: savedQueue,
451
+ assignment: nextRecord,
452
+ };
453
+ }
454
+
455
+ export async function heartbeatAssignment({
456
+ targetPath = ".",
457
+ outputDir = "",
458
+ sessionId = "",
459
+ workItemId,
460
+ agentIdentity,
461
+ leaseTtlSeconds = 1800,
462
+ stage = "",
463
+ runId = "",
464
+ jiraIssueKey = "",
465
+ budgetSnapshot = {},
466
+ env,
467
+ homeDir,
468
+ nowIso = new Date().toISOString(),
469
+ } = {}) {
470
+ const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
471
+ const normalizedWorkItemId = normalizeString(workItemId);
472
+ if (!normalizedWorkItemId) {
473
+ throw new Error("workItemId is required.");
474
+ }
475
+ const normalizedSessionId = normalizeSessionId(sessionId);
476
+ const normalizedAgentIdentity = requireAgentIdentity(agentIdentity);
477
+ const normalizedTtl = normalizePositiveInteger(leaseTtlSeconds, 1800);
478
+ const storage = await resolveAssignmentLedgerStorage({
479
+ targetPath,
480
+ outputDir,
481
+ env,
482
+ homeDir,
483
+ });
484
+ const { ledger, queue } = await loadLedgerAndQueue(storage, normalizedNow);
485
+
486
+ const assignmentIndex = findAssignmentIndex(ledger, normalizedWorkItemId);
487
+ if (assignmentIndex < 0) {
488
+ throw new Error(`No assignment exists for work item '${normalizedWorkItemId}'.`);
489
+ }
490
+ const existing = ledger.assignments[assignmentIndex];
491
+ if (existing.assignedAgentIdentity !== normalizedAgentIdentity) {
492
+ throw new Error(
493
+ `Work item '${normalizedWorkItemId}' is assigned to '${existing.assignedAgentIdentity}', not '${normalizedAgentIdentity}'.`
494
+ );
495
+ }
496
+ assertSessionBinding(existing, normalizedSessionId, normalizedWorkItemId);
497
+
498
+ const leaseExpiresAt = toIsoAfterSeconds(normalizedNow, normalizedTtl);
499
+ const next = normalizeAssignmentRecord(
500
+ {
501
+ ...existing,
502
+ sessionId: normalizedSessionId || normalizeSessionId(existing.sessionId),
503
+ status: "IN_PROGRESS",
504
+ leaseTtlSeconds: normalizedTtl,
505
+ leaseExpiresAt,
506
+ heartbeatAt: normalizedNow,
507
+ stage: normalizeString(stage) || existing.stage,
508
+ runId: normalizeString(runId) || existing.runId,
509
+ jiraIssueKey: normalizeString(jiraIssueKey) || existing.jiraIssueKey,
510
+ budgetSnapshot:
511
+ Object.keys(normalizeMetadata(budgetSnapshot)).length > 0
512
+ ? normalizeMetadata(budgetSnapshot)
513
+ : existing.budgetSnapshot,
514
+ updatedAt: normalizedNow,
515
+ },
516
+ normalizedNow
517
+ );
518
+ ledger.assignments[assignmentIndex] = next;
519
+ updateQueueItem({
520
+ queue,
521
+ workItemId: normalizedWorkItemId,
522
+ status: "IN_PROGRESS",
523
+ assignedAgentIdentity: normalizedAgentIdentity,
524
+ stage: next.stage,
525
+ runId: next.runId,
526
+ jiraIssueKey: next.jiraIssueKey,
527
+ nowIso: normalizedNow,
528
+ });
529
+
530
+ const [savedLedger, savedQueue] = await Promise.all([
531
+ writeLedger(storage.ledgerPath, ledger, normalizedNow),
532
+ writeQueue(storage.queuePath, queue, normalizedNow),
533
+ ]);
534
+
535
+ await appendEvent(storage.eventsPath, {
536
+ timestamp: normalizedNow,
537
+ eventType: "heartbeat",
538
+ sessionId: next.sessionId,
539
+ workItemId: normalizedWorkItemId,
540
+ agentIdentity: normalizedAgentIdentity,
541
+ stage: next.stage,
542
+ leaseExpiresAt,
543
+ });
544
+
545
+ return {
546
+ ...storage,
547
+ ledger: savedLedger,
548
+ queue: savedQueue,
549
+ assignment: next,
550
+ };
551
+ }
552
+
553
+ export async function releaseAssignment({
554
+ targetPath = ".",
555
+ outputDir = "",
556
+ sessionId = "",
557
+ workItemId,
558
+ agentIdentity = "",
559
+ status = "QUEUED",
560
+ stage = "",
561
+ runId = "",
562
+ jiraIssueKey = "",
563
+ reason = "",
564
+ budgetSnapshot = {},
565
+ env,
566
+ homeDir,
567
+ nowIso = new Date().toISOString(),
568
+ } = {}) {
569
+ const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
570
+ const normalizedWorkItemId = normalizeString(workItemId);
571
+ if (!normalizedWorkItemId) {
572
+ throw new Error("workItemId is required.");
573
+ }
574
+ const normalizedStatus = normalizeReleaseTargetStatus(status);
575
+ const normalizedAgentIdentity = normalizeString(agentIdentity) || null;
576
+ const normalizedSessionId = normalizeSessionId(sessionId);
577
+ const storage = await resolveAssignmentLedgerStorage({
578
+ targetPath,
579
+ outputDir,
580
+ env,
581
+ homeDir,
582
+ });
583
+ const { ledger, queue } = await loadLedgerAndQueue(storage, normalizedNow);
584
+
585
+ const assignmentIndex = findAssignmentIndex(ledger, normalizedWorkItemId);
586
+ if (assignmentIndex < 0) {
587
+ throw new Error(`No assignment exists for work item '${normalizedWorkItemId}'.`);
588
+ }
589
+ const existing = ledger.assignments[assignmentIndex];
590
+ assertSessionBinding(existing, normalizedSessionId, normalizedWorkItemId);
591
+ if (
592
+ normalizedAgentIdentity &&
593
+ normalizeString(existing.assignedAgentIdentity) &&
594
+ existing.assignedAgentIdentity !== normalizedAgentIdentity
595
+ ) {
596
+ throw new Error(
597
+ `Work item '${normalizedWorkItemId}' is assigned to '${existing.assignedAgentIdentity}', not '${normalizedAgentIdentity}'.`
598
+ );
599
+ }
600
+
601
+ const next = normalizeAssignmentRecord(
602
+ {
603
+ ...existing,
604
+ sessionId: normalizedSessionId || normalizeSessionId(existing.sessionId),
605
+ status: normalizedStatus,
606
+ stage: normalizeString(stage) || existing.stage,
607
+ runId: normalizeString(runId) || existing.runId,
608
+ jiraIssueKey: normalizeString(jiraIssueKey) || existing.jiraIssueKey,
609
+ budgetSnapshot:
610
+ Object.keys(normalizeMetadata(budgetSnapshot)).length > 0
611
+ ? normalizeMetadata(budgetSnapshot)
612
+ : existing.budgetSnapshot,
613
+ releasedAt: normalizedNow,
614
+ releaseReason: normalizeString(reason) || null,
615
+ updatedAt: normalizedNow,
616
+ },
617
+ normalizedNow
618
+ );
619
+ ledger.assignments[assignmentIndex] = next;
620
+ updateQueueItem({
621
+ queue,
622
+ workItemId: normalizedWorkItemId,
623
+ status: normalizedStatus,
624
+ assignedAgentIdentity: next.assignedAgentIdentity,
625
+ stage: next.stage,
626
+ runId: next.runId,
627
+ jiraIssueKey: next.jiraIssueKey,
628
+ nowIso: normalizedNow,
629
+ });
630
+
631
+ const [savedLedger, savedQueue] = await Promise.all([
632
+ writeLedger(storage.ledgerPath, ledger, normalizedNow),
633
+ writeQueue(storage.queuePath, queue, normalizedNow),
634
+ ]);
635
+
636
+ await appendEvent(storage.eventsPath, {
637
+ timestamp: normalizedNow,
638
+ eventType: "release",
639
+ sessionId: next.sessionId,
640
+ workItemId: normalizedWorkItemId,
641
+ agentIdentity: next.assignedAgentIdentity,
642
+ status: normalizedStatus,
643
+ reason: next.releaseReason,
644
+ });
645
+
646
+ return {
647
+ ...storage,
648
+ ledger: savedLedger,
649
+ queue: savedQueue,
650
+ assignment: next,
651
+ };
652
+ }
653
+
654
+ export async function reassignAssignment({
655
+ targetPath = ".",
656
+ outputDir = "",
657
+ sessionId = "",
658
+ workItemId,
659
+ fromAgentIdentity = "",
660
+ toAgentIdentity,
661
+ leaseTtlSeconds = 1800,
662
+ stage = "triage",
663
+ runId = "",
664
+ jiraIssueKey = "",
665
+ budgetSnapshot = {},
666
+ env,
667
+ homeDir,
668
+ nowIso = new Date().toISOString(),
669
+ } = {}) {
670
+ const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
671
+ const normalizedWorkItemId = normalizeString(workItemId);
672
+ if (!normalizedWorkItemId) {
673
+ throw new Error("workItemId is required.");
674
+ }
675
+ const normalizedSessionId = normalizeSessionId(sessionId);
676
+ const normalizedToAgent = requireAgentIdentity(toAgentIdentity, "toAgentIdentity");
677
+ const normalizedFromAgent = normalizeString(fromAgentIdentity) || null;
678
+ const normalizedTtl = normalizePositiveInteger(leaseTtlSeconds, 1800);
679
+ const storage = await resolveAssignmentLedgerStorage({
680
+ targetPath,
681
+ outputDir,
682
+ env,
683
+ homeDir,
684
+ });
685
+ const { ledger, queue } = await loadLedgerAndQueue(storage, normalizedNow);
686
+
687
+ const assignmentIndex = findAssignmentIndex(ledger, normalizedWorkItemId);
688
+ if (assignmentIndex < 0) {
689
+ throw new Error(`No assignment exists for work item '${normalizedWorkItemId}'.`);
690
+ }
691
+ const existing = ledger.assignments[assignmentIndex];
692
+ assertSessionBinding(existing, normalizedSessionId, normalizedWorkItemId);
693
+ if (
694
+ normalizedFromAgent &&
695
+ normalizeString(existing.assignedAgentIdentity) &&
696
+ existing.assignedAgentIdentity !== normalizedFromAgent
697
+ ) {
698
+ throw new Error(
699
+ `Work item '${normalizedWorkItemId}' is assigned to '${existing.assignedAgentIdentity}', not '${normalizedFromAgent}'.`
700
+ );
701
+ }
702
+
703
+ const leaseExpiresAt = toIsoAfterSeconds(normalizedNow, normalizedTtl);
704
+ const next = normalizeAssignmentRecord(
705
+ {
706
+ ...existing,
707
+ sessionId: normalizedSessionId || normalizeSessionId(existing.sessionId),
708
+ assignedAgentIdentity: normalizedToAgent,
709
+ leasedAt: normalizedNow,
710
+ leaseTtlSeconds: normalizedTtl,
711
+ leaseExpiresAt,
712
+ status: "CLAIMED",
713
+ stage: normalizeString(stage) || existing.stage,
714
+ runId: normalizeString(runId) || existing.runId,
715
+ jiraIssueKey: normalizeString(jiraIssueKey) || existing.jiraIssueKey,
716
+ budgetSnapshot:
717
+ Object.keys(normalizeMetadata(budgetSnapshot)).length > 0
718
+ ? normalizeMetadata(budgetSnapshot)
719
+ : existing.budgetSnapshot,
720
+ heartbeatAt: null,
721
+ releasedAt: null,
722
+ releaseReason: null,
723
+ updatedAt: normalizedNow,
724
+ },
725
+ normalizedNow
726
+ );
727
+ ledger.assignments[assignmentIndex] = next;
728
+ updateQueueItem({
729
+ queue,
730
+ workItemId: normalizedWorkItemId,
731
+ status: "ASSIGNED",
732
+ assignedAgentIdentity: normalizedToAgent,
733
+ stage: next.stage,
734
+ runId: next.runId,
735
+ jiraIssueKey: next.jiraIssueKey,
736
+ nowIso: normalizedNow,
737
+ });
738
+
739
+ const [savedLedger, savedQueue] = await Promise.all([
740
+ writeLedger(storage.ledgerPath, ledger, normalizedNow),
741
+ writeQueue(storage.queuePath, queue, normalizedNow),
742
+ ]);
743
+
744
+ await appendEvent(storage.eventsPath, {
745
+ timestamp: normalizedNow,
746
+ eventType: "reassign",
747
+ sessionId: next.sessionId,
748
+ workItemId: normalizedWorkItemId,
749
+ fromAgentIdentity: existing.assignedAgentIdentity,
750
+ toAgentIdentity: normalizedToAgent,
751
+ leaseTtlSeconds: normalizedTtl,
752
+ leaseExpiresAt,
753
+ stage: next.stage,
754
+ });
755
+
756
+ return {
757
+ ...storage,
758
+ ledger: savedLedger,
759
+ queue: savedQueue,
760
+ assignment: next,
761
+ };
762
+ }
763
+
764
+ export async function listAssignments({
765
+ targetPath = ".",
766
+ outputDir = "",
767
+ sessionId = "",
768
+ statuses = [],
769
+ agentIdentity = "",
770
+ includeExpired = true,
771
+ limit = 50,
772
+ env,
773
+ homeDir,
774
+ nowIso = new Date().toISOString(),
775
+ } = {}) {
776
+ const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
777
+ const normalizedLimit = normalizePositiveInteger(limit, 50);
778
+ const normalizedAgent = normalizeString(agentIdentity);
779
+ const normalizedSessionId = normalizeSessionId(sessionId);
780
+ const statusFilter = parseStatusList(statuses);
781
+ const storage = await resolveAssignmentLedgerStorage({
782
+ targetPath,
783
+ outputDir,
784
+ env,
785
+ homeDir,
786
+ });
787
+ const ledger = await loadLedger(storage.ledgerPath, normalizedNow);
788
+ const records = ledger.assignments
789
+ .map((record) => {
790
+ const expired = isAssignmentExpired(record, normalizedNow);
791
+ return {
792
+ ...record,
793
+ expired,
794
+ };
795
+ })
796
+ .filter((record) => {
797
+ if (statusFilter && !statusFilter.has(record.status)) {
798
+ return false;
799
+ }
800
+ if (normalizedAgent && record.assignedAgentIdentity !== normalizedAgent) {
801
+ return false;
802
+ }
803
+ if (normalizedSessionId && record.sessionId !== normalizedSessionId) {
804
+ return false;
805
+ }
806
+ if (!includeExpired && record.expired) {
807
+ return false;
808
+ }
809
+ return true;
810
+ })
811
+ .sort((left, right) => {
812
+ const leftEpoch = Date.parse(String(left.updatedAt || "")) || 0;
813
+ const rightEpoch = Date.parse(String(right.updatedAt || "")) || 0;
814
+ return rightEpoch - leftEpoch;
815
+ });
816
+
817
+ return {
818
+ ...storage,
819
+ totalCount: ledger.assignments.length,
820
+ visibleCount: records.length,
821
+ assignments: records.slice(0, normalizedLimit),
822
+ };
823
+ }
824
+
825
+ function normalizeLeaseTtlMs(value, fallbackValue = 1_800_000) {
826
+ return normalizePositiveInteger(value, fallbackValue);
827
+ }
828
+
829
+ export async function leaseWorkItem({
830
+ targetPath = ".",
831
+ outputDir = "",
832
+ sessionId,
833
+ workItemId,
834
+ agentIdentity,
835
+ leaseTtlMs = 1_800_000,
836
+ stage = "triage",
837
+ runId = "",
838
+ jiraIssueKey = "",
839
+ budgetSnapshot = {},
840
+ env,
841
+ homeDir,
842
+ nowIso = new Date().toISOString(),
843
+ } = {}) {
844
+ const normalizedSessionId = requireSessionId(sessionId);
845
+ const leaseTtlSeconds = Math.max(1, Math.ceil(normalizeLeaseTtlMs(leaseTtlMs) / 1000));
846
+ return claimAssignment({
847
+ targetPath,
848
+ outputDir,
849
+ sessionId: normalizedSessionId,
850
+ workItemId,
851
+ agentIdentity,
852
+ leaseTtlSeconds,
853
+ stage,
854
+ runId,
855
+ jiraIssueKey,
856
+ budgetSnapshot,
857
+ env,
858
+ homeDir,
859
+ nowIso,
860
+ });
861
+ }
862
+
863
+ export async function heartbeatLease({
864
+ targetPath = ".",
865
+ outputDir = "",
866
+ sessionId,
867
+ workItemId,
868
+ agentIdentity,
869
+ leaseTtlMs = 1_800_000,
870
+ stage = "",
871
+ runId = "",
872
+ jiraIssueKey = "",
873
+ budgetSnapshot = {},
874
+ env,
875
+ homeDir,
876
+ nowIso = new Date().toISOString(),
877
+ } = {}) {
878
+ const normalizedSessionId = requireSessionId(sessionId);
879
+ const leaseTtlSeconds = Math.max(1, Math.ceil(normalizeLeaseTtlMs(leaseTtlMs) / 1000));
880
+ return heartbeatAssignment({
881
+ targetPath,
882
+ outputDir,
883
+ sessionId: normalizedSessionId,
884
+ workItemId,
885
+ agentIdentity,
886
+ leaseTtlSeconds,
887
+ stage,
888
+ runId,
889
+ jiraIssueKey,
890
+ budgetSnapshot,
891
+ env,
892
+ homeDir,
893
+ nowIso,
894
+ });
895
+ }
896
+
897
+ export async function releaseLease({
898
+ targetPath = ".",
899
+ outputDir = "",
900
+ sessionId,
901
+ workItemId,
902
+ agentIdentity = "",
903
+ status = "QUEUED",
904
+ stage = "",
905
+ runId = "",
906
+ jiraIssueKey = "",
907
+ reason = "",
908
+ budgetSnapshot = {},
909
+ env,
910
+ homeDir,
911
+ nowIso = new Date().toISOString(),
912
+ } = {}) {
913
+ const normalizedSessionId = requireSessionId(sessionId);
914
+ return releaseAssignment({
915
+ targetPath,
916
+ outputDir,
917
+ sessionId: normalizedSessionId,
918
+ workItemId,
919
+ agentIdentity,
920
+ status,
921
+ stage,
922
+ runId,
923
+ jiraIssueKey,
924
+ reason,
925
+ budgetSnapshot,
926
+ env,
927
+ homeDir,
928
+ nowIso,
929
+ });
930
+ }
931
+
932
+ export async function reassignLease({
933
+ targetPath = ".",
934
+ outputDir = "",
935
+ sessionId,
936
+ workItemId,
937
+ from = "",
938
+ to,
939
+ leaseTtlMs = 1_800_000,
940
+ stage = "triage",
941
+ runId = "",
942
+ jiraIssueKey = "",
943
+ budgetSnapshot = {},
944
+ env,
945
+ homeDir,
946
+ nowIso = new Date().toISOString(),
947
+ } = {}) {
948
+ const normalizedSessionId = requireSessionId(sessionId);
949
+ const leaseTtlSeconds = Math.max(1, Math.ceil(normalizeLeaseTtlMs(leaseTtlMs) / 1000));
950
+ return reassignAssignment({
951
+ targetPath,
952
+ outputDir,
953
+ sessionId: normalizedSessionId,
954
+ workItemId,
955
+ fromAgentIdentity: from,
956
+ toAgentIdentity: to,
957
+ leaseTtlSeconds,
958
+ stage,
959
+ runId,
960
+ jiraIssueKey,
961
+ budgetSnapshot,
962
+ env,
963
+ homeDir,
964
+ nowIso,
965
+ });
966
+ }