sentinelayer-cli 0.6.2 → 0.8.1

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 (280) hide show
  1. package/README.md +1009 -996
  2. package/bin/create-sentinelayer.js +5 -5
  3. package/bin/sentinelayer-cli.js +4 -4
  4. package/bin/sl.js +5 -5
  5. package/package.json +64 -63
  6. package/src/agents/ai-governance/index.js +12 -0
  7. package/src/agents/ai-governance/tools/base.js +171 -0
  8. package/src/agents/ai-governance/tools/eval-regression.js +47 -0
  9. package/src/agents/ai-governance/tools/hitl-audit.js +81 -0
  10. package/src/agents/ai-governance/tools/index.js +52 -0
  11. package/src/agents/ai-governance/tools/prompt-drift.js +42 -0
  12. package/src/agents/ai-governance/tools/provenance-check.js +69 -0
  13. package/src/agents/backend/index.js +12 -0
  14. package/src/agents/backend/tools/base.js +189 -0
  15. package/src/agents/backend/tools/circuit-breaker-check.js +123 -0
  16. package/src/agents/backend/tools/idempotency-audit.js +105 -0
  17. package/src/agents/backend/tools/index.js +87 -0
  18. package/src/agents/backend/tools/retry-audit.js +132 -0
  19. package/src/agents/backend/tools/timeout-audit.js +144 -0
  20. package/src/agents/code-quality/index.js +12 -0
  21. package/src/agents/code-quality/tools/base.js +159 -0
  22. package/src/agents/code-quality/tools/complexity-measure.js +197 -0
  23. package/src/agents/code-quality/tools/coupling-analysis.js +81 -0
  24. package/src/agents/code-quality/tools/cycle-detect.js +49 -0
  25. package/src/agents/code-quality/tools/dep-graph.js +196 -0
  26. package/src/agents/code-quality/tools/index.js +89 -0
  27. package/src/agents/data-layer/index.js +12 -0
  28. package/src/agents/data-layer/tools/base.js +181 -0
  29. package/src/agents/data-layer/tools/index-audit.js +165 -0
  30. package/src/agents/data-layer/tools/index.js +83 -0
  31. package/src/agents/data-layer/tools/migration-scan.js +135 -0
  32. package/src/agents/data-layer/tools/query-explain.js +120 -0
  33. package/src/agents/data-layer/tools/tenancy-scan.js +166 -0
  34. package/src/agents/documentation/index.js +12 -0
  35. package/src/agents/documentation/tools/api-diff.js +91 -0
  36. package/src/agents/documentation/tools/base.js +151 -0
  37. package/src/agents/documentation/tools/dead-link-check.js +58 -0
  38. package/src/agents/documentation/tools/docstring-coverage.js +78 -0
  39. package/src/agents/documentation/tools/index.js +52 -0
  40. package/src/agents/documentation/tools/readme-freshness.js +61 -0
  41. package/src/agents/envelope/fix-cycle.js +45 -0
  42. package/src/agents/envelope/index.js +31 -0
  43. package/src/agents/envelope/loop.js +150 -0
  44. package/src/agents/envelope/pulse.js +18 -0
  45. package/src/agents/envelope/stream.js +40 -0
  46. package/src/agents/infrastructure/index.js +12 -0
  47. package/src/agents/infrastructure/tools/base.js +171 -0
  48. package/src/agents/infrastructure/tools/checkov-run.js +32 -0
  49. package/src/agents/infrastructure/tools/drift-detect.js +59 -0
  50. package/src/agents/infrastructure/tools/iam-least-priv-check.js +78 -0
  51. package/src/agents/infrastructure/tools/index.js +52 -0
  52. package/src/agents/infrastructure/tools/tflint-run.js +31 -0
  53. package/src/agents/jules/config/definition.js +160 -160
  54. package/src/agents/jules/config/system-prompt.js +182 -182
  55. package/src/agents/jules/error-intake.js +51 -51
  56. package/src/agents/jules/fix-cycle.js +17 -17
  57. package/src/agents/jules/loop.js +460 -450
  58. package/src/agents/jules/pulse.js +10 -10
  59. package/src/agents/jules/stream.js +187 -186
  60. package/src/agents/jules/swarm/file-scanner.js +74 -74
  61. package/src/agents/jules/swarm/index.js +11 -11
  62. package/src/agents/jules/swarm/orchestrator.js +362 -362
  63. package/src/agents/jules/swarm/pattern-hunter.js +123 -123
  64. package/src/agents/jules/swarm/sub-agent.js +315 -309
  65. package/src/agents/jules/tools/aidenid-email.js +189 -189
  66. package/src/agents/jules/tools/auth-audit.js +1708 -1691
  67. package/src/agents/jules/tools/dispatch.js +340 -335
  68. package/src/agents/jules/tools/file-edit.js +2 -2
  69. package/src/agents/jules/tools/file-read.js +2 -2
  70. package/src/agents/jules/tools/frontend-analyze.js +570 -570
  71. package/src/agents/jules/tools/glob.js +2 -2
  72. package/src/agents/jules/tools/grep.js +2 -2
  73. package/src/agents/jules/tools/index.js +29 -29
  74. package/src/agents/jules/tools/path-guards.js +2 -2
  75. package/src/agents/jules/tools/runtime-audit.js +507 -507
  76. package/src/agents/jules/tools/shell.js +2 -2
  77. package/src/agents/jules/tools/url-policy.js +100 -100
  78. package/src/agents/mode.js +113 -0
  79. package/src/agents/observability/index.js +12 -0
  80. package/src/agents/observability/tools/alert-audit.js +39 -0
  81. package/src/agents/observability/tools/base.js +181 -0
  82. package/src/agents/observability/tools/dashboard-gap.js +42 -0
  83. package/src/agents/observability/tools/index.js +54 -0
  84. package/src/agents/observability/tools/log-schema-check.js +74 -0
  85. package/src/agents/observability/tools/span-coverage.js +74 -0
  86. package/src/agents/persona-visuals.js +102 -61
  87. package/src/agents/release/index.js +12 -0
  88. package/src/agents/release/tools/base.js +181 -0
  89. package/src/agents/release/tools/changelog-diff.js +86 -0
  90. package/src/agents/release/tools/feature-flag-audit.js +126 -0
  91. package/src/agents/release/tools/index.js +61 -0
  92. package/src/agents/release/tools/rollback-verify.js +129 -0
  93. package/src/agents/release/tools/semver-check.js +109 -0
  94. package/src/agents/reliability/index.js +12 -0
  95. package/src/agents/reliability/tools/backpressure-check.js +129 -0
  96. package/src/agents/reliability/tools/base.js +181 -0
  97. package/src/agents/reliability/tools/chaos-probe.js +109 -0
  98. package/src/agents/reliability/tools/graceful-degradation-check.js +114 -0
  99. package/src/agents/reliability/tools/health-check-audit.js +111 -0
  100. package/src/agents/reliability/tools/index.js +87 -0
  101. package/src/agents/run-persona.js +109 -0
  102. package/src/agents/security/index.js +12 -0
  103. package/src/agents/security/tools/authz-audit.js +134 -0
  104. package/src/agents/security/tools/base.js +190 -0
  105. package/src/agents/security/tools/crypto-review.js +175 -0
  106. package/src/agents/security/tools/index.js +97 -0
  107. package/src/agents/security/tools/sast-scan.js +175 -0
  108. package/src/agents/security/tools/secrets-scan.js +216 -0
  109. package/src/agents/shared-tools/dispatch-core.js +320 -315
  110. package/src/agents/shared-tools/file-edit.js +180 -180
  111. package/src/agents/shared-tools/file-read.js +100 -100
  112. package/src/agents/shared-tools/glob.js +168 -168
  113. package/src/agents/shared-tools/grep.js +228 -228
  114. package/src/agents/shared-tools/index.js +46 -46
  115. package/src/agents/shared-tools/path-guards.js +161 -161
  116. package/src/agents/shared-tools/shell.js +383 -383
  117. package/src/agents/supply-chain/index.js +12 -0
  118. package/src/agents/supply-chain/tools/attestation-check.js +42 -0
  119. package/src/agents/supply-chain/tools/base.js +151 -0
  120. package/src/agents/supply-chain/tools/index.js +52 -0
  121. package/src/agents/supply-chain/tools/lockfile-integrity.js +73 -0
  122. package/src/agents/supply-chain/tools/package-verify.js +56 -0
  123. package/src/agents/supply-chain/tools/sbom-diff.js +34 -0
  124. package/src/agents/testing/index.js +12 -0
  125. package/src/agents/testing/tools/base.js +202 -0
  126. package/src/agents/testing/tools/coverage-gap.js +144 -0
  127. package/src/agents/testing/tools/flake-detect.js +125 -0
  128. package/src/agents/testing/tools/index.js +85 -0
  129. package/src/agents/testing/tools/mutation-test.js +143 -0
  130. package/src/agents/testing/tools/snapshot-diff.js +103 -0
  131. package/src/ai/aidenid.js +1021 -1009
  132. package/src/ai/client.js +553 -553
  133. package/src/ai/domain-target-store.js +268 -268
  134. package/src/ai/identity-store.js +270 -270
  135. package/src/ai/proxy.js +137 -137
  136. package/src/ai/site-store.js +145 -145
  137. package/src/audit/agents/architecture.js +180 -180
  138. package/src/audit/agents/compliance.js +179 -179
  139. package/src/audit/agents/documentation.js +165 -165
  140. package/src/audit/agents/performance.js +145 -145
  141. package/src/audit/agents/security.js +215 -215
  142. package/src/audit/agents/testing.js +172 -172
  143. package/src/audit/orchestrator.js +557 -557
  144. package/src/audit/package.js +204 -204
  145. package/src/audit/registry.js +284 -284
  146. package/src/audit/replay.js +103 -103
  147. package/src/auth/gate.js +428 -371
  148. package/src/auth/http.js +681 -611
  149. package/src/auth/service.js +1106 -1106
  150. package/src/auth/session-store.js +813 -813
  151. package/src/cli.js +257 -252
  152. package/src/commands/ai/identity-lifecycle.js +1338 -1338
  153. package/src/commands/ai/provision-governance.js +1272 -1272
  154. package/src/commands/ai/shared.js +147 -147
  155. package/src/commands/ai.js +11 -11
  156. package/src/commands/apply.js +12 -12
  157. package/src/commands/audit.js +1171 -1166
  158. package/src/commands/auth.js +419 -419
  159. package/src/commands/chat.js +184 -191
  160. package/src/commands/config.js +184 -184
  161. package/src/commands/cost.js +311 -311
  162. package/src/commands/daemon/core.js +850 -850
  163. package/src/commands/daemon/extended.js +1048 -1048
  164. package/src/commands/daemon/shared.js +213 -213
  165. package/src/commands/daemon.js +11 -11
  166. package/src/commands/guide.js +174 -174
  167. package/src/commands/ingest.js +58 -58
  168. package/src/commands/init.js +55 -55
  169. package/src/commands/legacy-args.js +20 -10
  170. package/src/commands/mcp.js +461 -461
  171. package/src/commands/omargate.js +63 -29
  172. package/src/commands/persona.js +65 -20
  173. package/src/commands/plugin.js +260 -260
  174. package/src/commands/policy.js +132 -132
  175. package/src/commands/prompt.js +238 -238
  176. package/src/commands/review.js +704 -704
  177. package/src/commands/scan.js +865 -872
  178. package/src/commands/session.js +1238 -0
  179. package/src/commands/spec.js +771 -716
  180. package/src/commands/swarm.js +651 -651
  181. package/src/commands/telemetry.js +202 -202
  182. package/src/commands/watch.js +511 -511
  183. package/src/config/agent-dictionary.js +182 -182
  184. package/src/config/io.js +56 -56
  185. package/src/config/paths.js +18 -18
  186. package/src/config/schema.js +55 -55
  187. package/src/config/service.js +184 -184
  188. package/src/coord/events-log.js +141 -0
  189. package/src/coord/handshake.js +719 -0
  190. package/src/coord/index.js +35 -0
  191. package/src/coord/paths.js +84 -0
  192. package/src/coord/priority.js +62 -0
  193. package/src/coord/tarjan.js +157 -0
  194. package/src/cost/budget.js +235 -235
  195. package/src/cost/history.js +188 -188
  196. package/src/cost/tokenizer.js +160 -0
  197. package/src/cost/tracker.js +232 -171
  198. package/src/daemon/artifact-lineage.js +896 -534
  199. package/src/daemon/assignment-ledger.js +1083 -770
  200. package/src/daemon/ast-drift.js +496 -0
  201. package/src/daemon/ast-parser-layer.js +258 -258
  202. package/src/daemon/budget-governor.js +633 -633
  203. package/src/daemon/callgraph-overlay.js +646 -646
  204. package/src/daemon/error-worker.js +1209 -626
  205. package/src/daemon/fix-cycle.js +384 -377
  206. package/src/daemon/hybrid-mapper.js +929 -929
  207. package/src/daemon/ingest-refresh.js +79 -11
  208. package/src/daemon/jira-lifecycle.js +767 -632
  209. package/src/daemon/operator-control.js +657 -657
  210. package/src/daemon/pulse.js +327 -327
  211. package/src/daemon/reliability-lane.js +471 -471
  212. package/src/daemon/scope-engine.js +1068 -0
  213. package/src/daemon/watchdog.js +971 -971
  214. package/src/events/schema.js +190 -0
  215. package/src/guide/generator.js +316 -316
  216. package/src/ingest/engine.js +933 -918
  217. package/src/ingest/ownership.js +380 -0
  218. package/src/interactive/index.js +97 -97
  219. package/src/legacy-cli.js +3228 -2994
  220. package/src/mcp/registry.js +695 -695
  221. package/src/memory/blackboard.js +301 -301
  222. package/src/memory/retrieval.js +581 -581
  223. package/src/orchestrator/kai-chen.js +126 -0
  224. package/src/plugin/manifest.js +553 -553
  225. package/src/policy/packs.js +144 -144
  226. package/src/prompt/generator.js +136 -118
  227. package/src/review/ai-review.js +672 -679
  228. package/src/review/compliance-pack.js +389 -0
  229. package/src/review/investor-dd-config.js +54 -0
  230. package/src/review/investor-dd-file-loop.js +303 -0
  231. package/src/review/investor-dd-file-router.js +406 -0
  232. package/src/review/investor-dd-html-report.js +233 -0
  233. package/src/review/investor-dd-notification.js +120 -0
  234. package/src/review/investor-dd-orchestrator.js +405 -0
  235. package/src/review/investor-dd-persona-runner.js +275 -0
  236. package/src/review/live-validator.js +253 -0
  237. package/src/review/local-review.js +1351 -1305
  238. package/src/review/omargate-interactive.js +68 -68
  239. package/src/review/omargate-orchestrator.js +492 -300
  240. package/src/review/persona-prompts.js +484 -296
  241. package/src/review/reconciliation-rules.js +329 -0
  242. package/src/review/replay.js +235 -235
  243. package/src/review/report.js +664 -664
  244. package/src/review/reproducibility-chain.js +136 -0
  245. package/src/review/scan-modes.js +147 -42
  246. package/src/review/spec-binding.js +487 -487
  247. package/src/scaffold/generator.js +67 -67
  248. package/src/scaffold/templates.js +150 -150
  249. package/src/scan/generator.js +418 -418
  250. package/src/scan/gh-secrets.js +107 -107
  251. package/src/session/agent-registry.js +359 -0
  252. package/src/session/analytics.js +479 -0
  253. package/src/session/daemon.js +1396 -0
  254. package/src/session/file-locks.js +666 -0
  255. package/src/session/paths.js +37 -0
  256. package/src/session/recap.js +567 -0
  257. package/src/session/redact.js +82 -0
  258. package/src/session/runtime-bridge.js +762 -0
  259. package/src/session/scoring.js +406 -0
  260. package/src/session/setup-guides.js +304 -0
  261. package/src/session/store.js +704 -0
  262. package/src/session/stream.js +333 -0
  263. package/src/session/sync.js +753 -0
  264. package/src/session/tasks.js +1054 -0
  265. package/src/session/templates.js +188 -0
  266. package/src/spec/generator.js +619 -519
  267. package/src/spec/regenerate.js +237 -237
  268. package/src/spec/templates.js +91 -91
  269. package/src/swarm/dashboard.js +247 -247
  270. package/src/swarm/factory.js +363 -363
  271. package/src/swarm/pentest.js +934 -934
  272. package/src/swarm/registry.js +419 -419
  273. package/src/swarm/report.js +158 -158
  274. package/src/swarm/runtime.js +569 -576
  275. package/src/swarm/scenario-dsl.js +272 -272
  276. package/src/telemetry/ledger.js +302 -302
  277. package/src/telemetry/session-tracker.js +234 -234
  278. package/src/telemetry/sync.js +203 -203
  279. package/src/ui/command-hints.js +13 -13
  280. package/src/ui/markdown.js +220 -220
