sentinelayer-cli 0.4.4 → 0.6.2

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 (149) hide show
  1. package/README.md +996 -998
  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 -63
  6. package/src/agents/jules/config/definition.js +160 -209
  7. package/src/agents/jules/config/system-prompt.js +182 -175
  8. package/src/agents/jules/error-intake.js +51 -51
  9. package/src/agents/jules/fix-cycle.js +17 -377
  10. package/src/agents/jules/loop.js +450 -367
  11. package/src/agents/jules/pulse.js +10 -327
  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 +309 -308
  18. package/src/agents/jules/tools/aidenid-email.js +189 -0
  19. package/src/agents/jules/tools/auth-audit.js +1691 -557
  20. package/src/agents/jules/tools/dispatch.js +335 -327
  21. package/src/agents/jules/tools/file-edit.js +2 -180
  22. package/src/agents/jules/tools/file-read.js +2 -100
  23. package/src/agents/jules/tools/frontend-analyze.js +570 -570
  24. package/src/agents/jules/tools/glob.js +2 -168
  25. package/src/agents/jules/tools/grep.js +2 -228
  26. package/src/agents/jules/tools/index.js +29 -29
  27. package/src/agents/jules/tools/path-guards.js +2 -161
  28. package/src/agents/jules/tools/runtime-audit.js +507 -503
  29. package/src/agents/jules/tools/shell.js +2 -383
  30. package/src/agents/jules/tools/url-policy.js +100 -100
  31. package/src/agents/persona-visuals.js +61 -0
  32. package/src/agents/shared-tools/dispatch-core.js +315 -0
  33. package/src/agents/shared-tools/file-edit.js +180 -0
  34. package/src/agents/shared-tools/file-read.js +100 -0
  35. package/src/agents/shared-tools/glob.js +168 -0
  36. package/src/agents/shared-tools/grep.js +228 -0
  37. package/src/agents/shared-tools/index.js +46 -0
  38. package/src/agents/shared-tools/path-guards.js +161 -0
  39. package/src/agents/shared-tools/shell.js +383 -0
  40. package/src/ai/aidenid.js +1009 -972
  41. package/src/ai/client.js +553 -508
  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 -0
  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 +371 -126
  57. package/src/auth/http.js +611 -270
  58. package/src/auth/service.js +1106 -891
  59. package/src/auth/session-store.js +813 -359
  60. package/src/cli.js +252 -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 +1166 -1166
  67. package/src/commands/auth.js +419 -375
  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 -21
  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 -866
  87. package/src/commands/spec.js +716 -716
  88. package/src/commands/swarm.js +651 -651
  89. package/src/commands/telemetry.js +202 -202
  90. package/src/commands/watch.js +511 -510
  91. package/src/config/agent-dictionary.js +182 -182
  92. package/src/config/io.js +56 -56
  93. package/src/config/paths.js +18 -18
  94. package/src/config/schema.js +55 -55
  95. package/src/config/service.js +184 -184
  96. package/src/cost/budget.js +235 -235
  97. package/src/cost/history.js +188 -188
  98. package/src/cost/tracker.js +171 -171
  99. package/src/daemon/artifact-lineage.js +534 -534
  100. package/src/daemon/assignment-ledger.js +770 -770
  101. package/src/daemon/ast-parser-layer.js +258 -258
  102. package/src/daemon/budget-governor.js +633 -633
  103. package/src/daemon/callgraph-overlay.js +646 -646
  104. package/src/daemon/error-worker.js +626 -626
  105. package/src/daemon/fix-cycle.js +377 -0
  106. package/src/daemon/hybrid-mapper.js +929 -929
  107. package/src/daemon/jira-lifecycle.js +632 -632
  108. package/src/daemon/operator-control.js +657 -657
  109. package/src/daemon/pulse.js +327 -0
  110. package/src/daemon/reliability-lane.js +471 -471
  111. package/src/daemon/watchdog.js +971 -971
  112. package/src/guide/generator.js +316 -316
  113. package/src/ingest/engine.js +918 -918
  114. package/src/interactive/index.js +97 -95
  115. package/src/legacy-cli.js +2994 -2592
  116. package/src/mcp/registry.js +695 -695
  117. package/src/memory/blackboard.js +301 -301
  118. package/src/memory/retrieval.js +581 -581
  119. package/src/plugin/manifest.js +553 -553
  120. package/src/policy/packs.js +144 -144
  121. package/src/prompt/generator.js +118 -118
  122. package/src/review/ai-review.js +679 -669
  123. package/src/review/local-review.js +1305 -1295
  124. package/src/review/omargate-interactive.js +68 -0
  125. package/src/review/omargate-orchestrator.js +300 -0
  126. package/src/review/persona-prompts.js +296 -0
  127. package/src/review/replay.js +235 -235
  128. package/src/review/report.js +664 -664
  129. package/src/review/scan-modes.js +42 -0
  130. package/src/review/spec-binding.js +487 -487
  131. package/src/scaffold/generator.js +67 -67
  132. package/src/scaffold/templates.js +150 -150
  133. package/src/scan/generator.js +418 -418
  134. package/src/scan/gh-secrets.js +107 -107
  135. package/src/spec/generator.js +519 -519
  136. package/src/spec/regenerate.js +237 -237
  137. package/src/spec/templates.js +91 -91
  138. package/src/swarm/dashboard.js +247 -247
  139. package/src/swarm/factory.js +363 -363
  140. package/src/swarm/pentest.js +934 -934
  141. package/src/swarm/registry.js +419 -419
  142. package/src/swarm/report.js +158 -158
  143. package/src/swarm/runtime.js +576 -576
  144. package/src/swarm/scenario-dsl.js +272 -272
  145. package/src/telemetry/ledger.js +302 -302
  146. package/src/telemetry/session-tracker.js +234 -118
  147. package/src/telemetry/sync.js +203 -199
  148. package/src/ui/command-hints.js +13 -0
  149. package/src/ui/markdown.js +220 -220
