sentinelayer-cli 0.1.1 → 0.3.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 (133) 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 +62 -54
  6. package/src/agents/jules/config/definition.js +209 -209
  7. package/src/agents/jules/config/system-prompt.js +175 -175
  8. package/src/agents/jules/error-intake.js +51 -51
  9. package/src/agents/jules/fix-cycle.js +377 -377
  10. package/src/agents/jules/loop.js +367 -367
  11. package/src/agents/jules/pulse.js +319 -319
  12. package/src/agents/jules/stream.js +186 -186
  13. package/src/agents/jules/swarm/file-scanner.js +74 -74
  14. package/src/agents/jules/swarm/index.js +11 -11
  15. package/src/agents/jules/swarm/orchestrator.js +362 -362
  16. package/src/agents/jules/swarm/pattern-hunter.js +123 -123
  17. package/src/agents/jules/swarm/sub-agent.js +308 -308
  18. package/src/agents/jules/tools/auth-audit.js +226 -222
  19. package/src/agents/jules/tools/dispatch.js +327 -327
  20. package/src/agents/jules/tools/file-edit.js +180 -180
  21. package/src/agents/jules/tools/file-read.js +100 -100
  22. package/src/agents/jules/tools/frontend-analyze.js +570 -570
  23. package/src/agents/jules/tools/glob.js +168 -168
  24. package/src/agents/jules/tools/grep.js +228 -228
  25. package/src/agents/jules/tools/index.js +29 -29
  26. package/src/agents/jules/tools/path-guards.js +161 -161
  27. package/src/agents/jules/tools/runtime-audit.js +493 -493
  28. package/src/agents/jules/tools/shell.js +383 -383
  29. package/src/ai/aidenid.js +972 -945
  30. package/src/ai/client.js +508 -508
  31. package/src/ai/domain-target-store.js +268 -268
  32. package/src/ai/identity-store.js +270 -270
  33. package/src/ai/site-store.js +145 -145
  34. package/src/audit/agents/architecture.js +180 -180
  35. package/src/audit/agents/compliance.js +179 -179
  36. package/src/audit/agents/documentation.js +165 -165
  37. package/src/audit/agents/performance.js +145 -145
  38. package/src/audit/agents/security.js +215 -215
  39. package/src/audit/agents/testing.js +172 -172
  40. package/src/audit/orchestrator.js +557 -557
  41. package/src/audit/package.js +204 -204
  42. package/src/audit/registry.js +284 -284
  43. package/src/audit/replay.js +103 -103
  44. package/src/auth/http.js +113 -113
  45. package/src/auth/service.js +891 -848
  46. package/src/auth/session-store.js +359 -345
  47. package/src/cli.js +252 -252
  48. package/src/commands/ai/identity-lifecycle.js +1338 -1337
  49. package/src/commands/ai/provision-governance.js +1272 -1246
  50. package/src/commands/ai/shared.js +147 -147
  51. package/src/commands/ai.js +11 -11
  52. package/src/commands/apply.js +12 -12
  53. package/src/commands/audit.js +1166 -1147
  54. package/src/commands/auth.js +375 -366
  55. package/src/commands/chat.js +191 -191
  56. package/src/commands/config.js +184 -184
  57. package/src/commands/cost.js +311 -311
  58. package/src/commands/daemon/core.js +850 -850
  59. package/src/commands/daemon/extended.js +1048 -1048
  60. package/src/commands/daemon/shared.js +213 -213
  61. package/src/commands/daemon.js +11 -11
  62. package/src/commands/guide.js +174 -174
  63. package/src/commands/ingest.js +58 -58
  64. package/src/commands/init.js +55 -55
  65. package/src/commands/legacy-args.js +10 -10
  66. package/src/commands/mcp.js +461 -404
  67. package/src/commands/omargate.js +15 -15
  68. package/src/commands/persona.js +20 -20
  69. package/src/commands/plugin.js +260 -260
  70. package/src/commands/policy.js +132 -132
  71. package/src/commands/prompt.js +238 -238
  72. package/src/commands/review.js +704 -704
  73. package/src/commands/scan.js +866 -788
  74. package/src/commands/spec.js +716 -716
  75. package/src/commands/swarm.js +651 -651
  76. package/src/commands/telemetry.js +202 -202
  77. package/src/commands/watch.js +510 -510
  78. package/src/config/agent-dictionary.js +182 -182
  79. package/src/config/io.js +56 -56
  80. package/src/config/paths.js +18 -18
  81. package/src/config/schema.js +55 -55
  82. package/src/config/service.js +184 -184
  83. package/src/cost/budget.js +235 -235
  84. package/src/cost/history.js +188 -188
  85. package/src/cost/tracker.js +171 -171
  86. package/src/daemon/artifact-lineage.js +534 -534
  87. package/src/daemon/assignment-ledger.js +770 -770
  88. package/src/daemon/ast-parser-layer.js +258 -258
  89. package/src/daemon/budget-governor.js +633 -633
  90. package/src/daemon/callgraph-overlay.js +646 -646
  91. package/src/daemon/error-worker.js +626 -626
  92. package/src/daemon/hybrid-mapper.js +929 -929
  93. package/src/daemon/ingest-refresh.js +195 -0
  94. package/src/daemon/jira-lifecycle.js +632 -632
  95. package/src/daemon/operator-control.js +657 -657
  96. package/src/daemon/reliability-lane.js +471 -471
  97. package/src/daemon/watchdog.js +971 -971
  98. package/src/guide/generator.js +316 -316
  99. package/src/ingest/engine.js +918 -918
  100. package/src/interactive/action-menu.js +132 -0
  101. package/src/interactive/auto-ingest.js +111 -0
  102. package/src/interactive/index.js +95 -0
  103. package/src/interactive/workspace.js +92 -0
  104. package/src/legacy-cli.js +2548 -2435
  105. package/src/mcp/registry.js +695 -695
  106. package/src/memory/blackboard.js +301 -301
  107. package/src/memory/retrieval.js +581 -581
  108. package/src/plugin/manifest.js +553 -553
  109. package/src/policy/packs.js +144 -144
  110. package/src/prompt/generator.js +118 -106
  111. package/src/review/ai-review.js +669 -669
  112. package/src/review/local-review.js +1284 -1284
  113. package/src/review/replay.js +235 -235
  114. package/src/review/report.js +664 -664
  115. package/src/review/spec-binding.js +487 -487
  116. package/src/scaffold/generator.js +67 -0
  117. package/src/scaffold/templates.js +150 -0
  118. package/src/scan/generator.js +418 -351
  119. package/src/scan/gh-secrets.js +107 -0
  120. package/src/spec/generator.js +519 -519
  121. package/src/spec/regenerate.js +237 -237
  122. package/src/spec/templates.js +91 -91
  123. package/src/swarm/dashboard.js +247 -247
  124. package/src/swarm/factory.js +363 -363
  125. package/src/swarm/pentest.js +934 -934
  126. package/src/swarm/registry.js +419 -419
  127. package/src/swarm/report.js +158 -158
  128. package/src/swarm/runtime.js +576 -576
  129. package/src/swarm/scenario-dsl.js +272 -272
  130. package/src/telemetry/ledger.js +302 -302
  131. package/src/telemetry/session-tracker.js +118 -0
  132. package/src/telemetry/sync.js +190 -0
  133. package/src/ui/markdown.js +220 -220