@@ -1,632 +1,767 @@
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 { createAgentEvent } from "../events/schema.js";
5
+ import { appendToStream } from "../session/stream.js";
6
+ import { resolveAssignmentLedgerStorage } from "./assignment-ledger.js";
7
+ import { resolveErrorDaemonStorage } from "./error-worker.js";
8
+
9
+ const LIFECYCLE_SCHEMA_VERSION = "1.0.0";
10
+ const QUEUE_SCHEMA_VERSION = "1.0.0";
11
+
12
+ export const JIRA_STATUSES = Object.freeze([
13
+ "OPEN",
14
+ "IN_PROGRESS",
15
+ "BLOCKED",
16
+ "DONE",
17
+ "CANCELLED",
18
+ ]);
19
+
20
+ const JIRA_STATUS_SET = new Set(JIRA_STATUSES);
21
+ const JIRA_LIFECYCLE_PHASES = new Set([
22
+ "create",
23
+ "plan_comment",
24
+ "in_progress",
25
+ "checkpoint",
26
+ "blocked",
27
+ "resolved",
28
+ ]);
29
+
30
+ function normalizeString(value) {
31
+ return String(value || "").trim();
32
+ }
33
+
34
+ function normalizeIsoTimestamp(value, fallbackIso = new Date().toISOString()) {
35
+ const normalized = normalizeString(value);
36
+ if (!normalized) {
37
+ return fallbackIso;
38
+ }
39
+ const epoch = Date.parse(normalized);
40
+ if (!Number.isFinite(epoch)) {
41
+ return fallbackIso;
42
+ }
43
+ return new Date(epoch).toISOString();
44
+ }
45
+
46
+ function normalizeStatus(value, fallbackValue = "OPEN") {
47
+ const normalized = normalizeString(value).toUpperCase();
48
+ if (JIRA_STATUS_SET.has(normalized)) {
49
+ return normalized;
50
+ }
51
+ return fallbackValue;
52
+ }
53
+
54
+ function normalizeJiraLifecyclePhase(value) {
55
+ const normalized = normalizeString(value).toLowerCase();
56
+ if (!JIRA_LIFECYCLE_PHASES.has(normalized)) {
57
+ throw new Error(`phase must be one of: ${[...JIRA_LIFECYCLE_PHASES].join(", ")}.`);
58
+ }
59
+ return normalized;
60
+ }
61
+
62
+ function resolveTransitionPhase(status) {
63
+ const normalized = normalizeStatus(status, "OPEN");
64
+ if (normalized === "IN_PROGRESS") return "in_progress";
65
+ if (normalized === "BLOCKED") return "blocked";
66
+ if (normalized === "DONE" || normalized === "CANCELLED") return "resolved";
67
+ return "checkpoint";
68
+ }
69
+
70
+ function normalizeLabels(labels = []) {
71
+ if (!Array.isArray(labels)) {
72
+ return [];
73
+ }
74
+ const deduped = new Set();
75
+ for (const label of labels) {
76
+ const normalized = normalizeString(label);
77
+ if (normalized) {
78
+ deduped.add(normalized);
79
+ }
80
+ }
81
+ return [...deduped];
82
+ }
83
+
84
+ function normalizeComment(comment = {}, nowIso = new Date().toISOString()) {
85
+ return {
86
+ at: normalizeIsoTimestamp(comment.at, nowIso),
87
+ actor: normalizeString(comment.actor) || "omar-daemon",
88
+ type: normalizeString(comment.type) || "note",
89
+ message: normalizeString(comment.message),
90
+ };
91
+ }
92
+
93
+ function normalizeTransition(transition = {}, nowIso = new Date().toISOString()) {
94
+ return {
95
+ at: normalizeIsoTimestamp(transition.at, nowIso),
96
+ actor: normalizeString(transition.actor) || "omar-daemon",
97
+ from: normalizeStatus(transition.from, "OPEN"),
98
+ to: normalizeStatus(transition.to, "OPEN"),
99
+ reason: normalizeString(transition.reason) || null,
100
+ };
101
+ }
102
+
103
+ function normalizeIssue(issue = {}, nowIso = new Date().toISOString()) {
104
+ const createdAt = normalizeIsoTimestamp(issue.createdAt, nowIso);
105
+ return {
106
+ workItemId: normalizeString(issue.workItemId),
107
+ issueKey: normalizeString(issue.issueKey),
108
+ summary: normalizeString(issue.summary) || "Daemon work item remediation",
109
+ description: normalizeString(issue.description),
110
+ status: normalizeStatus(issue.status, "OPEN"),
111
+ labels: normalizeLabels(issue.labels),
112
+ assignee: normalizeString(issue.assignee) || null,
113
+ createdAt,
114
+ updatedAt: normalizeIsoTimestamp(issue.updatedAt, createdAt),
115
+ latestCommentAt: issue.latestCommentAt ? normalizeIsoTimestamp(issue.latestCommentAt, createdAt) : null,
116
+ comments: Array.isArray(issue.comments)
117
+ ? issue.comments.map((comment) => normalizeComment(comment, createdAt)).filter((comment) => comment.message)
118
+ : [],
119
+ transitions: Array.isArray(issue.transitions)
120
+ ? issue.transitions
121
+ .map((transition) => normalizeTransition(transition, createdAt))
122
+ .filter((transition) => transition.to)
123
+ : [],
124
+ };
125
+ }
126
+
127
+ function createInitialLifecycle(nowIso = new Date().toISOString()) {
128
+ return {
129
+ schemaVersion: LIFECYCLE_SCHEMA_VERSION,
130
+ generatedAt: normalizeIsoTimestamp(nowIso, nowIso),
131
+ issueCounter: 0,
132
+ issues: [],
133
+ };
134
+ }
135
+
136
+ function normalizeIssueKeyPrefix(value) {
137
+ const cleaned = normalizeString(value)
138
+ .toUpperCase()
139
+ .replace(/[^A-Z0-9]+/g, "");
140
+ if (!cleaned) {
141
+ return "SLD";
142
+ }
143
+ return cleaned.slice(0, 12);
144
+ }
145
+
146
+ function parseCsv(rawValue) {
147
+ if (!rawValue) {
148
+ return [];
149
+ }
150
+ return String(rawValue)
151
+ .split(",")
152
+ .map((item) => item.trim())
153
+ .filter(Boolean);
154
+ }
155
+
156
+ async function loadJsonFile(filePath, defaultFactory) {
157
+ try {
158
+ const raw = await fsp.readFile(filePath, "utf-8");
159
+ return JSON.parse(raw);
160
+ } catch (error) {
161
+ if (error && typeof error === "object" && error.code === "ENOENT") {
162
+ return defaultFactory();
163
+ }
164
+ throw error;
165
+ }
166
+ }
167
+
168
+ async function writeJsonFile(filePath, payload = {}) {
169
+ await fsp.mkdir(path.dirname(filePath), { recursive: true });
170
+ await fsp.writeFile(filePath, `${JSON.stringify(payload, null, 2)}\n`, "utf-8");
171
+ }
172
+
173
+ async function appendEvent(filePath, payload = {}) {
174
+ await fsp.mkdir(path.dirname(filePath), { recursive: true });
175
+ await fsp.appendFile(filePath, `${JSON.stringify(payload)}\n`, "utf-8");
176
+ }
177
+
178
+ async function loadQueue(queuePath, nowIso = new Date().toISOString()) {
179
+ const parsed = await loadJsonFile(queuePath, () => ({
180
+ schemaVersion: QUEUE_SCHEMA_VERSION,
181
+ generatedAt: normalizeIsoTimestamp(nowIso, nowIso),
182
+ items: [],
183
+ }));
184
+ return {
185
+ schemaVersion: normalizeString(parsed.schemaVersion) || QUEUE_SCHEMA_VERSION,
186
+ generatedAt: normalizeIsoTimestamp(parsed.generatedAt, nowIso),
187
+ items: Array.isArray(parsed.items) ? parsed.items : [],
188
+ };
189
+ }
190
+
191
+ async function loadLifecycle(lifecyclePath, nowIso = new Date().toISOString()) {
192
+ const parsed = await loadJsonFile(lifecyclePath, () => createInitialLifecycle(nowIso));
193
+ return {
194
+ schemaVersion: normalizeString(parsed.schemaVersion) || LIFECYCLE_SCHEMA_VERSION,
195
+ generatedAt: normalizeIsoTimestamp(parsed.generatedAt, nowIso),
196
+ issueCounter: Number(parsed.issueCounter || 0),
197
+ issues: Array.isArray(parsed.issues)
198
+ ? parsed.issues.map((issue) => normalizeIssue(issue, nowIso)).filter((issue) => issue.workItemId && issue.issueKey)
199
+ : [],
200
+ };
201
+ }
202
+
203
+ async function writeLifecycle(lifecyclePath, lifecycle = {}, nowIso = new Date().toISOString()) {
204
+ const normalized = {
205
+ schemaVersion: LIFECYCLE_SCHEMA_VERSION,
206
+ generatedAt: normalizeIsoTimestamp(nowIso, nowIso),
207
+ issueCounter: Math.max(0, Number(lifecycle.issueCounter || 0)),
208
+ issues: Array.isArray(lifecycle.issues)
209
+ ? lifecycle.issues
210
+ .map((issue) => normalizeIssue(issue, nowIso))
211
+ .filter((issue) => issue.workItemId && issue.issueKey)
212
+ : [],
213
+ };
214
+ await writeJsonFile(lifecyclePath, normalized);
215
+ return normalized;
216
+ }
217
+
218
+ function findIssueIndex(lifecycle = {}, { workItemId = "", issueKey = "" } = {}) {
219
+ const normalizedWorkItemId = normalizeString(workItemId);
220
+ const normalizedIssueKey = normalizeString(issueKey);
221
+ return lifecycle.issues.findIndex((issue) => {
222
+ if (normalizedIssueKey && issue.issueKey === normalizedIssueKey) {
223
+ return true;
224
+ }
225
+ if (normalizedWorkItemId && issue.workItemId === normalizedWorkItemId) {
226
+ return true;
227
+ }
228
+ return false;
229
+ });
230
+ }
231
+
232
+ function buildDefaultSummary(queueItem = {}, workItemId = "") {
233
+ const service = normalizeString(queueItem.service) || "unknown-service";
234
+ const endpoint = normalizeString(queueItem.endpoint) || "unknown-endpoint";
235
+ const errorCode = normalizeString(queueItem.errorCode) || "UNKNOWN_ERROR";
236
+ return `[${workItemId}] ${service} ${endpoint} ${errorCode}`.trim();
237
+ }
238
+
239
+ function buildDefaultDescription(queueItem = {}) {
240
+ const lines = [
241
+ `service: ${normalizeString(queueItem.service) || "unknown-service"}`,
242
+ `endpoint: ${normalizeString(queueItem.endpoint) || "unknown-endpoint"}`,
243
+ `error_code: ${normalizeString(queueItem.errorCode) || "UNKNOWN_ERROR"}`,
244
+ `severity: ${normalizeString(queueItem.severity) || "UNKNOWN"}`,
245
+ `message: ${normalizeString(queueItem.message) || "n/a"}`,
246
+ `fingerprint: ${normalizeString(queueItem.fingerprint) || "n/a"}`,
247
+ ];
248
+ return lines.join("\n");
249
+ }
250
+
251
+ async function syncIssueKeyToAssignment({
252
+ targetPath,
253
+ outputDir,
254
+ workItemId,
255
+ issueKey,
256
+ nowIso,
257
+ env,
258
+ homeDir,
259
+ } = {}) {
260
+ const assignmentStorage = await resolveAssignmentLedgerStorage({
261
+ targetPath,
262
+ outputDir,
263
+ env,
264
+ homeDir,
265
+ });
266
+ const rawLedger = await loadJsonFile(assignmentStorage.ledgerPath, () => null);
267
+ if (!rawLedger || !Array.isArray(rawLedger.assignments)) {
268
+ return;
269
+ }
270
+ const assignments = rawLedger.assignments.map((record) => ({
271
+ ...record,
272
+ workItemId: normalizeString(record.workItemId),
273
+ }));
274
+ const index = assignments.findIndex((record) => record.workItemId === workItemId);
275
+ if (index < 0) {
276
+ return;
277
+ }
278
+ assignments[index] = {
279
+ ...assignments[index],
280
+ jiraIssueKey: issueKey,
281
+ updatedAt: nowIso,
282
+ };
283
+ await writeJsonFile(assignmentStorage.ledgerPath, {
284
+ ...rawLedger,
285
+ generatedAt: nowIso,
286
+ assignments,
287
+ });
288
+ }
289
+
290
+ export async function resolveJiraLifecycleStorage({
291
+ targetPath = ".",
292
+ outputDir = "",
293
+ env,
294
+ homeDir,
295
+ } = {}) {
296
+ const daemonStorage = await resolveErrorDaemonStorage({
297
+ targetPath,
298
+ outputDir,
299
+ env,
300
+ homeDir,
301
+ });
302
+ return {
303
+ ...daemonStorage,
304
+ lifecyclePath: path.join(daemonStorage.baseDir, "jira-lifecycle.json"),
305
+ eventsPath: path.join(daemonStorage.baseDir, "jira-events.ndjson"),
306
+ };
307
+ }
308
+
309
+ export async function emitJiraLifecycleEvent(
310
+ sessionId,
311
+ {
312
+ phase,
313
+ ticketKey,
314
+ workItemId,
315
+ payload = {},
316
+ targetPath = ".",
317
+ nowIso = new Date().toISOString(),
318
+ } = {}
319
+ ) {
320
+ const normalizedSessionId = normalizeString(sessionId);
321
+ if (!normalizedSessionId) {
322
+ throw new Error("sessionId is required.");
323
+ }
324
+
325
+ const normalizedPayload =
326
+ payload && typeof payload === "object" && !Array.isArray(payload) ? { ...payload } : {};
327
+ const normalizedWorkItemId = normalizeString(workItemId);
328
+ const normalizedTicketKey = normalizeString(ticketKey);
329
+ const normalizedPhase = normalizeJiraLifecyclePhase(phase);
330
+ const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
331
+ const resolvedTargetPath = path.resolve(String(targetPath || "."));
332
+
333
+ const event = createAgentEvent({
334
+ event: "jira_lifecycle",
335
+ agentId: "omar-orchestrator",
336
+ sessionId: normalizedSessionId,
337
+ workItemId: normalizedWorkItemId || undefined,
338
+ ts: normalizedNow,
339
+ payload: {
340
+ phase: normalizedPhase,
341
+ ticketKey: normalizedTicketKey || null,
342
+ workItemId: normalizedWorkItemId || null,
343
+ ...normalizedPayload,
344
+ },
345
+ });
346
+
347
+ await appendToStream(normalizedSessionId, event, {
348
+ targetPath: resolvedTargetPath,
349
+ });
350
+ return event;
351
+ }
352
+
353
+ export async function openJiraIssue({
354
+ targetPath = ".",
355
+ outputDir = "",
356
+ sessionId = "",
357
+ workItemId,
358
+ summary = "",
359
+ description = "",
360
+ labels = [],
361
+ assignee = "",
362
+ issueKey = "",
363
+ issueKeyPrefix = "SLD",
364
+ actor = "omar-daemon",
365
+ env,
366
+ homeDir,
367
+ nowIso = new Date().toISOString(),
368
+ } = {}) {
369
+ const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
370
+ const normalizedWorkItemId = normalizeString(workItemId);
371
+ const normalizedSessionId = normalizeString(sessionId);
372
+ if (!normalizedWorkItemId) {
373
+ throw new Error("workItemId is required.");
374
+ }
375
+ const storage = await resolveJiraLifecycleStorage({
376
+ targetPath,
377
+ outputDir,
378
+ env,
379
+ homeDir,
380
+ });
381
+ const [queue, lifecycle] = await Promise.all([
382
+ loadQueue(storage.queuePath, normalizedNow),
383
+ loadLifecycle(storage.lifecyclePath, normalizedNow),
384
+ ]);
385
+ const queueItem = queue.items.find((item) => normalizeString(item.workItemId) === normalizedWorkItemId);
386
+ if (!queueItem) {
387
+ throw new Error(`Work item '${normalizedWorkItemId}' was not found in daemon queue.`);
388
+ }
389
+
390
+ const existingIndex = findIssueIndex(lifecycle, { workItemId: normalizedWorkItemId });
391
+ if (existingIndex >= 0) {
392
+ const existing = lifecycle.issues[existingIndex];
393
+ if (normalizedSessionId) {
394
+ await emitJiraLifecycleEvent(normalizedSessionId, {
395
+ phase: "checkpoint",
396
+ ticketKey: existing.issueKey,
397
+ workItemId: normalizedWorkItemId,
398
+ payload: {
399
+ status: existing.status,
400
+ reused: true,
401
+ },
402
+ targetPath,
403
+ nowIso: normalizedNow,
404
+ });
405
+ }
406
+ await syncIssueKeyToAssignment({
407
+ targetPath,
408
+ outputDir,
409
+ workItemId: normalizedWorkItemId,
410
+ issueKey: existing.issueKey,
411
+ nowIso: normalizedNow,
412
+ env,
413
+ homeDir,
414
+ });
415
+ return {
416
+ ...storage,
417
+ issue: existing,
418
+ created: false,
419
+ };
420
+ }
421
+
422
+ let normalizedIssueKey = normalizeString(issueKey);
423
+ if (!normalizedIssueKey) {
424
+ const prefix = normalizeIssueKeyPrefix(issueKeyPrefix);
425
+ lifecycle.issueCounter = Math.max(0, Number(lifecycle.issueCounter || 0)) + 1;
426
+ normalizedIssueKey = `${prefix}-${lifecycle.issueCounter}`;
427
+ }
428
+ const duplicateIssueKey = lifecycle.issues.some((issue) => issue.issueKey === normalizedIssueKey);
429
+ if (duplicateIssueKey) {
430
+ throw new Error(`issueKey '${normalizedIssueKey}' already exists in jira lifecycle registry.`);
431
+ }
432
+
433
+ const issue = normalizeIssue(
434
+ {
435
+ workItemId: normalizedWorkItemId,
436
+ issueKey: normalizedIssueKey,
437
+ summary: normalizeString(summary) || buildDefaultSummary(queueItem, normalizedWorkItemId),
438
+ description: normalizeString(description) || buildDefaultDescription(queueItem),
439
+ status: "OPEN",
440
+ labels: normalizeLabels([
441
+ "sentinelayer",
442
+ "omar-daemon",
443
+ `severity-${normalizeString(queueItem.severity || "unknown").toLowerCase()}`,
444
+ ...labels,
445
+ ]),
446
+ assignee: normalizeString(assignee) || null,
447
+ createdAt: normalizedNow,
448
+ updatedAt: normalizedNow,
449
+ latestCommentAt: null,
450
+ comments: [],
451
+ transitions: [],
452
+ },
453
+ normalizedNow
454
+ );
455
+ lifecycle.issues.push(issue);
456
+ const savedLifecycle = await writeLifecycle(storage.lifecyclePath, lifecycle, normalizedNow);
457
+ await appendEvent(storage.eventsPath, {
458
+ timestamp: normalizedNow,
459
+ eventType: "create_issue",
460
+ actor: normalizeString(actor) || "omar-daemon",
461
+ workItemId: normalizedWorkItemId,
462
+ issueKey: normalizedIssueKey,
463
+ status: "OPEN",
464
+ });
465
+ await syncIssueKeyToAssignment({
466
+ targetPath,
467
+ outputDir,
468
+ workItemId: normalizedWorkItemId,
469
+ issueKey: normalizedIssueKey,
470
+ nowIso: normalizedNow,
471
+ env,
472
+ homeDir,
473
+ });
474
+ if (normalizedSessionId) {
475
+ await emitJiraLifecycleEvent(normalizedSessionId, {
476
+ phase: "create",
477
+ ticketKey: normalizedIssueKey,
478
+ workItemId: normalizedWorkItemId,
479
+ payload: {
480
+ status: issue.status,
481
+ summary: issue.summary,
482
+ },
483
+ targetPath,
484
+ nowIso: normalizedNow,
485
+ });
486
+ }
487
+ return {
488
+ ...storage,
489
+ lifecycle: savedLifecycle,
490
+ issue,
491
+ created: true,
492
+ };
493
+ }
494
+
495
+ export async function commentJiraIssue({
496
+ targetPath = ".",
497
+ outputDir = "",
498
+ sessionId = "",
499
+ workItemId = "",
500
+ issueKey = "",
501
+ actor = "omar-daemon",
502
+ type = "note",
503
+ message,
504
+ env,
505
+ homeDir,
506
+ nowIso = new Date().toISOString(),
507
+ } = {}) {
508
+ const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
509
+ const normalizedMessage = normalizeString(message);
510
+ const normalizedSessionId = normalizeString(sessionId);
511
+ if (!normalizedMessage) {
512
+ throw new Error("message is required.");
513
+ }
514
+ const storage = await resolveJiraLifecycleStorage({
515
+ targetPath,
516
+ outputDir,
517
+ env,
518
+ homeDir,
519
+ });
520
+ const lifecycle = await loadLifecycle(storage.lifecyclePath, normalizedNow);
521
+ const issueIndex = findIssueIndex(lifecycle, { workItemId, issueKey });
522
+ if (issueIndex < 0) {
523
+ throw new Error("No jira lifecycle issue found for the provided workItemId/issueKey.");
524
+ }
525
+ const existing = lifecycle.issues[issueIndex];
526
+ const comment = normalizeComment(
527
+ {
528
+ at: normalizedNow,
529
+ actor,
530
+ type,
531
+ message: normalizedMessage,
532
+ },
533
+ normalizedNow
534
+ );
535
+ existing.comments = [...existing.comments, comment];
536
+ existing.latestCommentAt = normalizedNow;
537
+ existing.updatedAt = normalizedNow;
538
+ lifecycle.issues[issueIndex] = normalizeIssue(existing, normalizedNow);
539
+ const savedLifecycle = await writeLifecycle(storage.lifecyclePath, lifecycle, normalizedNow);
540
+ await appendEvent(storage.eventsPath, {
541
+ timestamp: normalizedNow,
542
+ eventType: "comment",
543
+ actor: normalizeString(actor) || "omar-daemon",
544
+ workItemId: existing.workItemId,
545
+ issueKey: existing.issueKey,
546
+ type: comment.type,
547
+ message: comment.message,
548
+ });
549
+ if (normalizedSessionId) {
550
+ await emitJiraLifecycleEvent(normalizedSessionId, {
551
+ phase: comment.type === "plan" ? "plan_comment" : "checkpoint",
552
+ ticketKey: existing.issueKey,
553
+ workItemId: existing.workItemId,
554
+ payload: {
555
+ commentType: comment.type,
556
+ status: lifecycle.issues[issueIndex].status,
557
+ message: comment.message,
558
+ },
559
+ targetPath,
560
+ nowIso: normalizedNow,
561
+ });
562
+ }
563
+ return {
564
+ ...storage,
565
+ lifecycle: savedLifecycle,
566
+ issue: lifecycle.issues[issueIndex],
567
+ comment,
568
+ };
569
+ }
570
+
571
+ export async function transitionJiraIssue({
572
+ targetPath = ".",
573
+ outputDir = "",
574
+ sessionId = "",
575
+ workItemId = "",
576
+ issueKey = "",
577
+ toStatus,
578
+ actor = "omar-daemon",
579
+ reason = "",
580
+ env,
581
+ homeDir,
582
+ nowIso = new Date().toISOString(),
583
+ } = {}) {
584
+ const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
585
+ const nextStatus = normalizeStatus(toStatus, "");
586
+ const normalizedSessionId = normalizeString(sessionId);
587
+ if (!nextStatus) {
588
+ throw new Error(`toStatus must be one of: ${JIRA_STATUSES.join(", ")}.`);
589
+ }
590
+ const storage = await resolveJiraLifecycleStorage({
591
+ targetPath,
592
+ outputDir,
593
+ env,
594
+ homeDir,
595
+ });
596
+ const lifecycle = await loadLifecycle(storage.lifecyclePath, normalizedNow);
597
+ const issueIndex = findIssueIndex(lifecycle, { workItemId, issueKey });
598
+ if (issueIndex < 0) {
599
+ throw new Error("No jira lifecycle issue found for the provided workItemId/issueKey.");
600
+ }
601
+ const existing = lifecycle.issues[issueIndex];
602
+ const transition = normalizeTransition(
603
+ {
604
+ at: normalizedNow,
605
+ actor,
606
+ from: existing.status,
607
+ to: nextStatus,
608
+ reason,
609
+ },
610
+ normalizedNow
611
+ );
612
+ existing.status = nextStatus;
613
+ existing.transitions = [...existing.transitions, transition];
614
+ existing.updatedAt = normalizedNow;
615
+ lifecycle.issues[issueIndex] = normalizeIssue(existing, normalizedNow);
616
+ const savedLifecycle = await writeLifecycle(storage.lifecyclePath, lifecycle, normalizedNow);
617
+ await appendEvent(storage.eventsPath, {
618
+ timestamp: normalizedNow,
619
+ eventType: "transition",
620
+ actor: normalizeString(actor) || "omar-daemon",
621
+ workItemId: existing.workItemId,
622
+ issueKey: existing.issueKey,
623
+ from: transition.from,
624
+ to: transition.to,
625
+ reason: transition.reason,
626
+ });
627
+ if (normalizedSessionId) {
628
+ await emitJiraLifecycleEvent(normalizedSessionId, {
629
+ phase: resolveTransitionPhase(nextStatus),
630
+ ticketKey: existing.issueKey,
631
+ workItemId: existing.workItemId,
632
+ payload: {
633
+ from: transition.from,
634
+ to: transition.to,
635
+ reason: transition.reason,
636
+ status: lifecycle.issues[issueIndex].status,
637
+ },
638
+ targetPath,
639
+ nowIso: normalizedNow,
640
+ });
641
+ }
642
+ return {
643
+ ...storage,
644
+ lifecycle: savedLifecycle,
645
+ issue: lifecycle.issues[issueIndex],
646
+ transition,
647
+ };
648
+ }
649
+
650
+ export async function startJiraLifecycle({
651
+ targetPath = ".",
652
+ outputDir = "",
653
+ sessionId = "",
654
+ workItemId,
655
+ actor = "omar-daemon",
656
+ assignee = "",
657
+ summary = "",
658
+ description = "",
659
+ labels = [],
660
+ planMessage,
661
+ issueKey = "",
662
+ issueKeyPrefix = "SLD",
663
+ env,
664
+ homeDir,
665
+ nowIso = new Date().toISOString(),
666
+ } = {}) {
667
+ const opened = await openJiraIssue({
668
+ targetPath,
669
+ outputDir,
670
+ sessionId,
671
+ workItemId,
672
+ actor,
673
+ assignee,
674
+ summary,
675
+ description,
676
+ labels,
677
+ issueKey,
678
+ issueKeyPrefix,
679
+ env,
680
+ homeDir,
681
+ nowIso,
682
+ });
683
+ const normalizedPlanMessage = normalizeString(planMessage);
684
+ let comment = null;
685
+ if (normalizedPlanMessage) {
686
+ const commented = await commentJiraIssue({
687
+ targetPath,
688
+ outputDir,
689
+ sessionId,
690
+ workItemId,
691
+ issueKey: opened.issue.issueKey,
692
+ actor,
693
+ type: "plan",
694
+ message: normalizedPlanMessage,
695
+ env,
696
+ homeDir,
697
+ nowIso,
698
+ });
699
+ comment = commented.comment;
700
+ }
701
+ const transitioned = await transitionJiraIssue({
702
+ targetPath,
703
+ outputDir,
704
+ sessionId,
705
+ workItemId,
706
+ issueKey: opened.issue.issueKey,
707
+ toStatus: "IN_PROGRESS",
708
+ actor,
709
+ reason: "Agent accepted work item and started remediation plan.",
710
+ env,
711
+ homeDir,
712
+ nowIso,
713
+ });
714
+ return {
715
+ ...transitioned,
716
+ created: opened.created,
717
+ comment,
718
+ };
719
+ }
720
+
721
+ export async function listJiraIssues({
722
+ targetPath = ".",
723
+ outputDir = "",
724
+ workItemId = "",
725
+ issueKey = "",
726
+ statuses = [],
727
+ limit = 50,
728
+ env,
729
+ homeDir,
730
+ nowIso = new Date().toISOString(),
731
+ } = {}) {
732
+ const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
733
+ const normalizedLimit = Math.max(1, Math.floor(Number(limit || 50)));
734
+ const normalizedWorkItemId = normalizeString(workItemId);
735
+ const normalizedIssueKey = normalizeString(issueKey);
736
+ const statusFilter = new Set(parseCsv(statuses).map((status) => normalizeStatus(status, "")).filter(Boolean));
737
+ const storage = await resolveJiraLifecycleStorage({
738
+ targetPath,
739
+ outputDir,
740
+ env,
741
+ homeDir,
742
+ });
743
+ const lifecycle = await loadLifecycle(storage.lifecyclePath, normalizedNow);
744
+ const filtered = lifecycle.issues.filter((issue) => {
745
+ if (normalizedWorkItemId && issue.workItemId !== normalizedWorkItemId) {
746
+ return false;
747
+ }
748
+ if (normalizedIssueKey && issue.issueKey !== normalizedIssueKey) {
749
+ return false;
750
+ }
751
+ if (statusFilter.size > 0 && !statusFilter.has(issue.status)) {
752
+ return false;
753
+ }
754
+ return true;
755
+ });
756
+ const sorted = [...filtered].sort((left, right) => {
757
+ const leftEpoch = Date.parse(String(left.updatedAt || "")) || 0;
758
+ const rightEpoch = Date.parse(String(right.updatedAt || "")) || 0;
759
+ return rightEpoch - leftEpoch;
760
+ });
761
+ return {
762
+ ...storage,
763
+ totalCount: lifecycle.issues.length,
764
+ visibleCount: sorted.length,
765
+ issues: sorted.slice(0, normalizedLimit),
766
+ };
767
+ }