@@ -1,632 +1,632 @@
1
- import fsp from "node:fs/promises";
2
- import path from "node:path";
3
-
4
- import { resolveAssignmentLedgerStorage } from "./assignment-ledger.js";
5
- import { resolveErrorDaemonStorage } from "./error-worker.js";
6
-
7
- const LIFECYCLE_SCHEMA_VERSION = "1.0.0";
8
- const QUEUE_SCHEMA_VERSION = "1.0.0";
9
-
10
- export const JIRA_STATUSES = Object.freeze([
11
- "OPEN",
12
- "IN_PROGRESS",
13
- "BLOCKED",
14
- "DONE",
15
- "CANCELLED",
16
- ]);
17
-
18
- const JIRA_STATUS_SET = new Set(JIRA_STATUSES);
19
-
20
- function normalizeString(value) {
21
- return String(value || "").trim();
22
- }
23
-
24
- function normalizeIsoTimestamp(value, fallbackIso = new Date().toISOString()) {
25
- const normalized = normalizeString(value);
26
- if (!normalized) {
27
- return fallbackIso;
28
- }
29
- const epoch = Date.parse(normalized);
30
- if (!Number.isFinite(epoch)) {
31
- return fallbackIso;
32
- }
33
- return new Date(epoch).toISOString();
34
- }
35
-
36
- function normalizeStatus(value, fallbackValue = "OPEN") {
37
- const normalized = normalizeString(value).toUpperCase();
38
- if (JIRA_STATUS_SET.has(normalized)) {
39
- return normalized;
40
- }
41
- return fallbackValue;
42
- }
43
-
44
- function normalizeLabels(labels = []) {
45
- if (!Array.isArray(labels)) {
46
- return [];
47
- }
48
- const deduped = new Set();
49
- for (const label of labels) {
50
- const normalized = normalizeString(label);
51
- if (normalized) {
52
- deduped.add(normalized);
53
- }
54
- }
55
- return [...deduped];
56
- }
57
-
58
- function normalizeComment(comment = {}, nowIso = new Date().toISOString()) {
59
- return {
60
- at: normalizeIsoTimestamp(comment.at, nowIso),
61
- actor: normalizeString(comment.actor) || "omar-daemon",
62
- type: normalizeString(comment.type) || "note",
63
- message: normalizeString(comment.message),
64
- };
65
- }
66
-
67
- function normalizeTransition(transition = {}, nowIso = new Date().toISOString()) {
68
- return {
69
- at: normalizeIsoTimestamp(transition.at, nowIso),
70
- actor: normalizeString(transition.actor) || "omar-daemon",
71
- from: normalizeStatus(transition.from, "OPEN"),
72
- to: normalizeStatus(transition.to, "OPEN"),
73
- reason: normalizeString(transition.reason) || null,
74
- };
75
- }
76
-
77
- function normalizeIssue(issue = {}, nowIso = new Date().toISOString()) {
78
- const createdAt = normalizeIsoTimestamp(issue.createdAt, nowIso);
79
- return {
80
- workItemId: normalizeString(issue.workItemId),
81
- issueKey: normalizeString(issue.issueKey),
82
- summary: normalizeString(issue.summary) || "Daemon work item remediation",
83
- description: normalizeString(issue.description),
84
- status: normalizeStatus(issue.status, "OPEN"),
85
- labels: normalizeLabels(issue.labels),
86
- assignee: normalizeString(issue.assignee) || null,
87
- createdAt,
88
- updatedAt: normalizeIsoTimestamp(issue.updatedAt, createdAt),
89
- latestCommentAt: issue.latestCommentAt ? normalizeIsoTimestamp(issue.latestCommentAt, createdAt) : null,
90
- comments: Array.isArray(issue.comments)
91
- ? issue.comments.map((comment) => normalizeComment(comment, createdAt)).filter((comment) => comment.message)
92
- : [],
93
- transitions: Array.isArray(issue.transitions)
94
- ? issue.transitions
95
- .map((transition) => normalizeTransition(transition, createdAt))
96
- .filter((transition) => transition.to)
97
- : [],
98
- };
99
- }
100
-
101
- function createInitialLifecycle(nowIso = new Date().toISOString()) {
102
- return {
103
- schemaVersion: LIFECYCLE_SCHEMA_VERSION,
104
- generatedAt: normalizeIsoTimestamp(nowIso, nowIso),
105
- issueCounter: 0,
106
- issues: [],
107
- };
108
- }
109
-
110
- function normalizeIssueKeyPrefix(value) {
111
- const cleaned = normalizeString(value)
112
- .toUpperCase()
113
- .replace(/[^A-Z0-9]+/g, "");
114
- if (!cleaned) {
115
- return "SLD";
116
- }
117
- return cleaned.slice(0, 12);
118
- }
119
-
120
- function parseCsv(rawValue) {
121
- if (!rawValue) {
122
- return [];
123
- }
124
- return String(rawValue)
125
- .split(",")
126
- .map((item) => item.trim())
127
- .filter(Boolean);
128
- }
129
-
130
- async function loadJsonFile(filePath, defaultFactory) {
131
- try {
132
- const raw = await fsp.readFile(filePath, "utf-8");
133
- return JSON.parse(raw);
134
- } catch (error) {
135
- if (error && typeof error === "object" && error.code === "ENOENT") {
136
- return defaultFactory();
137
- }
138
- throw error;
139
- }
140
- }
141
-
142
- async function writeJsonFile(filePath, payload = {}) {
143
- await fsp.mkdir(path.dirname(filePath), { recursive: true });
144
- await fsp.writeFile(filePath, `${JSON.stringify(payload, null, 2)}\n`, "utf-8");
145
- }
146
-
147
- async function appendEvent(filePath, payload = {}) {
148
- await fsp.mkdir(path.dirname(filePath), { recursive: true });
149
- await fsp.appendFile(filePath, `${JSON.stringify(payload)}\n`, "utf-8");
150
- }
151
-
152
- async function loadQueue(queuePath, nowIso = new Date().toISOString()) {
153
- const parsed = await loadJsonFile(queuePath, () => ({
154
- schemaVersion: QUEUE_SCHEMA_VERSION,
155
- generatedAt: normalizeIsoTimestamp(nowIso, nowIso),
156
- items: [],
157
- }));
158
- return {
159
- schemaVersion: normalizeString(parsed.schemaVersion) || QUEUE_SCHEMA_VERSION,
160
- generatedAt: normalizeIsoTimestamp(parsed.generatedAt, nowIso),
161
- items: Array.isArray(parsed.items) ? parsed.items : [],
162
- };
163
- }
164
-
165
- async function loadLifecycle(lifecyclePath, nowIso = new Date().toISOString()) {
166
- const parsed = await loadJsonFile(lifecyclePath, () => createInitialLifecycle(nowIso));
167
- return {
168
- schemaVersion: normalizeString(parsed.schemaVersion) || LIFECYCLE_SCHEMA_VERSION,
169
- generatedAt: normalizeIsoTimestamp(parsed.generatedAt, nowIso),
170
- issueCounter: Number(parsed.issueCounter || 0),
171
- issues: Array.isArray(parsed.issues)
172
- ? parsed.issues.map((issue) => normalizeIssue(issue, nowIso)).filter((issue) => issue.workItemId && issue.issueKey)
173
- : [],
174
- };
175
- }
176
-
177
- async function writeLifecycle(lifecyclePath, lifecycle = {}, nowIso = new Date().toISOString()) {
178
- const normalized = {
179
- schemaVersion: LIFECYCLE_SCHEMA_VERSION,
180
- generatedAt: normalizeIsoTimestamp(nowIso, nowIso),
181
- issueCounter: Math.max(0, Number(lifecycle.issueCounter || 0)),
182
- issues: Array.isArray(lifecycle.issues)
183
- ? lifecycle.issues
184
- .map((issue) => normalizeIssue(issue, nowIso))
185
- .filter((issue) => issue.workItemId && issue.issueKey)
186
- : [],
187
- };
188
- await writeJsonFile(lifecyclePath, normalized);
189
- return normalized;
190
- }
191
-
192
- function findIssueIndex(lifecycle = {}, { workItemId = "", issueKey = "" } = {}) {
193
- const normalizedWorkItemId = normalizeString(workItemId);
194
- const normalizedIssueKey = normalizeString(issueKey);
195
- return lifecycle.issues.findIndex((issue) => {
196
- if (normalizedIssueKey && issue.issueKey === normalizedIssueKey) {
197
- return true;
198
- }
199
- if (normalizedWorkItemId && issue.workItemId === normalizedWorkItemId) {
200
- return true;
201
- }
202
- return false;
203
- });
204
- }
205
-
206
- function buildDefaultSummary(queueItem = {}, workItemId = "") {
207
- const service = normalizeString(queueItem.service) || "unknown-service";
208
- const endpoint = normalizeString(queueItem.endpoint) || "unknown-endpoint";
209
- const errorCode = normalizeString(queueItem.errorCode) || "UNKNOWN_ERROR";
210
- return `[${workItemId}] ${service} ${endpoint} ${errorCode}`.trim();
211
- }
212
-
213
- function buildDefaultDescription(queueItem = {}) {
214
- const lines = [
215
- `service: ${normalizeString(queueItem.service) || "unknown-service"}`,
216
- `endpoint: ${normalizeString(queueItem.endpoint) || "unknown-endpoint"}`,
217
- `error_code: ${normalizeString(queueItem.errorCode) || "UNKNOWN_ERROR"}`,
218
- `severity: ${normalizeString(queueItem.severity) || "UNKNOWN"}`,
219
- `message: ${normalizeString(queueItem.message) || "n/a"}`,
220
- `fingerprint: ${normalizeString(queueItem.fingerprint) || "n/a"}`,
221
- ];
222
- return lines.join("\n");
223
- }
224
-
225
- async function syncIssueKeyToAssignment({
226
- targetPath,
227
- outputDir,
228
- workItemId,
229
- issueKey,
230
- nowIso,
231
- env,
232
- homeDir,
233
- } = {}) {
234
- const assignmentStorage = await resolveAssignmentLedgerStorage({
235
- targetPath,
236
- outputDir,
237
- env,
238
- homeDir,
239
- });
240
- const rawLedger = await loadJsonFile(assignmentStorage.ledgerPath, () => null);
241
- if (!rawLedger || !Array.isArray(rawLedger.assignments)) {
242
- return;
243
- }
244
- const assignments = rawLedger.assignments.map((record) => ({
245
- ...record,
246
- workItemId: normalizeString(record.workItemId),
247
- }));
248
- const index = assignments.findIndex((record) => record.workItemId === workItemId);
249
- if (index < 0) {
250
- return;
251
- }
252
- assignments[index] = {
253
- ...assignments[index],
254
- jiraIssueKey: issueKey,
255
- updatedAt: nowIso,
256
- };
257
- await writeJsonFile(assignmentStorage.ledgerPath, {
258
- ...rawLedger,
259
- generatedAt: nowIso,
260
- assignments,
261
- });
262
- }
263
-
264
- export async function resolveJiraLifecycleStorage({
265
- targetPath = ".",
266
- outputDir = "",
267
- env,
268
- homeDir,
269
- } = {}) {
270
- const daemonStorage = await resolveErrorDaemonStorage({
271
- targetPath,
272
- outputDir,
273
- env,
274
- homeDir,
275
- });
276
- return {
277
- ...daemonStorage,
278
- lifecyclePath: path.join(daemonStorage.baseDir, "jira-lifecycle.json"),
279
- eventsPath: path.join(daemonStorage.baseDir, "jira-events.ndjson"),
280
- };
281
- }
282
-
283
- export async function openJiraIssue({
284
- targetPath = ".",
285
- outputDir = "",
286
- workItemId,
287
- summary = "",
288
- description = "",
289
- labels = [],
290
- assignee = "",
291
- issueKey = "",
292
- issueKeyPrefix = "SLD",
293
- actor = "omar-daemon",
294
- env,
295
- homeDir,
296
- nowIso = new Date().toISOString(),
297
- } = {}) {
298
- const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
299
- const normalizedWorkItemId = normalizeString(workItemId);
300
- if (!normalizedWorkItemId) {
301
- throw new Error("workItemId is required.");
302
- }
303
- const storage = await resolveJiraLifecycleStorage({
304
- targetPath,
305
- outputDir,
306
- env,
307
- homeDir,
308
- });
309
- const [queue, lifecycle] = await Promise.all([
310
- loadQueue(storage.queuePath, normalizedNow),
311
- loadLifecycle(storage.lifecyclePath, normalizedNow),
312
- ]);
313
- const queueItem = queue.items.find((item) => normalizeString(item.workItemId) === normalizedWorkItemId);
314
- if (!queueItem) {
315
- throw new Error(`Work item '${normalizedWorkItemId}' was not found in daemon queue.`);
316
- }
317
-
318
- const existingIndex = findIssueIndex(lifecycle, { workItemId: normalizedWorkItemId });
319
- if (existingIndex >= 0) {
320
- const existing = lifecycle.issues[existingIndex];
321
- await syncIssueKeyToAssignment({
322
- targetPath,
323
- outputDir,
324
- workItemId: normalizedWorkItemId,
325
- issueKey: existing.issueKey,
326
- nowIso: normalizedNow,
327
- env,
328
- homeDir,
329
- });
330
- return {
331
- ...storage,
332
- issue: existing,
333
- created: false,
334
- };
335
- }
336
-
337
- let normalizedIssueKey = normalizeString(issueKey);
338
- if (!normalizedIssueKey) {
339
- const prefix = normalizeIssueKeyPrefix(issueKeyPrefix);
340
- lifecycle.issueCounter = Math.max(0, Number(lifecycle.issueCounter || 0)) + 1;
341
- normalizedIssueKey = `${prefix}-${lifecycle.issueCounter}`;
342
- }
343
- const duplicateIssueKey = lifecycle.issues.some((issue) => issue.issueKey === normalizedIssueKey);
344
- if (duplicateIssueKey) {
345
- throw new Error(`issueKey '${normalizedIssueKey}' already exists in jira lifecycle registry.`);
346
- }
347
-
348
- const issue = normalizeIssue(
349
- {
350
- workItemId: normalizedWorkItemId,
351
- issueKey: normalizedIssueKey,
352
- summary: normalizeString(summary) || buildDefaultSummary(queueItem, normalizedWorkItemId),
353
- description: normalizeString(description) || buildDefaultDescription(queueItem),
354
- status: "OPEN",
355
- labels: normalizeLabels([
356
- "sentinelayer",
357
- "omar-daemon",
358
- `severity-${normalizeString(queueItem.severity || "unknown").toLowerCase()}`,
359
- ...labels,
360
- ]),
361
- assignee: normalizeString(assignee) || null,
362
- createdAt: normalizedNow,
363
- updatedAt: normalizedNow,
364
- latestCommentAt: null,
365
- comments: [],
366
- transitions: [],
367
- },
368
- normalizedNow
369
- );
370
- lifecycle.issues.push(issue);
371
- const savedLifecycle = await writeLifecycle(storage.lifecyclePath, lifecycle, normalizedNow);
372
- await appendEvent(storage.eventsPath, {
373
- timestamp: normalizedNow,
374
- eventType: "create_issue",
375
- actor: normalizeString(actor) || "omar-daemon",
376
- workItemId: normalizedWorkItemId,
377
- issueKey: normalizedIssueKey,
378
- status: "OPEN",
379
- });
380
- await syncIssueKeyToAssignment({
381
- targetPath,
382
- outputDir,
383
- workItemId: normalizedWorkItemId,
384
- issueKey: normalizedIssueKey,
385
- nowIso: normalizedNow,
386
- env,
387
- homeDir,
388
- });
389
- return {
390
- ...storage,
391
- lifecycle: savedLifecycle,
392
- issue,
393
- created: true,
394
- };
395
- }
396
-
397
- export async function commentJiraIssue({
398
- targetPath = ".",
399
- outputDir = "",
400
- workItemId = "",
401
- issueKey = "",
402
- actor = "omar-daemon",
403
- type = "note",
404
- message,
405
- env,
406
- homeDir,
407
- nowIso = new Date().toISOString(),
408
- } = {}) {
409
- const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
410
- const normalizedMessage = normalizeString(message);
411
- if (!normalizedMessage) {
412
- throw new Error("message is required.");
413
- }
414
- const storage = await resolveJiraLifecycleStorage({
415
- targetPath,
416
- outputDir,
417
- env,
418
- homeDir,
419
- });
420
- const lifecycle = await loadLifecycle(storage.lifecyclePath, normalizedNow);
421
- const issueIndex = findIssueIndex(lifecycle, { workItemId, issueKey });
422
- if (issueIndex < 0) {
423
- throw new Error("No jira lifecycle issue found for the provided workItemId/issueKey.");
424
- }
425
- const existing = lifecycle.issues[issueIndex];
426
- const comment = normalizeComment(
427
- {
428
- at: normalizedNow,
429
- actor,
430
- type,
431
- message: normalizedMessage,
432
- },
433
- normalizedNow
434
- );
435
- existing.comments = [...existing.comments, comment];
436
- existing.latestCommentAt = normalizedNow;
437
- existing.updatedAt = normalizedNow;
438
- lifecycle.issues[issueIndex] = normalizeIssue(existing, normalizedNow);
439
- const savedLifecycle = await writeLifecycle(storage.lifecyclePath, lifecycle, normalizedNow);
440
- await appendEvent(storage.eventsPath, {
441
- timestamp: normalizedNow,
442
- eventType: "comment",
443
- actor: normalizeString(actor) || "omar-daemon",
444
- workItemId: existing.workItemId,
445
- issueKey: existing.issueKey,
446
- type: comment.type,
447
- message: comment.message,
448
- });
449
- return {
450
- ...storage,
451
- lifecycle: savedLifecycle,
452
- issue: lifecycle.issues[issueIndex],
453
- comment,
454
- };
455
- }
456
-
457
- export async function transitionJiraIssue({
458
- targetPath = ".",
459
- outputDir = "",
460
- workItemId = "",
461
- issueKey = "",
462
- toStatus,
463
- actor = "omar-daemon",
464
- reason = "",
465
- env,
466
- homeDir,
467
- nowIso = new Date().toISOString(),
468
- } = {}) {
469
- const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
470
- const nextStatus = normalizeStatus(toStatus, "");
471
- if (!nextStatus) {
472
- throw new Error(`toStatus must be one of: ${JIRA_STATUSES.join(", ")}.`);
473
- }
474
- const storage = await resolveJiraLifecycleStorage({
475
- targetPath,
476
- outputDir,
477
- env,
478
- homeDir,
479
- });
480
- const lifecycle = await loadLifecycle(storage.lifecyclePath, normalizedNow);
481
- const issueIndex = findIssueIndex(lifecycle, { workItemId, issueKey });
482
- if (issueIndex < 0) {
483
- throw new Error("No jira lifecycle issue found for the provided workItemId/issueKey.");
484
- }
485
- const existing = lifecycle.issues[issueIndex];
486
- const transition = normalizeTransition(
487
- {
488
- at: normalizedNow,
489
- actor,
490
- from: existing.status,
491
- to: nextStatus,
492
- reason,
493
- },
494
- normalizedNow
495
- );
496
- existing.status = nextStatus;
497
- existing.transitions = [...existing.transitions, transition];
498
- existing.updatedAt = normalizedNow;
499
- lifecycle.issues[issueIndex] = normalizeIssue(existing, normalizedNow);
500
- const savedLifecycle = await writeLifecycle(storage.lifecyclePath, lifecycle, normalizedNow);
501
- await appendEvent(storage.eventsPath, {
502
- timestamp: normalizedNow,
503
- eventType: "transition",
504
- actor: normalizeString(actor) || "omar-daemon",
505
- workItemId: existing.workItemId,
506
- issueKey: existing.issueKey,
507
- from: transition.from,
508
- to: transition.to,
509
- reason: transition.reason,
510
- });
511
- return {
512
- ...storage,
513
- lifecycle: savedLifecycle,
514
- issue: lifecycle.issues[issueIndex],
515
- transition,
516
- };
517
- }
518
-
519
- export async function startJiraLifecycle({
520
- targetPath = ".",
521
- outputDir = "",
522
- workItemId,
523
- actor = "omar-daemon",
524
- assignee = "",
525
- summary = "",
526
- description = "",
527
- labels = [],
528
- planMessage,
529
- issueKey = "",
530
- issueKeyPrefix = "SLD",
531
- env,
532
- homeDir,
533
- nowIso = new Date().toISOString(),
534
- } = {}) {
535
- const opened = await openJiraIssue({
536
- targetPath,
537
- outputDir,
538
- workItemId,
539
- actor,
540
- assignee,
541
- summary,
542
- description,
543
- labels,
544
- issueKey,
545
- issueKeyPrefix,
546
- env,
547
- homeDir,
548
- nowIso,
549
- });
550
- const normalizedPlanMessage = normalizeString(planMessage);
551
- let comment = null;
552
- if (normalizedPlanMessage) {
553
- const commented = await commentJiraIssue({
554
- targetPath,
555
- outputDir,
556
- workItemId,
557
- issueKey: opened.issue.issueKey,
558
- actor,
559
- type: "plan",
560
- message: normalizedPlanMessage,
561
- env,
562
- homeDir,
563
- nowIso,
564
- });
565
- comment = commented.comment;
566
- }
567
- const transitioned = await transitionJiraIssue({
568
- targetPath,
569
- outputDir,
570
- workItemId,
571
- issueKey: opened.issue.issueKey,
572
- toStatus: "IN_PROGRESS",
573
- actor,
574
- reason: "Agent accepted work item and started remediation plan.",
575
- env,
576
- homeDir,
577
- nowIso,
578
- });
579
- return {
580
- ...transitioned,
581
- created: opened.created,
582
- comment,
583
- };
584
- }
585
-
586
- export async function listJiraIssues({
587
- targetPath = ".",
588
- outputDir = "",
589
- workItemId = "",
590
- issueKey = "",
591
- statuses = [],
592
- limit = 50,
593
- env,
594
- homeDir,
595
- nowIso = new Date().toISOString(),
596
- } = {}) {
597
- const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
598
- const normalizedLimit = Math.max(1, Math.floor(Number(limit || 50)));
599
- const normalizedWorkItemId = normalizeString(workItemId);
600
- const normalizedIssueKey = normalizeString(issueKey);
601
- const statusFilter = new Set(parseCsv(statuses).map((status) => normalizeStatus(status, "")).filter(Boolean));
602
- const storage = await resolveJiraLifecycleStorage({
603
- targetPath,
604
- outputDir,
605
- env,
606
- homeDir,
607
- });
608
- const lifecycle = await loadLifecycle(storage.lifecyclePath, normalizedNow);
609
- const filtered = lifecycle.issues.filter((issue) => {
610
- if (normalizedWorkItemId && issue.workItemId !== normalizedWorkItemId) {
611
- return false;
612
- }
613
- if (normalizedIssueKey && issue.issueKey !== normalizedIssueKey) {
614
- return false;
615
- }
616
- if (statusFilter.size > 0 && !statusFilter.has(issue.status)) {
617
- return false;
618
- }
619
- return true;
620
- });
621
- const sorted = [...filtered].sort((left, right) => {
622
- const leftEpoch = Date.parse(String(left.updatedAt || "")) || 0;
623
- const rightEpoch = Date.parse(String(right.updatedAt || "")) || 0;
624
- return rightEpoch - leftEpoch;
625
- });
626
- return {
627
- ...storage,
628
- totalCount: lifecycle.issues.length,
629
- visibleCount: sorted.length,
630
- issues: sorted.slice(0, normalizedLimit),
631
- };
632
- }
1
+ import fsp from "node:fs/promises";
2
+ import path from "node:path";
3
+
4
+ import { resolveAssignmentLedgerStorage } from "./assignment-ledger.js";
5
+ import { resolveErrorDaemonStorage } from "./error-worker.js";
6
+
7
+ const LIFECYCLE_SCHEMA_VERSION = "1.0.0";
8
+ const QUEUE_SCHEMA_VERSION = "1.0.0";
9
+
10
+ export const JIRA_STATUSES = Object.freeze([
11
+ "OPEN",
12
+ "IN_PROGRESS",
13
+ "BLOCKED",
14
+ "DONE",
15
+ "CANCELLED",
16
+ ]);
17
+
18
+ const JIRA_STATUS_SET = new Set(JIRA_STATUSES);
19
+
20
+ function normalizeString(value) {
21
+ return String(value || "").trim();
22
+ }
23
+
24
+ function normalizeIsoTimestamp(value, fallbackIso = new Date().toISOString()) {
25
+ const normalized = normalizeString(value);
26
+ if (!normalized) {
27
+ return fallbackIso;
28
+ }
29
+ const epoch = Date.parse(normalized);
30
+ if (!Number.isFinite(epoch)) {
31
+ return fallbackIso;
32
+ }
33
+ return new Date(epoch).toISOString();
34
+ }
35
+
36
+ function normalizeStatus(value, fallbackValue = "OPEN") {
37
+ const normalized = normalizeString(value).toUpperCase();
38
+ if (JIRA_STATUS_SET.has(normalized)) {
39
+ return normalized;
40
+ }
41
+ return fallbackValue;
42
+ }
43
+
44
+ function normalizeLabels(labels = []) {
45
+ if (!Array.isArray(labels)) {
46
+ return [];
47
+ }
48
+ const deduped = new Set();
49
+ for (const label of labels) {
50
+ const normalized = normalizeString(label);
51
+ if (normalized) {
52
+ deduped.add(normalized);
53
+ }
54
+ }
55
+ return [...deduped];
56
+ }
57
+
58
+ function normalizeComment(comment = {}, nowIso = new Date().toISOString()) {
59
+ return {
60
+ at: normalizeIsoTimestamp(comment.at, nowIso),
61
+ actor: normalizeString(comment.actor) || "omar-daemon",
62
+ type: normalizeString(comment.type) || "note",
63
+ message: normalizeString(comment.message),
64
+ };
65
+ }
66
+
67
+ function normalizeTransition(transition = {}, nowIso = new Date().toISOString()) {
68
+ return {
69
+ at: normalizeIsoTimestamp(transition.at, nowIso),
70
+ actor: normalizeString(transition.actor) || "omar-daemon",
71
+ from: normalizeStatus(transition.from, "OPEN"),
72
+ to: normalizeStatus(transition.to, "OPEN"),
73
+ reason: normalizeString(transition.reason) || null,
74
+ };
75
+ }
76
+
77
+ function normalizeIssue(issue = {}, nowIso = new Date().toISOString()) {
78
+ const createdAt = normalizeIsoTimestamp(issue.createdAt, nowIso);
79
+ return {
80
+ workItemId: normalizeString(issue.workItemId),
81
+ issueKey: normalizeString(issue.issueKey),
82
+ summary: normalizeString(issue.summary) || "Daemon work item remediation",
83
+ description: normalizeString(issue.description),
84
+ status: normalizeStatus(issue.status, "OPEN"),
85
+ labels: normalizeLabels(issue.labels),
86
+ assignee: normalizeString(issue.assignee) || null,
87
+ createdAt,
88
+ updatedAt: normalizeIsoTimestamp(issue.updatedAt, createdAt),
89
+ latestCommentAt: issue.latestCommentAt ? normalizeIsoTimestamp(issue.latestCommentAt, createdAt) : null,
90
+ comments: Array.isArray(issue.comments)
91
+ ? issue.comments.map((comment) => normalizeComment(comment, createdAt)).filter((comment) => comment.message)
92
+ : [],
93
+ transitions: Array.isArray(issue.transitions)
94
+ ? issue.transitions
95
+ .map((transition) => normalizeTransition(transition, createdAt))
96
+ .filter((transition) => transition.to)
97
+ : [],
98
+ };
99
+ }
100
+
101
+ function createInitialLifecycle(nowIso = new Date().toISOString()) {
102
+ return {
103
+ schemaVersion: LIFECYCLE_SCHEMA_VERSION,
104
+ generatedAt: normalizeIsoTimestamp(nowIso, nowIso),
105
+ issueCounter: 0,
106
+ issues: [],
107
+ };
108
+ }
109
+
110
+ function normalizeIssueKeyPrefix(value) {
111
+ const cleaned = normalizeString(value)
112
+ .toUpperCase()
113
+ .replace(/[^A-Z0-9]+/g, "");
114
+ if (!cleaned) {
115
+ return "SLD";
116
+ }
117
+ return cleaned.slice(0, 12);
118
+ }
119
+
120
+ function parseCsv(rawValue) {
121
+ if (!rawValue) {
122
+ return [];
123
+ }
124
+ return String(rawValue)
125
+ .split(",")
126
+ .map((item) => item.trim())
127
+ .filter(Boolean);
128
+ }
129
+
130
+ async function loadJsonFile(filePath, defaultFactory) {
131
+ try {
132
+ const raw = await fsp.readFile(filePath, "utf-8");
133
+ return JSON.parse(raw);
134
+ } catch (error) {
135
+ if (error && typeof error === "object" && error.code === "ENOENT") {
136
+ return defaultFactory();
137
+ }
138
+ throw error;
139
+ }
140
+ }
141
+
142
+ async function writeJsonFile(filePath, payload = {}) {
143
+ await fsp.mkdir(path.dirname(filePath), { recursive: true });
144
+ await fsp.writeFile(filePath, `${JSON.stringify(payload, null, 2)}\n`, "utf-8");
145
+ }
146
+
147
+ async function appendEvent(filePath, payload = {}) {
148
+ await fsp.mkdir(path.dirname(filePath), { recursive: true });
149
+ await fsp.appendFile(filePath, `${JSON.stringify(payload)}\n`, "utf-8");
150
+ }
151
+
152
+ async function loadQueue(queuePath, nowIso = new Date().toISOString()) {
153
+ const parsed = await loadJsonFile(queuePath, () => ({
154
+ schemaVersion: QUEUE_SCHEMA_VERSION,
155
+ generatedAt: normalizeIsoTimestamp(nowIso, nowIso),
156
+ items: [],
157
+ }));
158
+ return {
159
+ schemaVersion: normalizeString(parsed.schemaVersion) || QUEUE_SCHEMA_VERSION,
160
+ generatedAt: normalizeIsoTimestamp(parsed.generatedAt, nowIso),
161
+ items: Array.isArray(parsed.items) ? parsed.items : [],
162
+ };
163
+ }
164
+
165
+ async function loadLifecycle(lifecyclePath, nowIso = new Date().toISOString()) {
166
+ const parsed = await loadJsonFile(lifecyclePath, () => createInitialLifecycle(nowIso));
167
+ return {
168
+ schemaVersion: normalizeString(parsed.schemaVersion) || LIFECYCLE_SCHEMA_VERSION,
169
+ generatedAt: normalizeIsoTimestamp(parsed.generatedAt, nowIso),
170
+ issueCounter: Number(parsed.issueCounter || 0),
171
+ issues: Array.isArray(parsed.issues)
172
+ ? parsed.issues.map((issue) => normalizeIssue(issue, nowIso)).filter((issue) => issue.workItemId && issue.issueKey)
173
+ : [],
174
+ };
175
+ }
176
+
177
+ async function writeLifecycle(lifecyclePath, lifecycle = {}, nowIso = new Date().toISOString()) {
178
+ const normalized = {
179
+ schemaVersion: LIFECYCLE_SCHEMA_VERSION,
180
+ generatedAt: normalizeIsoTimestamp(nowIso, nowIso),
181
+ issueCounter: Math.max(0, Number(lifecycle.issueCounter || 0)),
182
+ issues: Array.isArray(lifecycle.issues)
183
+ ? lifecycle.issues
184
+ .map((issue) => normalizeIssue(issue, nowIso))
185
+ .filter((issue) => issue.workItemId && issue.issueKey)
186
+ : [],
187
+ };
188
+ await writeJsonFile(lifecyclePath, normalized);
189
+ return normalized;
190
+ }
191
+
192
+ function findIssueIndex(lifecycle = {}, { workItemId = "", issueKey = "" } = {}) {
193
+ const normalizedWorkItemId = normalizeString(workItemId);
194
+ const normalizedIssueKey = normalizeString(issueKey);
195
+ return lifecycle.issues.findIndex((issue) => {
196
+ if (normalizedIssueKey && issue.issueKey === normalizedIssueKey) {
197
+ return true;
198
+ }
199
+ if (normalizedWorkItemId && issue.workItemId === normalizedWorkItemId) {
200
+ return true;
201
+ }
202
+ return false;
203
+ });
204
+ }
205
+
206
+ function buildDefaultSummary(queueItem = {}, workItemId = "") {
207
+ const service = normalizeString(queueItem.service) || "unknown-service";
208
+ const endpoint = normalizeString(queueItem.endpoint) || "unknown-endpoint";
209
+ const errorCode = normalizeString(queueItem.errorCode) || "UNKNOWN_ERROR";
210
+ return `[${workItemId}] ${service} ${endpoint} ${errorCode}`.trim();
211
+ }
212
+
213
+ function buildDefaultDescription(queueItem = {}) {
214
+ const lines = [
215
+ `service: ${normalizeString(queueItem.service) || "unknown-service"}`,
216
+ `endpoint: ${normalizeString(queueItem.endpoint) || "unknown-endpoint"}`,
217
+ `error_code: ${normalizeString(queueItem.errorCode) || "UNKNOWN_ERROR"}`,
218
+ `severity: ${normalizeString(queueItem.severity) || "UNKNOWN"}`,
219
+ `message: ${normalizeString(queueItem.message) || "n/a"}`,
220
+ `fingerprint: ${normalizeString(queueItem.fingerprint) || "n/a"}`,
221
+ ];
222
+ return lines.join("\n");
223
+ }
224
+
225
+ async function syncIssueKeyToAssignment({
226
+ targetPath,
227
+ outputDir,
228
+ workItemId,
229
+ issueKey,
230
+ nowIso,
231
+ env,
232
+ homeDir,
233
+ } = {}) {
234
+ const assignmentStorage = await resolveAssignmentLedgerStorage({
235
+ targetPath,
236
+ outputDir,
237
+ env,
238
+ homeDir,
239
+ });
240
+ const rawLedger = await loadJsonFile(assignmentStorage.ledgerPath, () => null);
241
+ if (!rawLedger || !Array.isArray(rawLedger.assignments)) {
242
+ return;
243
+ }
244
+ const assignments = rawLedger.assignments.map((record) => ({
245
+ ...record,
246
+ workItemId: normalizeString(record.workItemId),
247
+ }));
248
+ const index = assignments.findIndex((record) => record.workItemId === workItemId);
249
+ if (index < 0) {
250
+ return;
251
+ }
252
+ assignments[index] = {
253
+ ...assignments[index],
254
+ jiraIssueKey: issueKey,
255
+ updatedAt: nowIso,
256
+ };
257
+ await writeJsonFile(assignmentStorage.ledgerPath, {
258
+ ...rawLedger,
259
+ generatedAt: nowIso,
260
+ assignments,
261
+ });
262
+ }
263
+
264
+ export async function resolveJiraLifecycleStorage({
265
+ targetPath = ".",
266
+ outputDir = "",
267
+ env,
268
+ homeDir,
269
+ } = {}) {
270
+ const daemonStorage = await resolveErrorDaemonStorage({
271
+ targetPath,
272
+ outputDir,
273
+ env,
274
+ homeDir,
275
+ });
276
+ return {
277
+ ...daemonStorage,
278
+ lifecyclePath: path.join(daemonStorage.baseDir, "jira-lifecycle.json"),
279
+ eventsPath: path.join(daemonStorage.baseDir, "jira-events.ndjson"),
280
+ };
281
+ }
282
+
283
+ export async function openJiraIssue({
284
+ targetPath = ".",
285
+ outputDir = "",
286
+ workItemId,
287
+ summary = "",
288
+ description = "",
289
+ labels = [],
290
+ assignee = "",
291
+ issueKey = "",
292
+ issueKeyPrefix = "SLD",
293
+ actor = "omar-daemon",
294
+ env,
295
+ homeDir,
296
+ nowIso = new Date().toISOString(),
297
+ } = {}) {
298
+ const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
299
+ const normalizedWorkItemId = normalizeString(workItemId);
300
+ if (!normalizedWorkItemId) {
301
+ throw new Error("workItemId is required.");
302
+ }
303
+ const storage = await resolveJiraLifecycleStorage({
304
+ targetPath,
305
+ outputDir,
306
+ env,
307
+ homeDir,
308
+ });
309
+ const [queue, lifecycle] = await Promise.all([
310
+ loadQueue(storage.queuePath, normalizedNow),
311
+ loadLifecycle(storage.lifecyclePath, normalizedNow),
312
+ ]);
313
+ const queueItem = queue.items.find((item) => normalizeString(item.workItemId) === normalizedWorkItemId);
314
+ if (!queueItem) {
315
+ throw new Error(`Work item '${normalizedWorkItemId}' was not found in daemon queue.`);
316
+ }
317
+
318
+ const existingIndex = findIssueIndex(lifecycle, { workItemId: normalizedWorkItemId });
319
+ if (existingIndex >= 0) {
320
+ const existing = lifecycle.issues[existingIndex];
321
+ await syncIssueKeyToAssignment({
322
+ targetPath,
323
+ outputDir,
324
+ workItemId: normalizedWorkItemId,
325
+ issueKey: existing.issueKey,
326
+ nowIso: normalizedNow,
327
+ env,
328
+ homeDir,
329
+ });
330
+ return {
331
+ ...storage,
332
+ issue: existing,
333
+ created: false,
334
+ };
335
+ }
336
+
337
+ let normalizedIssueKey = normalizeString(issueKey);
338
+ if (!normalizedIssueKey) {
339
+ const prefix = normalizeIssueKeyPrefix(issueKeyPrefix);
340
+ lifecycle.issueCounter = Math.max(0, Number(lifecycle.issueCounter || 0)) + 1;
341
+ normalizedIssueKey = `${prefix}-${lifecycle.issueCounter}`;
342
+ }
343
+ const duplicateIssueKey = lifecycle.issues.some((issue) => issue.issueKey === normalizedIssueKey);
344
+ if (duplicateIssueKey) {
345
+ throw new Error(`issueKey '${normalizedIssueKey}' already exists in jira lifecycle registry.`);
346
+ }
347
+
348
+ const issue = normalizeIssue(
349
+ {
350
+ workItemId: normalizedWorkItemId,
351
+ issueKey: normalizedIssueKey,
352
+ summary: normalizeString(summary) || buildDefaultSummary(queueItem, normalizedWorkItemId),
353
+ description: normalizeString(description) || buildDefaultDescription(queueItem),
354
+ status: "OPEN",
355
+ labels: normalizeLabels([
356
+ "sentinelayer",
357
+ "omar-daemon",
358
+ `severity-${normalizeString(queueItem.severity || "unknown").toLowerCase()}`,
359
+ ...labels,
360
+ ]),
361
+ assignee: normalizeString(assignee) || null,
362
+ createdAt: normalizedNow,
363
+ updatedAt: normalizedNow,
364
+ latestCommentAt: null,
365
+ comments: [],
366
+ transitions: [],
367
+ },
368
+ normalizedNow
369
+ );
370
+ lifecycle.issues.push(issue);
371
+ const savedLifecycle = await writeLifecycle(storage.lifecyclePath, lifecycle, normalizedNow);
372
+ await appendEvent(storage.eventsPath, {
373
+ timestamp: normalizedNow,
374
+ eventType: "create_issue",
375
+ actor: normalizeString(actor) || "omar-daemon",
376
+ workItemId: normalizedWorkItemId,
377
+ issueKey: normalizedIssueKey,
378
+ status: "OPEN",
379
+ });
380
+ await syncIssueKeyToAssignment({
381
+ targetPath,
382
+ outputDir,
383
+ workItemId: normalizedWorkItemId,
384
+ issueKey: normalizedIssueKey,
385
+ nowIso: normalizedNow,
386
+ env,
387
+ homeDir,
388
+ });
389
+ return {
390
+ ...storage,
391
+ lifecycle: savedLifecycle,
392
+ issue,
393
+ created: true,
394
+ };
395
+ }
396
+
397
+ export async function commentJiraIssue({
398
+ targetPath = ".",
399
+ outputDir = "",
400
+ workItemId = "",
401
+ issueKey = "",
402
+ actor = "omar-daemon",
403
+ type = "note",
404
+ message,
405
+ env,
406
+ homeDir,
407
+ nowIso = new Date().toISOString(),
408
+ } = {}) {
409
+ const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
410
+ const normalizedMessage = normalizeString(message);
411
+ if (!normalizedMessage) {
412
+ throw new Error("message is required.");
413
+ }
414
+ const storage = await resolveJiraLifecycleStorage({
415
+ targetPath,
416
+ outputDir,
417
+ env,
418
+ homeDir,
419
+ });
420
+ const lifecycle = await loadLifecycle(storage.lifecyclePath, normalizedNow);
421
+ const issueIndex = findIssueIndex(lifecycle, { workItemId, issueKey });
422
+ if (issueIndex < 0) {
423
+ throw new Error("No jira lifecycle issue found for the provided workItemId/issueKey.");
424
+ }
425
+ const existing = lifecycle.issues[issueIndex];
426
+ const comment = normalizeComment(
427
+ {
428
+ at: normalizedNow,
429
+ actor,
430
+ type,
431
+ message: normalizedMessage,
432
+ },
433
+ normalizedNow
434
+ );
435
+ existing.comments = [...existing.comments, comment];
436
+ existing.latestCommentAt = normalizedNow;
437
+ existing.updatedAt = normalizedNow;
438
+ lifecycle.issues[issueIndex] = normalizeIssue(existing, normalizedNow);
439
+ const savedLifecycle = await writeLifecycle(storage.lifecyclePath, lifecycle, normalizedNow);
440
+ await appendEvent(storage.eventsPath, {
441
+ timestamp: normalizedNow,
442
+ eventType: "comment",
443
+ actor: normalizeString(actor) || "omar-daemon",
444
+ workItemId: existing.workItemId,
445
+ issueKey: existing.issueKey,
446
+ type: comment.type,
447
+ message: comment.message,
448
+ });
449
+ return {
450
+ ...storage,
451
+ lifecycle: savedLifecycle,
452
+ issue: lifecycle.issues[issueIndex],
453
+ comment,
454
+ };
455
+ }
456
+
457
+ export async function transitionJiraIssue({
458
+ targetPath = ".",
459
+ outputDir = "",
460
+ workItemId = "",
461
+ issueKey = "",
462
+ toStatus,
463
+ actor = "omar-daemon",
464
+ reason = "",
465
+ env,
466
+ homeDir,
467
+ nowIso = new Date().toISOString(),
468
+ } = {}) {
469
+ const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
470
+ const nextStatus = normalizeStatus(toStatus, "");
471
+ if (!nextStatus) {
472
+ throw new Error(`toStatus must be one of: ${JIRA_STATUSES.join(", ")}.`);
473
+ }
474
+ const storage = await resolveJiraLifecycleStorage({
475
+ targetPath,
476
+ outputDir,
477
+ env,
478
+ homeDir,
479
+ });
480
+ const lifecycle = await loadLifecycle(storage.lifecyclePath, normalizedNow);
481
+ const issueIndex = findIssueIndex(lifecycle, { workItemId, issueKey });
482
+ if (issueIndex < 0) {
483
+ throw new Error("No jira lifecycle issue found for the provided workItemId/issueKey.");
484
+ }
485
+ const existing = lifecycle.issues[issueIndex];
486
+ const transition = normalizeTransition(
487
+ {
488
+ at: normalizedNow,
489
+ actor,
490
+ from: existing.status,
491
+ to: nextStatus,
492
+ reason,
493
+ },
494
+ normalizedNow
495
+ );
496
+ existing.status = nextStatus;
497
+ existing.transitions = [...existing.transitions, transition];
498
+ existing.updatedAt = normalizedNow;
499
+ lifecycle.issues[issueIndex] = normalizeIssue(existing, normalizedNow);
500
+ const savedLifecycle = await writeLifecycle(storage.lifecyclePath, lifecycle, normalizedNow);
501
+ await appendEvent(storage.eventsPath, {
502
+ timestamp: normalizedNow,
503
+ eventType: "transition",
504
+ actor: normalizeString(actor) || "omar-daemon",
505
+ workItemId: existing.workItemId,
506
+ issueKey: existing.issueKey,
507
+ from: transition.from,
508
+ to: transition.to,
509
+ reason: transition.reason,
510
+ });
511
+ return {
512
+ ...storage,
513
+ lifecycle: savedLifecycle,
514
+ issue: lifecycle.issues[issueIndex],
515
+ transition,
516
+ };
517
+ }
518
+
519
+ export async function startJiraLifecycle({
520
+ targetPath = ".",
521
+ outputDir = "",
522
+ workItemId,
523
+ actor = "omar-daemon",
524
+ assignee = "",
525
+ summary = "",
526
+ description = "",
527
+ labels = [],
528
+ planMessage,
529
+ issueKey = "",
530
+ issueKeyPrefix = "SLD",
531
+ env,
532
+ homeDir,
533
+ nowIso = new Date().toISOString(),
534
+ } = {}) {
535
+ const opened = await openJiraIssue({
536
+ targetPath,
537
+ outputDir,
538
+ workItemId,
539
+ actor,
540
+ assignee,
541
+ summary,
542
+ description,
543
+ labels,
544
+ issueKey,
545
+ issueKeyPrefix,
546
+ env,
547
+ homeDir,
548
+ nowIso,
549
+ });
550
+ const normalizedPlanMessage = normalizeString(planMessage);
551
+ let comment = null;
552
+ if (normalizedPlanMessage) {
553
+ const commented = await commentJiraIssue({
554
+ targetPath,
555
+ outputDir,
556
+ workItemId,
557
+ issueKey: opened.issue.issueKey,
558
+ actor,
559
+ type: "plan",
560
+ message: normalizedPlanMessage,
561
+ env,
562
+ homeDir,
563
+ nowIso,
564
+ });
565
+ comment = commented.comment;
566
+ }
567
+ const transitioned = await transitionJiraIssue({
568
+ targetPath,
569
+ outputDir,
570
+ workItemId,
571
+ issueKey: opened.issue.issueKey,
572
+ toStatus: "IN_PROGRESS",
573
+ actor,
574
+ reason: "Agent accepted work item and started remediation plan.",
575
+ env,
576
+ homeDir,
577
+ nowIso,
578
+ });
579
+ return {
580
+ ...transitioned,
581
+ created: opened.created,
582
+ comment,
583
+ };
584
+ }
585
+
586
+ export async function listJiraIssues({
587
+ targetPath = ".",
588
+ outputDir = "",
589
+ workItemId = "",
590
+ issueKey = "",
591
+ statuses = [],
592
+ limit = 50,
593
+ env,
594
+ homeDir,
595
+ nowIso = new Date().toISOString(),
596
+ } = {}) {
597
+ const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
598
+ const normalizedLimit = Math.max(1, Math.floor(Number(limit || 50)));
599
+ const normalizedWorkItemId = normalizeString(workItemId);
600
+ const normalizedIssueKey = normalizeString(issueKey);
601
+ const statusFilter = new Set(parseCsv(statuses).map((status) => normalizeStatus(status, "")).filter(Boolean));
602
+ const storage = await resolveJiraLifecycleStorage({
603
+ targetPath,
604
+ outputDir,
605
+ env,
606
+ homeDir,
607
+ });
608
+ const lifecycle = await loadLifecycle(storage.lifecyclePath, normalizedNow);
609
+ const filtered = lifecycle.issues.filter((issue) => {
610
+ if (normalizedWorkItemId && issue.workItemId !== normalizedWorkItemId) {
611
+ return false;
612
+ }
613
+ if (normalizedIssueKey && issue.issueKey !== normalizedIssueKey) {
614
+ return false;
615
+ }
616
+ if (statusFilter.size > 0 && !statusFilter.has(issue.status)) {
617
+ return false;
618
+ }
619
+ return true;
620
+ });
621
+ const sorted = [...filtered].sort((left, right) => {
622
+ const leftEpoch = Date.parse(String(left.updatedAt || "")) || 0;
623
+ const rightEpoch = Date.parse(String(right.updatedAt || "")) || 0;
624
+ return rightEpoch - leftEpoch;
625
+ });
626
+ return {
627
+ ...storage,
628
+ totalCount: lifecycle.issues.length,
629
+ visibleCount: sorted.length,
630
+ issues: sorted.slice(0, normalizedLimit),
631
+ };
632
+ }