sentinelayer-cli 0.4.5 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/README.md +996 -998
  2. package/bin/create-sentinelayer.js +5 -5
  3. package/bin/sentinelayer-cli.js +4 -4
  4. package/bin/sl.js +5 -5
  5. package/package.json +63 -63
  6. package/src/agents/jules/config/definition.js +160 -209
  7. package/src/agents/jules/config/system-prompt.js +182 -175
  8. package/src/agents/jules/error-intake.js +51 -51
  9. package/src/agents/jules/fix-cycle.js +17 -377
  10. package/src/agents/jules/loop.js +450 -367
  11. package/src/agents/jules/pulse.js +10 -327
  12. package/src/agents/jules/stream.js +186 -186
  13. package/src/agents/jules/swarm/file-scanner.js +74 -74
  14. package/src/agents/jules/swarm/index.js +11 -11
  15. package/src/agents/jules/swarm/orchestrator.js +362 -362
  16. package/src/agents/jules/swarm/pattern-hunter.js +123 -123
  17. package/src/agents/jules/swarm/sub-agent.js +309 -308
  18. package/src/agents/jules/tools/aidenid-email.js +189 -0
  19. package/src/agents/jules/tools/auth-audit.js +1691 -557
  20. package/src/agents/jules/tools/dispatch.js +335 -327
  21. package/src/agents/jules/tools/file-edit.js +2 -180
  22. package/src/agents/jules/tools/file-read.js +2 -100
  23. package/src/agents/jules/tools/frontend-analyze.js +570 -570
  24. package/src/agents/jules/tools/glob.js +2 -168
  25. package/src/agents/jules/tools/grep.js +2 -228
  26. package/src/agents/jules/tools/index.js +29 -29
  27. package/src/agents/jules/tools/path-guards.js +2 -161
  28. package/src/agents/jules/tools/runtime-audit.js +507 -503
  29. package/src/agents/jules/tools/shell.js +2 -383
  30. package/src/agents/jules/tools/url-policy.js +100 -100
  31. package/src/agents/persona-visuals.js +61 -0
  32. package/src/agents/shared-tools/dispatch-core.js +315 -0
  33. package/src/agents/shared-tools/file-edit.js +180 -0
  34. package/src/agents/shared-tools/file-read.js +100 -0
  35. package/src/agents/shared-tools/glob.js +168 -0
  36. package/src/agents/shared-tools/grep.js +228 -0
  37. package/src/agents/shared-tools/index.js +46 -0
  38. package/src/agents/shared-tools/path-guards.js +161 -0
  39. package/src/agents/shared-tools/shell.js +383 -0
  40. package/src/ai/aidenid.js +1009 -972
  41. package/src/ai/client.js +553 -508
  42. package/src/ai/domain-target-store.js +268 -268
  43. package/src/ai/identity-store.js +270 -270
  44. package/src/ai/proxy.js +137 -0
  45. package/src/ai/site-store.js +145 -145
  46. package/src/audit/agents/architecture.js +180 -180
  47. package/src/audit/agents/compliance.js +179 -179
  48. package/src/audit/agents/documentation.js +165 -165
  49. package/src/audit/agents/performance.js +145 -145
  50. package/src/audit/agents/security.js +215 -215
  51. package/src/audit/agents/testing.js +172 -172
  52. package/src/audit/orchestrator.js +557 -557
  53. package/src/audit/package.js +204 -204
  54. package/src/audit/registry.js +284 -284
  55. package/src/audit/replay.js +103 -103
  56. package/src/auth/gate.js +371 -126
  57. package/src/auth/http.js +611 -270
  58. package/src/auth/service.js +1106 -891
  59. package/src/auth/session-store.js +813 -359
  60. package/src/cli.js +252 -252
  61. package/src/commands/ai/identity-lifecycle.js +1338 -1338
  62. package/src/commands/ai/provision-governance.js +1272 -1272
  63. package/src/commands/ai/shared.js +147 -147
  64. package/src/commands/ai.js +11 -11
  65. package/src/commands/apply.js +12 -12
  66. package/src/commands/audit.js +1166 -1166
  67. package/src/commands/auth.js +419 -375
  68. package/src/commands/chat.js +191 -191
  69. package/src/commands/config.js +184 -184
  70. package/src/commands/cost.js +311 -311
  71. package/src/commands/daemon/core.js +850 -850
  72. package/src/commands/daemon/extended.js +1048 -1048
  73. package/src/commands/daemon/shared.js +213 -213
  74. package/src/commands/daemon.js +11 -11
  75. package/src/commands/guide.js +174 -174
  76. package/src/commands/ingest.js +58 -58
  77. package/src/commands/init.js +55 -55
  78. package/src/commands/legacy-args.js +10 -10
  79. package/src/commands/mcp.js +461 -461
  80. package/src/commands/omargate.js +29 -21
  81. package/src/commands/persona.js +20 -20
  82. package/src/commands/plugin.js +260 -260
  83. package/src/commands/policy.js +132 -132
  84. package/src/commands/prompt.js +238 -238
  85. package/src/commands/review.js +704 -704
  86. package/src/commands/scan.js +872 -866
  87. package/src/commands/spec.js +716 -716
  88. package/src/commands/swarm.js +651 -651
  89. package/src/commands/telemetry.js +202 -202
  90. package/src/commands/watch.js +511 -510
  91. package/src/config/agent-dictionary.js +182 -182
  92. package/src/config/io.js +56 -56
  93. package/src/config/paths.js +18 -18
  94. package/src/config/schema.js +55 -55
  95. package/src/config/service.js +184 -184
  96. package/src/cost/budget.js +235 -235
  97. package/src/cost/history.js +188 -188
  98. package/src/cost/tracker.js +171 -171
  99. package/src/daemon/artifact-lineage.js +534 -534
  100. package/src/daemon/assignment-ledger.js +770 -770
  101. package/src/daemon/ast-parser-layer.js +258 -258
  102. package/src/daemon/budget-governor.js +633 -633
  103. package/src/daemon/callgraph-overlay.js +646 -646
  104. package/src/daemon/error-worker.js +626 -626
  105. package/src/daemon/fix-cycle.js +377 -0
  106. package/src/daemon/hybrid-mapper.js +929 -929
  107. package/src/daemon/jira-lifecycle.js +632 -632
  108. package/src/daemon/operator-control.js +657 -657
  109. package/src/daemon/pulse.js +327 -0
  110. package/src/daemon/reliability-lane.js +471 -471
  111. package/src/daemon/watchdog.js +971 -971
  112. package/src/guide/generator.js +316 -316
  113. package/src/ingest/engine.js +918 -918
  114. package/src/interactive/index.js +97 -95
  115. package/src/legacy-cli.js +2994 -2592
  116. package/src/mcp/registry.js +695 -695
  117. package/src/memory/blackboard.js +301 -301
  118. package/src/memory/retrieval.js +581 -581
  119. package/src/plugin/manifest.js +553 -553
  120. package/src/policy/packs.js +144 -144
  121. package/src/prompt/generator.js +118 -118
  122. package/src/review/ai-review.js +679 -669
  123. package/src/review/local-review.js +1305 -1295
  124. package/src/review/omargate-interactive.js +68 -0
  125. package/src/review/omargate-orchestrator.js +300 -0
  126. package/src/review/persona-prompts.js +296 -0
  127. package/src/review/replay.js +235 -235
  128. package/src/review/report.js +664 -664
  129. package/src/review/scan-modes.js +42 -0
  130. package/src/review/spec-binding.js +487 -487
  131. package/src/scaffold/generator.js +67 -67
  132. package/src/scaffold/templates.js +150 -150
  133. package/src/scan/generator.js +418 -418
  134. package/src/scan/gh-secrets.js +107 -107
  135. package/src/spec/generator.js +519 -519
  136. package/src/spec/regenerate.js +237 -237
  137. package/src/spec/templates.js +91 -91
  138. package/src/swarm/dashboard.js +247 -247
  139. package/src/swarm/factory.js +363 -363
  140. package/src/swarm/pentest.js +934 -934
  141. package/src/swarm/registry.js +419 -419
  142. package/src/swarm/report.js +158 -158
  143. package/src/swarm/runtime.js +576 -576
  144. package/src/swarm/scenario-dsl.js +272 -272
  145. package/src/telemetry/ledger.js +302 -302
  146. package/src/telemetry/session-tracker.js +234 -118
  147. package/src/telemetry/sync.js +203 -199
  148. package/src/ui/command-hints.js +13 -0
  149. package/src/ui/markdown.js +220 -220
@@ -0,0 +1,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
+
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 → merge → Jira 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
+ }