sentinelayer-cli 0.6.2 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (159) hide show
  1. package/README.md +996 -996
  2. package/bin/create-sentinelayer.js +5 -5
  3. package/bin/sentinelayer-cli.js +4 -4
  4. package/bin/sl.js +5 -5
  5. package/package.json +64 -63
  6. package/src/agents/jules/config/definition.js +160 -160
  7. package/src/agents/jules/config/system-prompt.js +182 -182
  8. package/src/agents/jules/error-intake.js +51 -51
  9. package/src/agents/jules/fix-cycle.js +17 -17
  10. package/src/agents/jules/loop.js +457 -450
  11. package/src/agents/jules/pulse.js +10 -10
  12. package/src/agents/jules/stream.js +187 -186
  13. package/src/agents/jules/swarm/file-scanner.js +74 -74
  14. package/src/agents/jules/swarm/index.js +11 -11
  15. package/src/agents/jules/swarm/orchestrator.js +362 -362
  16. package/src/agents/jules/swarm/pattern-hunter.js +123 -123
  17. package/src/agents/jules/swarm/sub-agent.js +311 -309
  18. package/src/agents/jules/tools/aidenid-email.js +189 -189
  19. package/src/agents/jules/tools/auth-audit.js +1699 -1691
  20. package/src/agents/jules/tools/dispatch.js +340 -335
  21. package/src/agents/jules/tools/file-edit.js +2 -2
  22. package/src/agents/jules/tools/file-read.js +2 -2
  23. package/src/agents/jules/tools/frontend-analyze.js +570 -570
  24. package/src/agents/jules/tools/glob.js +2 -2
  25. package/src/agents/jules/tools/grep.js +2 -2
  26. package/src/agents/jules/tools/index.js +29 -29
  27. package/src/agents/jules/tools/path-guards.js +2 -2
  28. package/src/agents/jules/tools/runtime-audit.js +507 -507
  29. package/src/agents/jules/tools/shell.js +2 -2
  30. package/src/agents/jules/tools/url-policy.js +100 -100
  31. package/src/agents/persona-visuals.js +64 -61
  32. package/src/agents/shared-tools/dispatch-core.js +320 -315
  33. package/src/agents/shared-tools/file-edit.js +180 -180
  34. package/src/agents/shared-tools/file-read.js +100 -100
  35. package/src/agents/shared-tools/glob.js +168 -168
  36. package/src/agents/shared-tools/grep.js +228 -228
  37. package/src/agents/shared-tools/index.js +46 -46
  38. package/src/agents/shared-tools/path-guards.js +161 -161
  39. package/src/agents/shared-tools/shell.js +383 -383
  40. package/src/ai/aidenid.js +1021 -1009
  41. package/src/ai/client.js +553 -553
  42. package/src/ai/domain-target-store.js +268 -268
  43. package/src/ai/identity-store.js +270 -270
  44. package/src/ai/proxy.js +137 -137
  45. package/src/ai/site-store.js +145 -145
  46. package/src/audit/agents/architecture.js +180 -180
  47. package/src/audit/agents/compliance.js +179 -179
  48. package/src/audit/agents/documentation.js +165 -165
  49. package/src/audit/agents/performance.js +145 -145
  50. package/src/audit/agents/security.js +215 -215
  51. package/src/audit/agents/testing.js +172 -172
  52. package/src/audit/orchestrator.js +557 -557
  53. package/src/audit/package.js +204 -204
  54. package/src/audit/registry.js +284 -284
  55. package/src/audit/replay.js +103 -103
  56. package/src/auth/gate.js +400 -371
  57. package/src/auth/http.js +681 -611
  58. package/src/auth/service.js +1106 -1106
  59. package/src/auth/session-store.js +813 -813
  60. package/src/cli.js +257 -252
  61. package/src/commands/ai/identity-lifecycle.js +1338 -1338
  62. package/src/commands/ai/provision-governance.js +1272 -1272
  63. package/src/commands/ai/shared.js +147 -147
  64. package/src/commands/ai.js +11 -11
  65. package/src/commands/apply.js +12 -12
  66. package/src/commands/audit.js +1171 -1166
  67. package/src/commands/auth.js +419 -419
  68. package/src/commands/chat.js +191 -191
  69. package/src/commands/config.js +184 -184
  70. package/src/commands/cost.js +311 -311
  71. package/src/commands/daemon/core.js +850 -850
  72. package/src/commands/daemon/extended.js +1048 -1048
  73. package/src/commands/daemon/shared.js +213 -213
  74. package/src/commands/daemon.js +11 -11
  75. package/src/commands/guide.js +174 -174
  76. package/src/commands/ingest.js +58 -58
  77. package/src/commands/init.js +55 -55
  78. package/src/commands/legacy-args.js +10 -10
  79. package/src/commands/mcp.js +461 -461
  80. package/src/commands/omargate.js +29 -29
  81. package/src/commands/persona.js +20 -20
  82. package/src/commands/plugin.js +260 -260
  83. package/src/commands/policy.js +132 -132
  84. package/src/commands/prompt.js +238 -238
  85. package/src/commands/review.js +704 -704
  86. package/src/commands/scan.js +872 -872
  87. package/src/commands/session.js +590 -0
  88. package/src/commands/spec.js +778 -716
  89. package/src/commands/swarm.js +651 -651
  90. package/src/commands/telemetry.js +202 -202
  91. package/src/commands/watch.js +511 -511
  92. package/src/config/agent-dictionary.js +182 -182
  93. package/src/config/io.js +56 -56
  94. package/src/config/paths.js +18 -18
  95. package/src/config/schema.js +55 -55
  96. package/src/config/service.js +184 -184
  97. package/src/cost/budget.js +235 -235
  98. package/src/cost/history.js +188 -188
  99. package/src/cost/tracker.js +171 -171
  100. package/src/daemon/artifact-lineage.js +534 -534
  101. package/src/daemon/assignment-ledger.js +966 -770
  102. package/src/daemon/ast-parser-layer.js +258 -258
  103. package/src/daemon/budget-governor.js +633 -633
  104. package/src/daemon/callgraph-overlay.js +646 -646
  105. package/src/daemon/error-worker.js +1209 -626
  106. package/src/daemon/fix-cycle.js +384 -377
  107. package/src/daemon/hybrid-mapper.js +929 -929
  108. package/src/daemon/ingest-refresh.js +10 -9
  109. package/src/daemon/jira-lifecycle.js +767 -632
  110. package/src/daemon/operator-control.js +657 -657
  111. package/src/daemon/pulse.js +327 -327
  112. package/src/daemon/reliability-lane.js +471 -471
  113. package/src/daemon/scope-engine.js +1068 -0
  114. package/src/daemon/watchdog.js +971 -971
  115. package/src/events/schema.js +190 -0
  116. package/src/guide/generator.js +316 -316
  117. package/src/ingest/engine.js +918 -918
  118. package/src/interactive/index.js +97 -97
  119. package/src/legacy-cli.js +3161 -2994
  120. package/src/mcp/registry.js +695 -695
  121. package/src/memory/blackboard.js +301 -301
  122. package/src/memory/retrieval.js +581 -581
  123. package/src/plugin/manifest.js +553 -553
  124. package/src/policy/packs.js +144 -144
  125. package/src/prompt/generator.js +136 -118
  126. package/src/review/ai-review.js +679 -679
  127. package/src/review/local-review.js +1351 -1305
  128. package/src/review/omargate-interactive.js +68 -68
  129. package/src/review/omargate-orchestrator.js +404 -300
  130. package/src/review/persona-prompts.js +296 -296
  131. package/src/review/replay.js +235 -235
  132. package/src/review/report.js +664 -664
  133. package/src/review/scan-modes.js +48 -42
  134. package/src/review/spec-binding.js +487 -487
  135. package/src/scaffold/generator.js +67 -67
  136. package/src/scaffold/templates.js +150 -150
  137. package/src/scan/generator.js +418 -418
  138. package/src/scan/gh-secrets.js +107 -107
  139. package/src/session/agent-registry.js +352 -0
  140. package/src/session/daemon.js +801 -0
  141. package/src/session/paths.js +33 -0
  142. package/src/session/runtime-bridge.js +739 -0
  143. package/src/session/store.js +388 -0
  144. package/src/session/stream.js +325 -0
  145. package/src/spec/generator.js +619 -519
  146. package/src/spec/regenerate.js +237 -237
  147. package/src/spec/templates.js +91 -91
  148. package/src/swarm/dashboard.js +247 -247
  149. package/src/swarm/factory.js +363 -363
  150. package/src/swarm/pentest.js +934 -934
  151. package/src/swarm/registry.js +419 -419
  152. package/src/swarm/report.js +158 -158
  153. package/src/swarm/runtime.js +576 -576
  154. package/src/swarm/scenario-dsl.js +272 -272
  155. package/src/telemetry/ledger.js +302 -302
  156. package/src/telemetry/session-tracker.js +234 -234
  157. package/src/telemetry/sync.js +203 -203
  158. package/src/ui/command-hints.js +13 -13
  159. package/src/ui/markdown.js +220 -220
