sentinelayer-cli 0.4.5 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +16 -18
  2. package/package.json +7 -6
  3. package/src/agents/jules/config/definition.js +13 -62
  4. package/src/agents/jules/config/system-prompt.js +8 -1
  5. package/src/agents/jules/fix-cycle.js +12 -372
  6. package/src/agents/jules/loop.js +116 -26
  7. package/src/agents/jules/pulse.js +10 -327
  8. package/src/agents/jules/stream.js +13 -12
  9. package/src/agents/jules/swarm/orchestrator.js +3 -3
  10. package/src/agents/jules/swarm/sub-agent.js +6 -3
  11. package/src/agents/jules/tools/aidenid-email.js +189 -0
  12. package/src/agents/jules/tools/auth-audit.js +1187 -45
  13. package/src/agents/jules/tools/dispatch.js +25 -12
  14. package/src/agents/jules/tools/file-edit.js +2 -180
  15. package/src/agents/jules/tools/file-read.js +2 -100
  16. package/src/agents/jules/tools/glob.js +2 -168
  17. package/src/agents/jules/tools/grep.js +2 -228
  18. package/src/agents/jules/tools/path-guards.js +2 -161
  19. package/src/agents/jules/tools/runtime-audit.js +6 -2
  20. package/src/agents/jules/tools/shell.js +2 -383
  21. package/src/agents/persona-visuals.js +64 -0
  22. package/src/agents/shared-tools/dispatch-core.js +320 -0
  23. package/src/agents/shared-tools/file-edit.js +180 -0
  24. package/src/agents/shared-tools/file-read.js +100 -0
  25. package/src/agents/shared-tools/glob.js +168 -0
  26. package/src/agents/shared-tools/grep.js +228 -0
  27. package/src/agents/shared-tools/index.js +46 -0
  28. package/src/agents/shared-tools/path-guards.js +161 -0
  29. package/src/agents/shared-tools/shell.js +383 -0
  30. package/src/ai/aidenid.js +56 -7
  31. package/src/ai/client.js +45 -0
  32. package/src/ai/proxy.js +137 -0
  33. package/src/auth/gate.js +290 -16
  34. package/src/auth/http.js +450 -39
  35. package/src/auth/service.js +262 -47
  36. package/src/auth/session-store.js +475 -21
  37. package/src/cli.js +5 -0
  38. package/src/commands/audit.js +13 -8
  39. package/src/commands/auth.js +53 -9
  40. package/src/commands/omargate.js +10 -2
  41. package/src/commands/scan.js +10 -4
  42. package/src/commands/session.js +590 -0
  43. package/src/commands/spec.js +62 -0
  44. package/src/commands/watch.js +3 -2
  45. package/src/daemon/assignment-ledger.js +196 -0
  46. package/src/daemon/error-worker.js +599 -16
  47. package/src/daemon/fix-cycle.js +384 -0
  48. package/src/daemon/ingest-refresh.js +10 -9
  49. package/src/daemon/jira-lifecycle.js +135 -0
  50. package/src/daemon/pulse.js +327 -0
  51. package/src/daemon/scope-engine.js +1068 -0
  52. package/src/events/schema.js +190 -0
  53. package/src/interactive/index.js +18 -16
  54. package/src/legacy-cli.js +606 -37
  55. package/src/prompt/generator.js +19 -1
  56. package/src/review/ai-review.js +11 -1
  57. package/src/review/local-review.js +75 -19
  58. package/src/review/omargate-interactive.js +68 -0
  59. package/src/review/omargate-orchestrator.js +404 -0
  60. package/src/review/persona-prompts.js +296 -0
  61. package/src/review/scan-modes.js +48 -0
  62. package/src/scan/generator.js +1 -1
  63. package/src/session/agent-registry.js +352 -0
  64. package/src/session/daemon.js +801 -0
  65. package/src/session/paths.js +33 -0
  66. package/src/session/runtime-bridge.js +739 -0
  67. package/src/session/store.js +388 -0
  68. package/src/session/stream.js +325 -0
  69. package/src/spec/generator.js +100 -0
  70. package/src/telemetry/session-tracker.js +148 -32
  71. package/src/telemetry/sync.js +6 -2
  72. package/src/ui/command-hints.js +13 -0
