sentinelayer-cli 0.1.2 → 0.4.4

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 (129) hide show
  1. package/README.md +998 -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 +63 -54
  6. package/src/agents/jules/config/definition.js +209 -209
  7. package/src/agents/jules/config/system-prompt.js +175 -175
  8. package/src/agents/jules/error-intake.js +51 -51
  9. package/src/agents/jules/fix-cycle.js +377 -377
  10. package/src/agents/jules/loop.js +367 -367
  11. package/src/agents/jules/pulse.js +327 -319
  12. package/src/agents/jules/stream.js +186 -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 +308 -308
  18. package/src/agents/jules/tools/auth-audit.js +557 -222
  19. package/src/agents/jules/tools/dispatch.js +327 -327
  20. package/src/agents/jules/tools/file-edit.js +180 -180
  21. package/src/agents/jules/tools/file-read.js +100 -100
  22. package/src/agents/jules/tools/frontend-analyze.js +570 -570
  23. package/src/agents/jules/tools/glob.js +168 -168
  24. package/src/agents/jules/tools/grep.js +228 -228
  25. package/src/agents/jules/tools/index.js +29 -29
  26. package/src/agents/jules/tools/path-guards.js +161 -161
  27. package/src/agents/jules/tools/runtime-audit.js +503 -493
  28. package/src/agents/jules/tools/shell.js +383 -383
  29. package/src/agents/jules/tools/url-policy.js +100 -0
  30. package/src/ai/aidenid.js +972 -945
  31. package/src/ai/client.js +508 -508
  32. package/src/ai/domain-target-store.js +268 -268
  33. package/src/ai/identity-store.js +270 -270
  34. package/src/ai/site-store.js +145 -145
  35. package/src/audit/agents/architecture.js +180 -180
  36. package/src/audit/agents/compliance.js +179 -179
  37. package/src/audit/agents/documentation.js +165 -165
  38. package/src/audit/agents/performance.js +145 -145
  39. package/src/audit/agents/security.js +215 -215
  40. package/src/audit/agents/testing.js +172 -172
  41. package/src/audit/orchestrator.js +557 -557
  42. package/src/audit/package.js +204 -204
  43. package/src/audit/registry.js +284 -284
  44. package/src/audit/replay.js +103 -103
  45. package/src/auth/gate.js +45 -11
  46. package/src/auth/http.js +270 -113
  47. package/src/auth/service.js +891 -848
  48. package/src/auth/session-store.js +359 -345
  49. package/src/cli.js +252 -252
  50. package/src/commands/ai/identity-lifecycle.js +1338 -1337
  51. package/src/commands/ai/provision-governance.js +1272 -1246
  52. package/src/commands/ai/shared.js +147 -147
  53. package/src/commands/ai.js +11 -11
  54. package/src/commands/apply.js +12 -12
  55. package/src/commands/audit.js +1166 -1166
  56. package/src/commands/auth.js +375 -366
  57. package/src/commands/chat.js +191 -191
  58. package/src/commands/config.js +184 -184
  59. package/src/commands/cost.js +311 -311
  60. package/src/commands/daemon/core.js +850 -850
  61. package/src/commands/daemon/extended.js +1048 -1048
  62. package/src/commands/daemon/shared.js +213 -213
  63. package/src/commands/daemon.js +11 -11
  64. package/src/commands/guide.js +174 -174
  65. package/src/commands/ingest.js +58 -58
  66. package/src/commands/init.js +55 -55
  67. package/src/commands/legacy-args.js +10 -10
  68. package/src/commands/mcp.js +461 -404
  69. package/src/commands/omargate.js +15 -15
  70. package/src/commands/persona.js +20 -20
  71. package/src/commands/plugin.js +260 -260
  72. package/src/commands/policy.js +132 -132
  73. package/src/commands/prompt.js +238 -238
  74. package/src/commands/review.js +704 -704
  75. package/src/commands/scan.js +866 -788
  76. package/src/commands/spec.js +716 -716
  77. package/src/commands/swarm.js +651 -651
  78. package/src/commands/telemetry.js +202 -202
  79. package/src/commands/watch.js +510 -510
  80. package/src/config/agent-dictionary.js +182 -182
  81. package/src/config/io.js +56 -56
  82. package/src/config/paths.js +18 -18
  83. package/src/config/schema.js +55 -55
  84. package/src/config/service.js +184 -184
  85. package/src/cost/budget.js +235 -235
  86. package/src/cost/history.js +188 -188
  87. package/src/cost/tracker.js +171 -171
  88. package/src/daemon/artifact-lineage.js +534 -534
  89. package/src/daemon/assignment-ledger.js +770 -770
  90. package/src/daemon/ast-parser-layer.js +258 -258
  91. package/src/daemon/budget-governor.js +633 -633
  92. package/src/daemon/callgraph-overlay.js +646 -646
  93. package/src/daemon/error-worker.js +626 -626
  94. package/src/daemon/hybrid-mapper.js +929 -929
  95. package/src/daemon/jira-lifecycle.js +632 -632
  96. package/src/daemon/operator-control.js +657 -657
  97. package/src/daemon/reliability-lane.js +471 -471
  98. package/src/daemon/watchdog.js +971 -971
  99. package/src/guide/generator.js +316 -316
  100. package/src/ingest/engine.js +918 -918
  101. package/src/legacy-cli.js +2592 -2435
  102. package/src/mcp/registry.js +695 -695
  103. package/src/memory/blackboard.js +301 -301
  104. package/src/memory/retrieval.js +581 -581
  105. package/src/plugin/manifest.js +553 -553
  106. package/src/policy/packs.js +144 -144
  107. package/src/prompt/generator.js +118 -106
  108. package/src/review/ai-review.js +669 -669
  109. package/src/review/local-review.js +1295 -1284
  110. package/src/review/replay.js +235 -235
  111. package/src/review/report.js +664 -664
  112. package/src/review/spec-binding.js +487 -487
  113. package/src/scaffold/generator.js +67 -0
  114. package/src/scaffold/templates.js +150 -0
  115. package/src/scan/generator.js +418 -351
  116. package/src/scan/gh-secrets.js +107 -0
  117. package/src/spec/generator.js +519 -519
  118. package/src/spec/regenerate.js +237 -237
  119. package/src/spec/templates.js +91 -91
  120. package/src/swarm/dashboard.js +247 -247
  121. package/src/swarm/factory.js +363 -363
  122. package/src/swarm/pentest.js +934 -934
  123. package/src/swarm/registry.js +419 -419
  124. package/src/swarm/report.js +158 -158
  125. package/src/swarm/runtime.js +576 -576
  126. package/src/swarm/scenario-dsl.js +272 -272
  127. package/src/telemetry/ledger.js +302 -302
  128. package/src/telemetry/sync.js +107 -61
  129. package/src/ui/markdown.js +220 -220
@@ -1,770 +1,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
- 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
+ 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
+ }