@@ -1,377 +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
-
7
- /**
8
- * Jules Tanaka — Autonomous Fix Cycle
9
- *
10
- * Complete lifecycle:
11
- * claim Jira open → worktree create → agentic fix → test →
12
- * Jira comment findings PR create → Omar Gate watch
13
- * fix P0-P2 from comments mergeJira close artifact release
14
- *
15
- * Failure path: BLOCKED status + Jira comment + release assignment
16
- * Worktree cleanup: always in finally block
17
- */
18
-
19
- const LEASE_TTL_SECONDS = 1800;
20
- const HEARTBEAT_INTERVAL_MS = 300000;
21
- // MAX_FIX_ATTEMPTS reserved for future agentic retry loop
22
- const OMAR_POLL_INTERVAL_MS = 15000;
23
- const OMAR_POLL_MAX_ATTEMPTS = 40; // 10 minutes max wait
24
-
25
- export async function runFixCycle({ workItemId, workItem, rootPath, scopeMap, findings, onEvent, agentIdentity }) {
26
- const agentDef = agentIdentity || { id: "unknown", persona: "Unknown Agent", color: "white", avatar: "", signature: "" };
27
- const emit = (ev, pl) => {
28
- if (onEvent) onEvent({
29
- stream: "sl_event", event: ev,
30
- agent: { id: agentDef.id, persona: agentDef.persona, color: agentDef.color, avatar: agentDef.avatar },
31
- payload: { workItemId, ...pl },
32
- });
33
- };
34
-
35
- const artDir = path.join(rootPath, ".sentinelayer", "observability", "fixes", workItemId);
36
- await fsp.mkdir(artDir, { recursive: true });
37
-
38
- let jiraKey = null;
39
- let prNumber = null;
40
- let worktreePath = null;
41
- let branchName = null;
42
- let hbTimer = null;
43
-
44
- try {
45
- // ── [1] CLAIM ─────────────────────────────────────────────────
46
- emit("fix_claim", { status: "claiming" });
47
- await claimAssignment({
48
- targetPath: rootPath, workItemId,
49
- agentIdentity: "jules-tanaka@frontend",
50
- leaseTtlSeconds: LEASE_TTL_SECONDS, stage: "fix",
51
- });
52
-
53
- hbTimer = setInterval(async () => {
54
- try {
55
- await heartbeatAssignment({
56
- targetPath: rootPath, workItemId,
57
- agentIdentity: "jules-tanaka@frontend",
58
- leaseTtlSeconds: LEASE_TTL_SECONDS, stage: "fix",
59
- });
60
- } catch { /* heartbeat failure is non-blocking */ }
61
- }, HEARTBEAT_INTERVAL_MS);
62
-
63
- // ── [2] JIRA OPEN ─────────────────────────────────────────────
64
- emit("fix_jira", { status: "opening" });
65
- const sev = workItem?.severity || "P2";
66
- const endpoint = workItem?.endpoint || "unknown";
67
- const errorCode = workItem?.errorCode || "UNKNOWN";
68
-
69
- const jr = await startJiraLifecycle({
70
- targetPath: rootPath, workItemId, actor: agentDef.persona,
71
- summary: "[" + sev + "] Frontend: " + errorCode + " at " + endpoint,
72
- description: buildDescription(workItem, findings),
73
- labels: ["sentinelayer", "jules-tanaka", "frontend", "severity-" + sev.toLowerCase()],
74
- planMessage: buildPlan(workItem, scopeMap, findings),
75
- issueKeyPrefix: "SLD",
76
- });
77
- jiraKey = jr.issue?.issueKey;
78
- emit("fix_jira", { status: "opened", issueKey: jiraKey });
79
-
80
- // ── [3] WORKTREE CREATE ───────────────────────────────────────
81
- branchName = "fix/jules-" + workItemId.replace(/[^a-zA-Z0-9-]/g, "-");
82
- worktreePath = path.join(rootPath, ".jules-worktree-" + workItemId);
83
- emit("fix_worktree", { status: "creating", branch: branchName });
84
-
85
- safeExecFile("git", ["fetch", "origin"], rootPath);
86
- safeExecFile("git", ["worktree", "add", "-b", branchName, worktreePath, "origin/main"], rootPath);
87
- emit("fix_worktree", { status: "created", path: worktreePath });
88
-
89
- // ── [4] INVESTIGATE + FIX ─────────────────────────────────────
90
- emit("fix_investigate", { status: "analyzing" });
91
-
92
- // Comment Jira with findings before fix attempt
93
- if (jiraKey && findings && findings.length > 0) {
94
- await commentJiraIssue({
95
- targetPath: rootPath, workItemId, issueKey: jiraKey,
96
- actor: agentDef.persona, type: "finding",
97
- message: buildFindingsComment(findings),
98
- });
99
- }
100
-
101
- // Fix generation: the caller is responsible for writing changes to the
102
- // worktree before invoking runFixCycle, or for wiring julesAuditLoop
103
- // in fix mode with FileEdit tool access. runFixCycle handles the full
104
- // PR/Omar/merge/Jira lifecycle for whatever changes exist in the worktree.
105
-
106
- // ── [5] PUSH + PR ─────────────────────────────────────────────
107
- emit("fix_pr", { status: "pushing" });
108
-
109
- // Check if there are changes to commit in the worktree
110
- const diffOutput = safeExecFile("git", ["diff", "--stat"], worktreePath);
111
- const untrackedOutput = safeExecFile("git", ["ls-files", "--others", "--exclude-standard"], worktreePath);
112
- const hasChanges = diffOutput.trim().length > 0 || untrackedOutput.trim().length > 0;
113
-
114
- if (hasChanges) {
115
- safeExecFile("git", ["add", "-A"], worktreePath);
116
- safeExecFile("git", ["commit", "-m", "[Jules] Fix " + errorCode + " at " + endpoint], worktreePath);
117
- }
118
-
119
- safeExecFile("git", ["push", "-u", "origin", branchName], worktreePath);
120
-
121
- const prBody = buildPrBody(workItem, findings, jiraKey);
122
- const prUrl = safeExecFile("gh", [
123
- "pr", "create",
124
- "--title", "[Jules] Fix " + errorCode,
125
- "--body", prBody,
126
- "--head", branchName,
127
- ], worktreePath).trim();
128
-
129
- const prMatch = prUrl.match(/\/pull\/(\d+)/);
130
- prNumber = prMatch ? parseInt(prMatch[1]) : null;
131
- emit("fix_pr", { status: "created", prNumber, url: prUrl });
132
-
133
- // ── [6] OMAR GATE WATCH ───────────────────────────────────────
134
- if (prNumber) {
135
- emit("fix_omar", { status: "watching", prNumber });
136
- const omarPassed = await watchOmarGate(rootPath, branchName, emit);
137
-
138
- if (!omarPassed) {
139
- emit("fix_omar", { status: "failed" });
140
- // Comment Jira about Omar failure
141
- if (jiraKey) {
142
- await commentJiraIssue({
143
- targetPath: rootPath, workItemId, issueKey: jiraKey,
144
- actor: agentDef.persona, type: "operator_stop",
145
- message: "## Omar Gate Failed\nPR #" + prNumber + " did not pass Omar Gate.\nEscalating to human review.\n\n" + agentDef.signature,
146
- });
147
- await transitionJiraIssue({
148
- targetPath: rootPath, workItemId, issueKey: jiraKey,
149
- toStatus: "BLOCKED", actor: agentDef.persona,
150
- reason: "Omar Gate failed on PR #" + prNumber,
151
- });
152
- }
153
- await releaseAssignment({
154
- targetPath: rootPath, workItemId,
155
- agentIdentity: "jules-tanaka@frontend",
156
- status: "BLOCKED", reason: "Omar Gate failed on PR #" + prNumber,
157
- });
158
- return {
159
- workItemId, jiraIssueKey: jiraKey, prNumber,
160
- status: "blocked_omar", signature: agentDef.signature,
161
- };
162
- }
163
-
164
- emit("fix_omar", { status: "passed", prNumber });
165
-
166
- // ── [7] MERGE ───────────────────────────────────────────────
167
- emit("fix_merge", { status: "merging", prNumber });
168
- try {
169
- safeExecFile("gh", ["pr", "merge", String(prNumber), "--squash", "--delete-branch"], rootPath);
170
- emit("fix_merge", { status: "merged", prNumber });
171
- } catch (mergeErr) {
172
- emit("fix_merge", { status: "failed", error: mergeErr.message });
173
- // PR created but merge failed — still better than nothing
174
- }
175
- }
176
-
177
- // ── [8] JIRA CLOSE ────────────────────────────────────────────
178
- if (jiraKey) {
179
- await commentJiraIssue({
180
- targetPath: rootPath, workItemId, issueKey: jiraKey,
181
- actor: agentDef.persona, type: "fix",
182
- message: "## Resolution\nPR #" + (prNumber || "pending") + " merged.\nOmar Gate: passed.\nFindings addressed: " + (findings?.length || 0) + "\n\n" + agentDef.signature,
183
- });
184
- await transitionJiraIssue({
185
- targetPath: rootPath, workItemId, issueKey: jiraKey,
186
- toStatus: "DONE", actor: agentDef.persona,
187
- reason: "Fixed in PR #" + (prNumber || "pending"),
188
- });
189
- }
190
-
191
- // ── [9] ARTIFACT + S3 UPLOAD ────────────────────────────────────
192
- const result = {
193
- workItemId, jiraIssueKey: jiraKey, prNumber,
194
- status: "completed",
195
- findingsAddressed: findings?.length || 0,
196
- signature: agentDef.signature,
197
- };
198
- await fsp.writeFile(
199
- path.join(artDir, "fix-result.json"),
200
- JSON.stringify(result, null, 2),
201
- );
202
-
203
- // Upload to S3 for compliance archive + agent training data
204
- emit("fix_s3", { status: "uploading" });
205
- const s3Result = await uploadFixArtifactsToS3(artDir, workItemId, rootPath);
206
- emit("fix_s3", { status: s3Result.uploaded ? "uploaded" : "skipped", reason: s3Result.reason });
207
-
208
- // ── [10] RELEASE ──────────────────────────────────────────────
209
- await releaseAssignment({
210
- targetPath: rootPath, workItemId,
211
- agentIdentity: "jules-tanaka@frontend",
212
- status: "DONE",
213
- reason: "PR #" + (prNumber || "pending") + " merged. " + agentDef.signature,
214
- });
215
-
216
- emit("fix_complete", { prNumber, jiraIssueKey: jiraKey, status: "completed" });
217
- return result;
218
-
219
- } catch (err) {
220
- emit("fix_error", { error: err.message });
221
- try {
222
- await releaseAssignment({
223
- targetPath: rootPath, workItemId,
224
- agentIdentity: "jules-tanaka@frontend",
225
- status: "BLOCKED", reason: "Fix cycle failed: " + err.message,
226
- });
227
- } catch { /* release failure non-blocking */ }
228
- if (jiraKey) {
229
- try {
230
- await commentJiraIssue({
231
- targetPath: rootPath, workItemId, issueKey: jiraKey,
232
- actor: agentDef.persona, type: "operator_stop",
233
- message: "## Fix Failed\n" + err.message + "\nEscalating to human.\n\n" + agentDef.signature,
234
- });
235
- await transitionJiraIssue({
236
- targetPath: rootPath, workItemId, issueKey: jiraKey,
237
- toStatus: "BLOCKED", actor: agentDef.persona,
238
- reason: "Fix cycle failed: " + err.message,
239
- });
240
- } catch { /* Jira failure non-blocking */ }
241
- }
242
- return { workItemId, jiraIssueKey: jiraKey, prNumber, status: "failed", error: err.message, signature: agentDef.signature };
243
- } finally {
244
- if (hbTimer) clearInterval(hbTimer);
245
- if (worktreePath) {
246
- try { safeExecFile("git", ["worktree", "remove", worktreePath, "--force"], rootPath); } catch { /* best effort */ }
247
- }
248
- }
249
- }
250
-
251
- // ── Omar Gate Watch ──────────────────────────────────────────────────
252
-
253
- async function watchOmarGate(rootPath, branchName, emit) {
254
- for (let attempt = 0; attempt < OMAR_POLL_MAX_ATTEMPTS; attempt++) {
255
- await sleep(OMAR_POLL_INTERVAL_MS);
256
- try {
257
- const runJson = safeExecFile("gh", [
258
- "run", "list", "--workflow", "Omar Gate", "--branch", branchName,
259
- "--limit", "1", "--json", "databaseId,status,conclusion",
260
- ], rootPath);
261
- const runs = JSON.parse(runJson || "[]");
262
- if (runs.length === 0) continue;
263
-
264
- const run = runs[0];
265
- if (run.status === "completed") {
266
- emit("fix_omar", { status: "completed", conclusion: run.conclusion, runId: run.databaseId });
267
- return run.conclusion === "success";
268
- }
269
- if (attempt % 4 === 0) {
270
- emit("fix_omar", { status: "waiting", attempt, runId: run.databaseId });
271
- }
272
- } catch { /* polling failure non-blocking, will retry */ }
273
- }
274
- // Timed out waiting for Omar
275
- emit("fix_omar", { status: "timeout" });
276
- return false;
277
- }
278
-
279
- // ── Helpers ──────────────────────────────────────────────────────────
280
-
281
- function safeExecFile(bin, args, cwd) {
282
- return execFileSync(bin, args, {
283
- cwd, encoding: "utf-8", timeout: 60000,
284
- stdio: ["pipe", "pipe", "pipe"],
285
- });
286
- }
287
-
288
- function sleep(ms) {
289
- return new Promise(resolve => setTimeout(resolve, ms));
290
- }
291
-
292
- function buildDescription(w, f) {
293
- const parts = [];
294
- parts.push("**Service:** " + (w?.service || "unknown"));
295
- parts.push("**Endpoint:** " + (w?.endpoint || "unknown"));
296
- parts.push("**Error:** " + (w?.errorCode || "UNKNOWN"));
297
- parts.push("**Severity:** " + (w?.severity || "P2"));
298
- if (w?.message) parts.push("**Message:** " + w.message.slice(0, 500));
299
- if (w?.stackFingerprint) parts.push("**Stack fingerprint:** " + w.stackFingerprint);
300
- if (f?.length) parts.push("\n**Related findings:** " + f.length);
301
- parts.push("\n" + agentDef.signature);
302
- return parts.join("\n");
303
- }
304
-
305
- function buildPlan(w, s, f) {
306
- const parts = [];
307
- parts.push("## Investigation Plan");
308
- parts.push("1. Scope reconstruction from error at " + (w?.endpoint || "unknown"));
309
- parts.push("2. Read " + ((s?.primary || []).length) + " primary scope files");
310
- parts.push("3. Identify root cause from stack trace + code analysis");
311
- parts.push("4. Apply fix in isolated worktree");
312
- parts.push("5. Run tests to verify fix");
313
- parts.push("6. Open PR and watch Omar Gate");
314
- if (f?.length) parts.push("\n**Pre-existing findings:** " + f.length);
315
- parts.push("\n" + agentDef.signature);
316
- return parts.join("\n");
317
- }
318
-
319
- function buildFindingsComment(f) {
320
- const parts = ["## Findings"];
321
- const items = f || [];
322
- for (const finding of items.slice(0, 10)) {
323
- parts.push("- **[" + (finding.severity || "P3") + "]** " + (finding.file || "") + ":" + (finding.line || "") + " " + (finding.title || finding.type || ""));
324
- if (finding.evidence) parts.push(" Evidence: " + String(finding.evidence).slice(0, 200));
325
- }
326
- if (items.length > 10) parts.push("... and " + (items.length - 10) + " more");
327
- parts.push("\n" + agentDef.signature);
328
- return parts.join("\n");
329
- }
330
-
331
- function buildPrBody(w, f, jiraKey) {
332
- const parts = [];
333
- if (jiraKey) parts.push("Fixes " + jiraKey);
334
- parts.push("Error: " + (w?.errorCode || "UNKNOWN") + " at " + (w?.endpoint || "unknown"));
335
- parts.push("Severity: " + (w?.severity || "P2"));
336
- if (f?.length) parts.push("Findings addressed: " + f.length);
337
- parts.push("");
338
- parts.push(agentDef.signature);
339
- return parts.join("\n");
340
- }
341
-
342
- // ── S3 Upload ────────────────────────────────────────────────────────
343
-
344
- /**
345
- * Upload fix artifacts to S3 for compliance archive and agent training.
346
- * Uses AWS CLI (must be configured in environment).
347
- * Fails silently — S3 upload must never block the fix cycle.
348
- *
349
- * Bucket: SENTINELAYER_AUDIT_S3_BUCKET env var (default: sentinelayer-audit-artifacts)
350
- * Key pattern: {repo}/{date}/jules-tanaka/{workItemId}/
351
- */
352
- async function uploadFixArtifactsToS3(artifactDir, workItemId, rootPath) {
353
- const bucket = process.env.SENTINELAYER_AUDIT_S3_BUCKET;
354
- if (!bucket) {
355
- return { uploaded: false, reason: "SENTINELAYER_AUDIT_S3_BUCKET not set" };
356
- }
357
-
358
- try {
359
- // Derive repo name from git remote or directory name
360
- let repoName = "unknown-repo";
361
- try {
362
- const remote = safeExecFile("git", ["remote", "get-url", "origin"], rootPath).trim();
363
- const match = remote.match(/\/([^/]+?)(?:\.git)?$/);
364
- if (match) repoName = match[1];
365
- } catch { /* use default */ }
366
-
367
- const date = new Date().toISOString().split("T")[0];
368
- const s3Key = repoName + "/" + date + "/jules-tanaka/" + workItemId + "/";
369
- const s3Url = "s3://" + bucket + "/" + s3Key;
370
-
371
- safeExecFile("aws", ["s3", "sync", artifactDir, s3Url, "--quiet", "--sse", "AES256"], rootPath);
372
-
373
- return { uploaded: true, bucket, key: s3Key };
374
- } catch (err) {
375
- return { uploaded: false, reason: "S3 upload failed: " + err.message };
376
- }
377
- }
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 openworktree create → agentic fix test
13
+ * Jira comment findingsPR 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
+ }