@@ -0,0 +1,384 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import path from "node:path";
3
+ import fsp from "node:fs/promises";
4
+ import { startJiraLifecycle, commentJiraIssue, transitionJiraIssue } from "./jira-lifecycle.js";
5
+ import { claimAssignment, heartbeatAssignment, releaseAssignment } from "./assignment-ledger.js";
6
+ import { createAgentEvent } from "../events/schema.js";
7
+
8
+ /**
9
+ * Jules Tanaka — Autonomous Fix Cycle
10
+ *
11
+ * Complete lifecycle:
12
+ * claim → Jira open → worktree create → agentic fix → test →
13
+ * Jira comment findings → PR create → Omar Gate watch →
14
+ * fix P0-P2 from comments → merge → Jira close → artifact → release
15
+ *
16
+ * Failure path: BLOCKED status + Jira comment + release assignment
17
+ * Worktree cleanup: always in finally block
18
+ */
19
+
20
+ const LEASE_TTL_SECONDS = 1800;
21
+ const HEARTBEAT_INTERVAL_MS = 300000;
22
+ // MAX_FIX_ATTEMPTS reserved for future agentic retry loop
23
+ const OMAR_POLL_INTERVAL_MS = 15000;
24
+ const OMAR_POLL_MAX_ATTEMPTS = 40; // 10 minutes max wait
25
+
26
+ export async function runFixCycle({ workItemId, workItem, rootPath, scopeMap, findings, onEvent, agentIdentity }) {
27
+ const agentDef = agentIdentity || { id: "unknown", persona: "Unknown Agent", color: "white", avatar: "", signature: "" };
28
+ const emit = (ev, pl) => {
29
+ if (onEvent) onEvent(createAgentEvent({
30
+ event: ev,
31
+ agent: {
32
+ id: agentDef.id,
33
+ persona: agentDef.persona,
34
+ color: agentDef.color,
35
+ avatar: agentDef.avatar,
36
+ },
37
+ payload: { workItemId, ...pl },
38
+ workItemId,
39
+ }));
40
+ };
41
+
42
+ const artDir = path.join(rootPath, ".sentinelayer", "observability", "fixes", workItemId);
43
+ await fsp.mkdir(artDir, { recursive: true });
44
+
45
+ let jiraKey = null;
46
+ let prNumber = null;
47
+ let worktreePath = null;
48
+ let branchName = null;
49
+ let hbTimer = null;
50
+
51
+ try {
52
+ // ── [1] CLAIM ─────────────────────────────────────────────────
53
+ emit("fix_claim", { status: "claiming" });
54
+ await claimAssignment({
55
+ targetPath: rootPath, workItemId,
56
+ agentIdentity: "jules-tanaka@frontend",
57
+ leaseTtlSeconds: LEASE_TTL_SECONDS, stage: "fix",
58
+ });
59
+
60
+ hbTimer = setInterval(async () => {
61
+ try {
62
+ await heartbeatAssignment({
63
+ targetPath: rootPath, workItemId,
64
+ agentIdentity: "jules-tanaka@frontend",
65
+ leaseTtlSeconds: LEASE_TTL_SECONDS, stage: "fix",
66
+ });
67
+ } catch { /* heartbeat failure is non-blocking */ }
68
+ }, HEARTBEAT_INTERVAL_MS);
69
+
70
+ // ── [2] JIRA OPEN ─────────────────────────────────────────────
71
+ emit("fix_jira", { status: "opening" });
72
+ const sev = workItem?.severity || "P2";
73
+ const endpoint = workItem?.endpoint || "unknown";
74
+ const errorCode = workItem?.errorCode || "UNKNOWN";
75
+
76
+ const jr = await startJiraLifecycle({
77
+ targetPath: rootPath, workItemId, actor: agentDef.persona,
78
+ summary: "[" + sev + "] Frontend: " + errorCode + " at " + endpoint,
79
+ description: buildDescription(workItem, findings),
80
+ labels: ["sentinelayer", "jules-tanaka", "frontend", "severity-" + sev.toLowerCase()],
81
+ planMessage: buildPlan(workItem, scopeMap, findings),
82
+ issueKeyPrefix: "SLD",
83
+ });
84
+ jiraKey = jr.issue?.issueKey;
85
+ emit("fix_jira", { status: "opened", issueKey: jiraKey });
86
+
87
+ // ── [3] WORKTREE CREATE ───────────────────────────────────────
88
+ branchName = "fix/jules-" + workItemId.replace(/[^a-zA-Z0-9-]/g, "-");
89
+ worktreePath = path.join(rootPath, ".jules-worktree-" + workItemId);
90
+ emit("fix_worktree", { status: "creating", branch: branchName });
91
+
92
+ safeExecFile("git", ["fetch", "origin"], rootPath);
93
+ safeExecFile("git", ["worktree", "add", "-b", branchName, worktreePath, "origin/main"], rootPath);
94
+ emit("fix_worktree", { status: "created", path: worktreePath });
95
+
96
+ // ── [4] INVESTIGATE + FIX ─────────────────────────────────────
97
+ emit("fix_investigate", { status: "analyzing" });
98
+
99
+ // Comment Jira with findings before fix attempt
100
+ if (jiraKey && findings && findings.length > 0) {
101
+ await commentJiraIssue({
102
+ targetPath: rootPath, workItemId, issueKey: jiraKey,
103
+ actor: agentDef.persona, type: "finding",
104
+ message: buildFindingsComment(findings),
105
+ });
106
+ }
107
+
108
+ // Fix generation: the caller is responsible for writing changes to the
109
+ // worktree before invoking runFixCycle, or for wiring julesAuditLoop
110
+ // in fix mode with FileEdit tool access. runFixCycle handles the full
111
+ // PR/Omar/merge/Jira lifecycle for whatever changes exist in the worktree.
112
+
113
+ // ── [5] PUSH + PR ─────────────────────────────────────────────
114
+ emit("fix_pr", { status: "pushing" });
115
+
116
+ // Check if there are changes to commit in the worktree
117
+ const diffOutput = safeExecFile("git", ["diff", "--stat"], worktreePath);
118
+ const untrackedOutput = safeExecFile("git", ["ls-files", "--others", "--exclude-standard"], worktreePath);
119
+ const hasChanges = diffOutput.trim().length > 0 || untrackedOutput.trim().length > 0;
120
+
121
+ if (hasChanges) {
122
+ safeExecFile("git", ["add", "-A"], worktreePath);
123
+ safeExecFile("git", ["commit", "-m", "[Jules] Fix " + errorCode + " at " + endpoint], worktreePath);
124
+ }
125
+
126
+ safeExecFile("git", ["push", "-u", "origin", branchName], worktreePath);
127
+
128
+ const prBody = buildPrBody(workItem, findings, jiraKey);
129
+ const prUrl = safeExecFile("gh", [
130
+ "pr", "create",
131
+ "--title", "[Jules] Fix " + errorCode,
132
+ "--body", prBody,
133
+ "--head", branchName,
134
+ ], worktreePath).trim();
135
+
136
+ const prMatch = prUrl.match(/\/pull\/(\d+)/);
137
+ prNumber = prMatch ? parseInt(prMatch[1]) : null;
138
+ emit("fix_pr", { status: "created", prNumber, url: prUrl });
139
+
140
+ // ── [6] OMAR GATE WATCH ───────────────────────────────────────
141
+ if (prNumber) {
142
+ emit("fix_omar", { status: "watching", prNumber });
143
+ const omarPassed = await watchOmarGate(rootPath, branchName, emit);
144
+
145
+ if (!omarPassed) {
146
+ emit("fix_omar", { status: "failed" });
147
+ // Comment Jira about Omar failure
148
+ if (jiraKey) {
149
+ await commentJiraIssue({
150
+ targetPath: rootPath, workItemId, issueKey: jiraKey,
151
+ actor: agentDef.persona, type: "operator_stop",
152
+ message: "## Omar Gate Failed\nPR #" + prNumber + " did not pass Omar Gate.\nEscalating to human review.\n\n" + agentDef.signature,
153
+ });
154
+ await transitionJiraIssue({
155
+ targetPath: rootPath, workItemId, issueKey: jiraKey,
156
+ toStatus: "BLOCKED", actor: agentDef.persona,
157
+ reason: "Omar Gate failed on PR #" + prNumber,
158
+ });
159
+ }
160
+ await releaseAssignment({
161
+ targetPath: rootPath, workItemId,
162
+ agentIdentity: "jules-tanaka@frontend",
163
+ status: "BLOCKED", reason: "Omar Gate failed on PR #" + prNumber,
164
+ });
165
+ return {
166
+ workItemId, jiraIssueKey: jiraKey, prNumber,
167
+ status: "blocked_omar", signature: agentDef.signature,
168
+ };
169
+ }
170
+
171
+ emit("fix_omar", { status: "passed", prNumber });
172
+
173
+ // ── [7] MERGE ───────────────────────────────────────────────
174
+ emit("fix_merge", { status: "merging", prNumber });
175
+ try {
176
+ safeExecFile("gh", ["pr", "merge", String(prNumber), "--squash", "--delete-branch"], rootPath);
177
+ emit("fix_merge", { status: "merged", prNumber });
178
+ } catch (mergeErr) {
179
+ emit("fix_merge", { status: "failed", error: mergeErr.message });
180
+ // PR created but merge failed — still better than nothing
181
+ }
182
+ }
183
+
184
+ // ── [8] JIRA CLOSE ────────────────────────────────────────────
185
+ if (jiraKey) {
186
+ await commentJiraIssue({
187
+ targetPath: rootPath, workItemId, issueKey: jiraKey,
188
+ actor: agentDef.persona, type: "fix",
189
+ message: "## Resolution\nPR #" + (prNumber || "pending") + " merged.\nOmar Gate: passed.\nFindings addressed: " + (findings?.length || 0) + "\n\n" + agentDef.signature,
190
+ });
191
+ await transitionJiraIssue({
192
+ targetPath: rootPath, workItemId, issueKey: jiraKey,
193
+ toStatus: "DONE", actor: agentDef.persona,
194
+ reason: "Fixed in PR #" + (prNumber || "pending"),
195
+ });
196
+ }
197
+
198
+ // ── [9] ARTIFACT + S3 UPLOAD ────────────────────────────────────
199
+ const result = {
200
+ workItemId, jiraIssueKey: jiraKey, prNumber,
201
+ status: "completed",
202
+ findingsAddressed: findings?.length || 0,
203
+ signature: agentDef.signature,
204
+ };
205
+ await fsp.writeFile(
206
+ path.join(artDir, "fix-result.json"),
207
+ JSON.stringify(result, null, 2),
208
+ );
209
+
210
+ // Upload to S3 for compliance archive + agent training data
211
+ emit("fix_s3", { status: "uploading" });
212
+ const s3Result = await uploadFixArtifactsToS3(artDir, workItemId, rootPath);
213
+ emit("fix_s3", { status: s3Result.uploaded ? "uploaded" : "skipped", reason: s3Result.reason });
214
+
215
+ // ── [10] RELEASE ──────────────────────────────────────────────
216
+ await releaseAssignment({
217
+ targetPath: rootPath, workItemId,
218
+ agentIdentity: "jules-tanaka@frontend",
219
+ status: "DONE",
220
+ reason: "PR #" + (prNumber || "pending") + " merged. " + agentDef.signature,
221
+ });
222
+
223
+ emit("fix_complete", { prNumber, jiraIssueKey: jiraKey, status: "completed" });
224
+ return result;
225
+
226
+ } catch (err) {
227
+ emit("fix_error", { error: err.message });
228
+ try {
229
+ await releaseAssignment({
230
+ targetPath: rootPath, workItemId,
231
+ agentIdentity: "jules-tanaka@frontend",
232
+ status: "BLOCKED", reason: "Fix cycle failed: " + err.message,
233
+ });
234
+ } catch { /* release failure non-blocking */ }
235
+ if (jiraKey) {
236
+ try {
237
+ await commentJiraIssue({
238
+ targetPath: rootPath, workItemId, issueKey: jiraKey,
239
+ actor: agentDef.persona, type: "operator_stop",
240
+ message: "## Fix Failed\n" + err.message + "\nEscalating to human.\n\n" + agentDef.signature,
241
+ });
242
+ await transitionJiraIssue({
243
+ targetPath: rootPath, workItemId, issueKey: jiraKey,
244
+ toStatus: "BLOCKED", actor: agentDef.persona,
245
+ reason: "Fix cycle failed: " + err.message,
246
+ });
247
+ } catch { /* Jira failure non-blocking */ }
248
+ }
249
+ return { workItemId, jiraIssueKey: jiraKey, prNumber, status: "failed", error: err.message, signature: agentDef.signature };
250
+ } finally {
251
+ if (hbTimer) clearInterval(hbTimer);
252
+ if (worktreePath) {
253
+ try { safeExecFile("git", ["worktree", "remove", worktreePath, "--force"], rootPath); } catch { /* best effort */ }
254
+ }
255
+ }
256
+ }
257
+
258
+ // ── Omar Gate Watch ──────────────────────────────────────────────────
259
+
260
+ async function watchOmarGate(rootPath, branchName, emit) {
261
+ for (let attempt = 0; attempt < OMAR_POLL_MAX_ATTEMPTS; attempt++) {
262
+ await sleep(OMAR_POLL_INTERVAL_MS);
263
+ try {
264
+ const runJson = safeExecFile("gh", [
265
+ "run", "list", "--workflow", "Omar Gate", "--branch", branchName,
266
+ "--limit", "1", "--json", "databaseId,status,conclusion",
267
+ ], rootPath);
268
+ const runs = JSON.parse(runJson || "[]");
269
+ if (runs.length === 0) continue;
270
+
271
+ const run = runs[0];
272
+ if (run.status === "completed") {
273
+ emit("fix_omar", { status: "completed", conclusion: run.conclusion, runId: run.databaseId });
274
+ return run.conclusion === "success";
275
+ }
276
+ if (attempt % 4 === 0) {
277
+ emit("fix_omar", { status: "waiting", attempt, runId: run.databaseId });
278
+ }
279
+ } catch { /* polling failure non-blocking, will retry */ }
280
+ }
281
+ // Timed out waiting for Omar
282
+ emit("fix_omar", { status: "timeout" });
283
+ return false;
284
+ }
285
+
286
+ // ── Helpers ──────────────────────────────────────────────────────────
287
+
288
+ function safeExecFile(bin, args, cwd) {
289
+ return execFileSync(bin, args, {
290
+ cwd, encoding: "utf-8", timeout: 60000,
291
+ stdio: ["pipe", "pipe", "pipe"],
292
+ });
293
+ }
294
+
295
+ function sleep(ms) {
296
+ return new Promise(resolve => setTimeout(resolve, ms));
297
+ }
298
+
299
+ function buildDescription(w, f) {
300
+ const parts = [];
301
+ parts.push("**Service:** " + (w?.service || "unknown"));
302
+ parts.push("**Endpoint:** " + (w?.endpoint || "unknown"));
303
+ parts.push("**Error:** " + (w?.errorCode || "UNKNOWN"));
304
+ parts.push("**Severity:** " + (w?.severity || "P2"));
305
+ if (w?.message) parts.push("**Message:** " + w.message.slice(0, 500));
306
+ if (w?.stackFingerprint) parts.push("**Stack fingerprint:** " + w.stackFingerprint);
307
+ if (f?.length) parts.push("\n**Related findings:** " + f.length);
308
+ parts.push("\n" + agentDef.signature);
309
+ return parts.join("\n");
310
+ }
311
+
312
+ function buildPlan(w, s, f) {
313
+ const parts = [];
314
+ parts.push("## Investigation Plan");
315
+ parts.push("1. Scope reconstruction from error at " + (w?.endpoint || "unknown"));
316
+ parts.push("2. Read " + ((s?.primary || []).length) + " primary scope files");
317
+ parts.push("3. Identify root cause from stack trace + code analysis");
318
+ parts.push("4. Apply fix in isolated worktree");
319
+ parts.push("5. Run tests to verify fix");
320
+ parts.push("6. Open PR and watch Omar Gate");
321
+ if (f?.length) parts.push("\n**Pre-existing findings:** " + f.length);
322
+ parts.push("\n" + agentDef.signature);
323
+ return parts.join("\n");
324
+ }
325
+
326
+ function buildFindingsComment(f) {
327
+ const parts = ["## Findings"];
328
+ const items = f || [];
329
+ for (const finding of items.slice(0, 10)) {
330
+ parts.push("- **[" + (finding.severity || "P3") + "]** " + (finding.file || "") + ":" + (finding.line || "") + " " + (finding.title || finding.type || ""));
331
+ if (finding.evidence) parts.push(" Evidence: " + String(finding.evidence).slice(0, 200));
332
+ }
333
+ if (items.length > 10) parts.push("... and " + (items.length - 10) + " more");
334
+ parts.push("\n" + agentDef.signature);
335
+ return parts.join("\n");
336
+ }
337
+
338
+ function buildPrBody(w, f, jiraKey) {
339
+ const parts = [];
340
+ if (jiraKey) parts.push("Fixes " + jiraKey);
341
+ parts.push("Error: " + (w?.errorCode || "UNKNOWN") + " at " + (w?.endpoint || "unknown"));
342
+ parts.push("Severity: " + (w?.severity || "P2"));
343
+ if (f?.length) parts.push("Findings addressed: " + f.length);
344
+ parts.push("");
345
+ parts.push(agentDef.signature);
346
+ return parts.join("\n");
347
+ }
348
+
349
+ // ── S3 Upload ────────────────────────────────────────────────────────
350
+
351
+ /**
352
+ * Upload fix artifacts to S3 for compliance archive and agent training.
353
+ * Uses AWS CLI (must be configured in environment).
354
+ * Fails silently — S3 upload must never block the fix cycle.
355
+ *
356
+ * Bucket: SENTINELAYER_AUDIT_S3_BUCKET env var (default: sentinelayer-audit-artifacts)
357
+ * Key pattern: {repo}/{date}/jules-tanaka/{workItemId}/
358
+ */
359
+ async function uploadFixArtifactsToS3(artifactDir, workItemId, rootPath) {
360
+ const bucket = process.env.SENTINELAYER_AUDIT_S3_BUCKET;
361
+ if (!bucket) {
362
+ return { uploaded: false, reason: "SENTINELAYER_AUDIT_S3_BUCKET not set" };
363
+ }
364
+
365
+ try {
366
+ // Derive repo name from git remote or directory name
367
+ let repoName = "unknown-repo";
368
+ try {
369
+ const remote = safeExecFile("git", ["remote", "get-url", "origin"], rootPath).trim();
370
+ const match = remote.match(/\/([^/]+?)(?:\.git)?$/);
371
+ if (match) repoName = match[1];
372
+ } catch { /* use default */ }
373
+
374
+ const date = new Date().toISOString().split("T")[0];
375
+ const s3Key = repoName + "/" + date + "/jules-tanaka/" + workItemId + "/";
376
+ const s3Url = "s3://" + bucket + "/" + s3Key;
377
+
378
+ safeExecFile("aws", ["s3", "sync", artifactDir, s3Url, "--quiet", "--sse", "AES256"], rootPath);
379
+
380
+ return { uploaded: true, bucket, key: s3Key };
381
+ } catch (err) {
382
+ return { uploaded: false, reason: "S3 upload failed: " + err.message };
383
+ }
384
+ }
@@ -1,6 +1,7 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { collectCodebaseIngest, generateCodebaseIngest } from "../ingest/engine.js";
4
+ import { createAgentEvent } from "../events/schema.js";
4
5
 