@@ -1,377 +1,377 @@
1
- import { execFileSync } from "node:child_process";
2
- import path from "node:path";
3
- import fsp from "node:fs/promises";
4
- import { JULES_DEFINITION } from "./config/definition.js";
5
- import { startJiraLifecycle, commentJiraIssue, transitionJiraIssue } from "../../daemon/jira-lifecycle.js";
6
- import { claimAssignment, heartbeatAssignment, releaseAssignment } from "../../daemon/assignment-ledger.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 }) {
27
- const emit = (ev, pl) => {
28
- if (onEvent) onEvent({
29
- stream: "sl_event", event: ev,
30
- agent: { id: JULES_DEFINITION.id, persona: JULES_DEFINITION.persona, color: JULES_DEFINITION.color, avatar: JULES_DEFINITION.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: JULES_DEFINITION.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: JULES_DEFINITION.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: JULES_DEFINITION.persona, type: "operator_stop",
145
- message: "## Omar Gate Failed\nPR #" + prNumber + " did not pass Omar Gate.\nEscalating to human review.\n\n" + JULES_DEFINITION.signature,
146
- });
147
- await transitionJiraIssue({
148
- targetPath: rootPath, workItemId, issueKey: jiraKey,
149
- toStatus: "BLOCKED", actor: JULES_DEFINITION.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: JULES_DEFINITION.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: JULES_DEFINITION.persona, type: "fix",
182
- message: "## Resolution\nPR #" + (prNumber || "pending") + " merged.\nOmar Gate: passed.\nFindings addressed: " + (findings?.length || 0) + "\n\n" + JULES_DEFINITION.signature,
183
- });
184
- await transitionJiraIssue({
185
- targetPath: rootPath, workItemId, issueKey: jiraKey,
186
- toStatus: "DONE", actor: JULES_DEFINITION.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: JULES_DEFINITION.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. " + JULES_DEFINITION.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: JULES_DEFINITION.persona, type: "operator_stop",
233
- message: "## Fix Failed\n" + err.message + "\nEscalating to human.\n\n" + JULES_DEFINITION.signature,
234
- });
235
- await transitionJiraIssue({
236
- targetPath: rootPath, workItemId, issueKey: jiraKey,
237
- toStatus: "BLOCKED", actor: JULES_DEFINITION.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: JULES_DEFINITION.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" + JULES_DEFINITION.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" + JULES_DEFINITION.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" + JULES_DEFINITION.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(JULES_DEFINITION.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 { JULES_DEFINITION } from "./config/definition.js";
5
+ import { startJiraLifecycle, commentJiraIssue, transitionJiraIssue } from "../../daemon/jira-lifecycle.js";
6
+ import { claimAssignment, heartbeatAssignment, releaseAssignment } from "../../daemon/assignment-ledger.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 }) {
27
+ const emit = (ev, pl) => {
28
+ if (onEvent) onEvent({
29
+ stream: "sl_event", event: ev,
30
+ agent: { id: JULES_DEFINITION.id, persona: JULES_DEFINITION.persona, color: JULES_DEFINITION.color, avatar: JULES_DEFINITION.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: JULES_DEFINITION.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: JULES_DEFINITION.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: JULES_DEFINITION.persona, type: "operator_stop",
145
+ message: "## Omar Gate Failed\nPR #" + prNumber + " did not pass Omar Gate.\nEscalating to human review.\n\n" + JULES_DEFINITION.signature,
146
+ });
147
+ await transitionJiraIssue({
148
+ targetPath: rootPath, workItemId, issueKey: jiraKey,
149
+ toStatus: "BLOCKED", actor: JULES_DEFINITION.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: JULES_DEFINITION.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: JULES_DEFINITION.persona, type: "fix",
182
+ message: "## Resolution\nPR #" + (prNumber || "pending") + " merged.\nOmar Gate: passed.\nFindings addressed: " + (findings?.length || 0) + "\n\n" + JULES_DEFINITION.signature,
183
+ });
184
+ await transitionJiraIssue({
185
+ targetPath: rootPath, workItemId, issueKey: jiraKey,
186
+ toStatus: "DONE", actor: JULES_DEFINITION.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: JULES_DEFINITION.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. " + JULES_DEFINITION.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: JULES_DEFINITION.persona, type: "operator_stop",
233
+ message: "## Fix Failed\n" + err.message + "\nEscalating to human.\n\n" + JULES_DEFINITION.signature,
234
+ });
235
+ await transitionJiraIssue({
236
+ targetPath: rootPath, workItemId, issueKey: jiraKey,
237
+ toStatus: "BLOCKED", actor: JULES_DEFINITION.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: JULES_DEFINITION.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" + JULES_DEFINITION.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" + JULES_DEFINITION.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" + JULES_DEFINITION.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(JULES_DEFINITION.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
+ }