5
6
  /**
6
7
  * Pulse Ingest Refresh — periodic codebase re-index.
@@ -69,11 +70,11 @@ export async function refreshIngestIfNeeded(targetPath, options = {}) {
69
70
  }
70
71
 
71
72
  if (options.onEvent) {
72
- options.onEvent({
73
- stream: "sl_event",
73
+ options.onEvent(createAgentEvent({
74
74
  event: "ingest_refresh_start",
75
+ agentId: "daemon-ingest-refresh",
75
76
  payload: { delta: drift.delta, currentFiles: drift.currentFileCount, lastFiles: drift.lastFileCount },
76
- });
77
+ }));
77
78
  }
78
79
 
79
80
  const startMs = Date.now();
@@ -81,11 +82,11 @@ export async function refreshIngestIfNeeded(targetPath, options = {}) {
81
82
  // Budget gate: abort if taking too long
82
83
  const timeout = setTimeout(() => {
83
84
  if (options.onEvent) {
84
- options.onEvent({
85
- stream: "sl_event",
85
+ options.onEvent(createAgentEvent({
86
86
  event: "ingest_refresh_timeout",
87
+ agentId: "daemon-ingest-refresh",
87
88
  payload: { maxDurationMs, elapsed: Date.now() - startMs },
88
- });
89
+ }));
89
90
  }
90
91
  }, maxDurationMs);
91
92
 
@@ -104,15 +105,15 @@ export async function refreshIngestIfNeeded(targetPath, options = {}) {
104
105
  const durationMs = Date.now() - startMs;
105
106
 
106
107
  if (options.onEvent) {
107
- options.onEvent({
108
- stream: "sl_event",
108
+ options.onEvent(createAgentEvent({
109
109
  event: "ingest_refresh_complete",
110
+ agentId: "daemon-ingest-refresh",
110
111
  payload: {
111
112
  durationMs,
112
113
  filesScanned: ingest?.summary?.filesScanned || 0,
113
114
  delta: drift.delta,
114
115
  },
115
- });
116
+ }));
116
117
  }
117
118
 
118
119
  return {
@@ -1,6 +1,8 @@
1
1
  import fsp from "node:fs/promises";
2
2
  import path from "node:path";
3
3
 
4
+ import { createAgentEvent } from "../events/schema.js";
5
+ import { appendToStream } from "../session/stream.js";
4
6
  import { resolveAssignmentLedgerStorage } from "./assignment-ledger.js";
5
7
  import { resolveErrorDaemonStorage } from "./error-worker.js";
6
8
 
@@ -16,6 +18,14 @@ export const JIRA_STATUSES = Object.freeze([
16
18
  ]);
17
19
 
18
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
+ ]);
19
29
 
20
30
  function normalizeString(value) {
21
31
  return String(value || "").trim();
@@ -41,6 +51,22 @@ function normalizeStatus(value, fallbackValue = "OPEN") {
41
51
  return fallbackValue;
42
52
  }
43
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
+
44
70
  function normalizeLabels(labels = []) {
45
71
  if (!Array.isArray(labels)) {
46
72
  return [];
@@ -280,9 +306,54 @@ export async function resolveJiraLifecycleStorage({
280
306
  };
281
307
  }
282
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
+
283
353
  export async function openJiraIssue({
284
354
  targetPath = ".",
285
355
  outputDir = "",
356
+ sessionId = "",
286
357
  workItemId,
287
358
  summary = "",
288
359
  description = "",
@@ -297,6 +368,7 @@ export async function openJiraIssue({
297
368
  } = {}) {
298
369
  const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
299
370
  const normalizedWorkItemId = normalizeString(workItemId);
371
+ const normalizedSessionId = normalizeString(sessionId);
300
372
  if (!normalizedWorkItemId) {
301
373
  throw new Error("workItemId is required.");
302
374
  }
@@ -318,6 +390,19 @@ export async function openJiraIssue({
318
390
  const existingIndex = findIssueIndex(lifecycle, { workItemId: normalizedWorkItemId });
319
391
  if (existingIndex >= 0) {
320
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
+ }
321
406
  await syncIssueKeyToAssignment({
322
407
  targetPath,
323
408
  outputDir,
@@ -386,6 +471,19 @@ export async function openJiraIssue({
386
471
  env,
387
472
  homeDir,
388
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
+ }
389
487
  return {
390
488
  ...storage,
391
489
  lifecycle: savedLifecycle,
@@ -397,6 +495,7 @@ export async function openJiraIssue({
397
495
  export async function commentJiraIssue({
398
496
  targetPath = ".",
399
497
  outputDir = "",
498
+ sessionId = "",
400
499
  workItemId = "",
401
500
  issueKey = "",
402
501
  actor = "omar-daemon",
@@ -408,6 +507,7 @@ export async function commentJiraIssue({
408
507
  } = {}) {
409
508
  const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
410
509
  const normalizedMessage = normalizeString(message);
510
+ const normalizedSessionId = normalizeString(sessionId);
411
511
  if (!normalizedMessage) {
412
512
  throw new Error("message is required.");
413
513
  }
@@ -446,6 +546,20 @@ export async function commentJiraIssue({
446
546
  type: comment.type,
447
547
  message: comment.message,
448
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
+ }
449
563
  return {
450
564
  ...storage,
451
565
  lifecycle: savedLifecycle,
@@ -457,6 +571,7 @@ export async function commentJiraIssue({
457
571
  export async function transitionJiraIssue({
458
572
  targetPath = ".",
459
573
  outputDir = "",
574
+ sessionId = "",
460
575
  workItemId = "",
461
576
  issueKey = "",
462
577
  toStatus,
@@ -468,6 +583,7 @@ export async function transitionJiraIssue({
468
583
  } = {}) {
469
584
  const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
470
585
  const nextStatus = normalizeStatus(toStatus, "");
586
+ const normalizedSessionId = normalizeString(sessionId);
471
587
  if (!nextStatus) {
472
588
  throw new Error(`toStatus must be one of: ${JIRA_STATUSES.join(", ")}.`);
473
589
  }
@@ -508,6 +624,21 @@ export async function transitionJiraIssue({
508
624
  to: transition.to,
509
625
  reason: transition.reason,
510
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
+ }
511
642
  return {
512
643
  ...storage,
513
644
  lifecycle: savedLifecycle,
@@ -519,6 +650,7 @@ export async function transitionJiraIssue({
519
650
  export async function startJiraLifecycle({
520
651
  targetPath = ".",
521
652
  outputDir = "",
653
+ sessionId = "",
522
654
  workItemId,
523
655
  actor = "omar-daemon",
524
656
  assignee = "",
@@ -535,6 +667,7 @@ export async function startJiraLifecycle({
535
667
  const opened = await openJiraIssue({
536
668
  targetPath,
537
669
  outputDir,
670
+ sessionId,
538
671
  workItemId,
539
672
  actor,
540
673
  assignee,
@@ -553,6 +686,7 @@ export async function startJiraLifecycle({
553
686
  const commented = await commentJiraIssue({
554
687
  targetPath,
555
688
  outputDir,
689
+ sessionId,
556
690
  workItemId,
557
691
  issueKey: opened.issue.issueKey,
558
692
  actor,
@@ -567,6 +701,7 @@ export async function startJiraLifecycle({
567
701
  const transitioned = await transitionJiraIssue({
568
702
  targetPath,
569
703
  outputDir,
704
+ sessionId,
570
705
  workItemId,
571
706
  issueKey: opened.issue.issueKey,
572
707
  toStatus: "IN_PROGRESS",