-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.ts
More file actions
917 lines (841 loc) · 47.5 KB
/
agent.ts
File metadata and controls
917 lines (841 loc) · 47.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
/**
* agent.ts — Core agent orchestrator for GStack Intelligence.
*
* ─────────────────────────────────────────────────────────────────────────────
* PURPOSE
* ─────────────────────────────────────────────────────────────────────────────
* This is the main entry point for the GStack Intelligence AI coding agent. It receives
* a GitHub issue (or issue comment) event, runs the `pi` AI agent against the
* user's prompt, and posts the result back as an issue comment. It also
* manages all session state so that multi-turn conversations across multiple
* workflow runs are seamlessly resumed.
*
* ─────────────────────────────────────────────────────────────────────────────
* LIFECYCLE POSITION
* ─────────────────────────────────────────────────────────────────────────────
* Workflow step order:
* 1. Authorize (inline shell) — auth check + add 🚀 reaction indicator
* 2. Install (bun install) — install npm/bun dependencies
* 3. Run (agent.ts) ← YOU ARE HERE
*
* ─────────────────────────────────────────────────────────────────────────────
* AGENT EXECUTION PIPELINE
* ─────────────────────────────────────────────────────────────────────────────
* 1. Fetch issue title/body from GitHub via the `gh` CLI.
* 2. Resolve (or create) a conversation session for this issue number.
* - New issue → create a fresh session; record the mapping in state/.
* - Follow-up → load the existing session file for conversation context.
* 3. Build a prompt string from the event payload.
* 4. Run the `pi` coding agent binary with the prompt (+ prior session if resuming).
* Agent output is streamed through `tee` to provide a live Actions log AND
* persist the raw JSONL to `/tmp/agent-raw.jsonl` for post-processing.
* 5. Extract the assistant's final text reply by parsing the JSONL output
* natively (reverse-iterate to find the last `message_end` event).
* 6. Persist the issue → session mapping so the next run can resume the conversation.
* 7. Stage, commit, and push all changes (session log, mapping, repo edits)
* back to the default branch with an automatic retry-on-conflict loop.
* 8. Post the extracted reply as a new comment on the originating issue.
* 9. [finally] Add an outcome reaction: 👍 (thumbs up) on success or
* 👎 (thumbs down) on error. The 🚀 rocket from the Authorize step
* is left in place for both success and error cases.
*
* ─────────────────────────────────────────────────────────────────────────────
* SESSION CONTINUITY
* ─────────────────────────────────────────────────────────────────────────────
* GStack Intelligence maintains per-issue session state in:
* .github-gstack-intelligence/state/issues/<number>.json — maps issue # → session file path
* .github-gstack-intelligence/state/sessions/<timestamp>.jsonl — the `pi` session transcript
*
* On every run the agent checks for an existing mapping. If the mapped session
* file is still present, the run "resumes" by passing `--session <path>` to `pi`,
* giving the agent full memory of all prior exchanges for that issue.
*
* ─────────────────────────────────────────────────────────────────────────────
* PUSH CONFLICT RESOLUTION
* ─────────────────────────────────────────────────────────────────────────────
* Multiple agents may race to push to the same branch. To handle this gracefully
* the script retries a failed `git push` up to 10 times with increasing backoff
* delays, pulling with `--rebase -X theirs` between attempts. If all attempts
* fail, the run throws a clear error.
*
* ─────────────────────────────────────────────────────────────────────────────
* GITHUB COMMENT SIZE LIMIT
* ─────────────────────────────────────────────────────────────────────────────
* GitHub enforces a ~65 535 character limit on issue comments. The agent reply
* is capped at 60 000 characters to leave a comfortable safety margin.
*
* ─────────────────────────────────────────────────────────────────────────────
* DEPENDENCIES
* ─────────────────────────────────────────────────────────────────────────────
* - Node.js built-in `fs` module (existsSync, readFileSync, writeFileSync, mkdirSync)
* - Node.js built-in `path` module (resolve)
* - GitHub CLI (`gh`) — must be authenticated via GITHUB_TOKEN
* - `pi` binary — installed by `bun install` from package.json
* - System tools: `tee`, `git`, `bash`
* - Bun runtime — for Bun.spawn and top-level await
*/
import { existsSync, readFileSync, writeFileSync, mkdirSync } from "fs";
import { resolve } from "path";
import { route, loadConfig, AGENT_SIGNATURE, type RouteResult } from "./router";
// ─── Paths and event context ───────────────────────────────────────────────────
// `import.meta.dir` resolves to `.github-gstack-intelligence/lifecycle/`; stepping up one level
// gives us the `.github-gstack-intelligence/` directory which contains `state/` and `node_modules/`.
const minimumIntelligenceDir = resolve(import.meta.dir, "..");
const stateDir = resolve(minimumIntelligenceDir, "state");
const issuesDir = resolve(stateDir, "issues");
const sessionsDir = resolve(stateDir, "sessions");
const piSettingsPath = resolve(minimumIntelligenceDir, ".pi", "settings.json");
// The `pi` CLI requires a repo-root-relative path for `--session-dir`, not an
// absolute one, so we keep this as a relative string constant.
const sessionsDirRelative = ".github-gstack-intelligence/state/sessions";
// GitHub enforces a ~65 535 character limit on issue comments; cap at 60 000
// characters to leave a comfortable safety margin and avoid API rejections.
const MAX_COMMENT_LENGTH = 60000;
// Leading characters that indicate a message is intended for a different AI agent.
// When the first character of an issue title or comment body is in this set, GMI
// exits silently so that the designated agent can react instead.
const RESERVED_PREFIXES = new Set(["`", "~", "@", "#", "$", "%", "^", ":", ";", "|", "=", "/", "\\", "&"]);
// ─── Route mode ────────────────────────────────────────────────────────────────
// When `--route` is passed, the agent consults router.ts to determine which
// skill to execute based on the event type, slash commands, and labels.
// Without `--route`, all events go through general conversation (legacy behavior).
const isRouteMode = process.argv.includes("--route");
// Parse the full GitHub Actions event payload (contains issue/comment details).
const event = JSON.parse(readFileSync(process.env.GITHUB_EVENT_PATH!, "utf-8"));
// "issues" for new issues, "issue_comment" for replies on existing issues,
// "pull_request" for PR opened/synchronized events.
const eventName = process.env.GITHUB_EVENT_NAME!;
// Whether this event is a pull_request event (PR review, not an issue).
const isPullRequest = eventName === "pull_request";
// Whether this event is an automated event with no associated issue or PR.
// These events (schedule, release, deployment_status) don't have a target
// issue/PR number for comment posting — results are committed to state only.
const isAutomatedEvent = ["schedule", "release", "deployment_status"].includes(eventName);
// "owner/repo" format — used when calling the GitHub REST API via `gh api`.
const repo = process.env.GITHUB_REPOSITORY!;
// Fall back to "main" if the repository's default branch is not set in the event.
const defaultBranch = event.repository?.default_branch ?? "main";
// The target number is the issue number for issue events, or the PR number for
// pull_request events. For automated events (schedule, release, deployment_status),
// there is no target number — set to 0.
const targetNumber: number = isPullRequest
? event.pull_request.number
: isAutomatedEvent
? 0
: event.issue?.number ?? 0;
// Read the committed `.pi` defaults and pass them explicitly to the runtime.
// This prevents provider/model drift from host-level config (for example a
// runner image with a global `~/.pi/settings.json` set to github-copilot).
const piSettings = JSON.parse(readFileSync(piSettingsPath, "utf-8"));
const configuredProvider: string = piSettings.defaultProvider;
const configuredModel: string = piSettings.defaultModel;
const configuredThinking: string | undefined = piSettings.defaultThinkingLevel;
if (!configuredProvider || !configuredModel) {
throw new Error(
`Invalid .pi settings at ${piSettingsPath}: expected defaultProvider and defaultModel`
);
}
// Catch whitespace-only or obviously malformed model identifiers early so the
// pi agent doesn't start up only to fail with an opaque API error.
if (configuredModel.trim() !== configuredModel || /\s/.test(configuredModel)) {
throw new Error(
`Invalid model identifier "${configuredModel}" in ${piSettingsPath}: ` +
`model IDs must not contain whitespace. ` +
`Update the "defaultModel" field in .pi/settings.json to a valid model ID for the "${configuredProvider}" provider.`
);
}
console.log(`Configured provider: ${configuredProvider}, model: ${configuredModel}${configuredThinking ? `, thinking: ${configuredThinking}` : ""}`);
// ─── Helpers ──────────────────────────────────────────────────────────────────
/**
* Spawn an arbitrary subprocess, capture its stdout, and return both the
* trimmed output and the process exit code.
*
* @param cmd - Command and arguments array (e.g. ["git", "push", "origin", "main"]).
* @param opts - Optional options; `stdin` can be piped from another process.
* @returns - `{ exitCode, stdout }` after the process has exited.
*/
async function run(cmd: string[], opts?: { stdin?: any }): Promise<{ exitCode: number; stdout: string }> {
const proc = Bun.spawn(cmd, {
stdout: "pipe",
stderr: "inherit", // surface errors directly in the Actions log
stdin: opts?.stdin,
});
const stdout = await new Response(proc.stdout).text();
const exitCode = await proc.exited;
return { exitCode, stdout: stdout.trim() };
}
/**
* Convenience wrapper: run `gh <args>` and return trimmed stdout.
* Uses the `run` helper above so that `gh` errors appear in the Actions log.
* Throws on non-zero exit codes to fail fast on API errors.
*/
async function gh(...args: string[]): Promise<string> {
const { exitCode, stdout } = await run(["gh", ...args]);
if (exitCode !== 0) {
throw new Error(`gh ${args[0]} failed with exit code ${exitCode}`);
}
return stdout;
}
/**
* Extract the most recent assistant text from a JSONL file written by the `pi` agent.
*
* Reads the file line-by-line, parses each line as JSON (silently skipping any
* malformed lines), and iterates in reverse to find the last `message_end` event
* where `role === "assistant"` and the content array includes at least one `text`
* block. All text blocks from that event are concatenated and returned.
*
* Returns an empty string when the file is missing, empty, or contains no
* qualifying assistant message — the caller should handle that gracefully.
*
* @param filePath - Absolute path to the raw JSONL output file.
*/
function extractAgentText(filePath: string): string {
let rawContent: string;
try {
rawContent = readFileSync(filePath, "utf-8");
} catch {
console.warn(`Could not read agent output file: ${filePath}`);
return "";
}
const lines = rawContent.split("\n");
// Walk backwards (most recent events first) to find the last assistant
// message_end with text content — mirrors the original `tac | jq` logic.
for (let i = lines.length - 1; i >= 0; i--) {
const line = lines[i].trim();
if (line.length === 0) continue;
let event: any;
try {
event = JSON.parse(line);
} catch {
// Skip non-JSON lines (e.g. log output, partial writes).
continue;
}
if (
event.type === "message_end" &&
event.message?.role === "assistant" &&
Array.isArray(event.message?.content)
) {
const textParts = event.message.content
.filter((block: any) => block.type === "text")
.map((block: any) => block.text ?? "");
if (textParts.length > 0) {
return textParts.join("");
}
}
}
return "";
}
async function main() {
// ─── Restore reaction state from Authorize step ─────────────────────
// The Authorize step writes the 🚀 reaction metadata to
// `/tmp/reaction-state.json`. We read it here so the `finally` block can
// add the outcome reaction (👍 or 👎) when the agent finishes.
// If the file is absent (e.g., authorization was skipped), we default to null.
let reactionState: any = null;
if (existsSync("/tmp/reaction-state.json")) {
try {
reactionState = JSON.parse(readFileSync("/tmp/reaction-state.json", "utf-8"));
} catch {
console.warn("Could not parse /tmp/reaction-state.json, skipping reaction state");
}
}
// Track whether the agent completed successfully so the `finally` block can
// add the correct outcome reaction (👍 on success, 👎 on error).
let succeeded = false;
try {
// ── Read title and body from the event payload ───────────────────────────────
// For pull_request events, use the PR title and body.
// For issue events, use the issue title and body from the webhook payload.
// For automated events (schedule, release, deployment_status), title/body
// are derived from the event context (handled by the router's skill prompt).
// GitHub truncates string fields at 65 536 characters in webhook payloads, so
// we fall back to the API only when the body hits that limit.
let title: string;
let body: string;
if (isPullRequest) {
title = event.pull_request.title ?? "";
body = event.pull_request.body ?? "";
} else if (isAutomatedEvent) {
// Automated events don't have an issue/PR — the router builds the prompt
// from the event payload. Title/body are placeholders for context lines.
if (eventName === "release") {
title = `Release: ${event.release?.tag_name ?? "unknown"}`;
body = event.release?.body ?? "";
} else if (eventName === "deployment_status") {
title = `Deployment: ${event.deployment?.environment ?? "unknown"}`;
body = `Status: ${event.deployment_status?.state ?? "unknown"}`;
} else {
// schedule
title = `Scheduled run: ${event.schedule ?? "unknown cron"}`;
body = "";
}
} else {
title = event.issue?.title ?? "";
body = event.issue?.body ?? "";
if (body.length >= 65536) {
body = await gh("issue", "view", String(targetNumber), "--json", "body", "--jq", ".body");
}
}
// ── Resolve or create session mapping ───────────────────────────────────────
// Each issue maps to exactly one `pi` session file via `state/issues/<n>.json`.
// If a mapping exists AND the referenced session file is still present, we resume
// the conversation by passing `--session <path>` to `pi`. Otherwise we start fresh.
// For pull_request and automated events, session continuity is not needed —
// each run is a one-shot operation that starts fresh.
mkdirSync(issuesDir, { recursive: true });
mkdirSync(sessionsDir, { recursive: true });
let mode = "new";
let sessionPath = "";
const mappingFile = (isPullRequest || isAutomatedEvent) ? "" : resolve(issuesDir, `${targetNumber}.json`);
if (!isPullRequest && !isAutomatedEvent && existsSync(mappingFile)) {
try {
const mapping = JSON.parse(readFileSync(mappingFile, "utf-8"));
if (existsSync(mapping.sessionPath)) {
// A prior session exists — resume it to preserve conversation context.
mode = "resume";
sessionPath = mapping.sessionPath;
console.log(`Found existing session: ${sessionPath}`);
} else {
// The mapping points to a session file that no longer exists (e.g., cleaned up).
console.log("Mapped session file missing, starting fresh");
}
} catch {
console.warn(`Could not parse ${mappingFile}, starting fresh`);
}
} else {
console.log("No session mapping found, starting fresh");
}
// ── Configure git identity ───────────────────────────────────────────────────
// Set the bot identity for all git commits made during this run.
await run(["git", "config", "user.name", "github-gstack-intelligence[bot]"]);
await run(["git", "config", "user.email", "github-gstack-intelligence[bot]@users.noreply.github.com"]);
// ── Build prompt from event context ─────────────────────────────────────────
// For `issue_comment` events, use the new comment body as the full prompt so
// that follow-up instructions reach the agent verbatim.
// For `issues` (opened) events, combine the title and body for full context.
let prompt: string;
if (eventName === "issue_comment") {
prompt = event.comment.body ?? "";
} else {
prompt = `${title}\n\n${body}`;
}
// ── Skill routing (--route mode) ────────────────────────────────────────────
// When --route is active, consult the router to determine which skill to
// execute. If a route matches, load the skill prompt and inject context.
// If no route matches, fall through to general conversation.
let routeResult: RouteResult | null = null;
if (isRouteMode) {
try {
const config = loadConfig(minimumIntelligenceDir);
routeResult = route(event, eventName, config);
if (routeResult) {
// Load the skill prompt file.
const skillPath = resolve(minimumIntelligenceDir, "skills", `${routeResult.skill}.md`);
if (existsSync(skillPath)) {
let skillPrompt: string;
if (routeResult.skill === "autoplan") {
// /autoplan chains four review skills into a single combined prompt.
// Load each review skill and concatenate them so the agent executes
// all four reviews in one invocation (Approach A from the plan).
const autoplanPrompt = readFileSync(skillPath, "utf-8");
const reviewSkills = ["plan-ceo-review", "plan-design-review", "plan-eng-review", "plan-devex-review"] as const;
const reviewSections: string[] = [];
for (const reviewSkill of reviewSkills) {
const reviewPath = resolve(minimumIntelligenceDir, "skills", `${reviewSkill}.md`);
if (existsSync(reviewPath)) {
const reviewContent = readFileSync(reviewPath, "utf-8");
const SKILL_TITLES: Record<string, string> = {
"plan-ceo-review": "CEO Review",
"plan-design-review": "Design Review",
"plan-eng-review": "Engineering Review",
"plan-devex-review": "DX Review",
};
const sectionTitle = SKILL_TITLES[reviewSkill] ?? reviewSkill;
reviewSections.push(`## ${sectionTitle}\n${reviewContent}`);
} else {
console.warn(`Autoplan sub-skill not found: ${reviewPath}`);
}
}
skillPrompt = `${autoplanPrompt}\n\n---\n\nExecute the following ${reviewSections.length} review(s) in sequence:\n\n${reviewSections.join("\n\n")}`;
console.log(`Autoplan: loaded ${reviewSections.length} review skill(s)`);
} else {
skillPrompt = readFileSync(skillPath, "utf-8");
}
// Build context lines for the prompt.
const contextParts: string[] = [];
if (routeResult.context.prNumber) {
contextParts.push(`PR: #${routeResult.context.prNumber}`);
}
if (routeResult.context.issueNumber) {
contextParts.push(`Issue: #${routeResult.context.issueNumber}`);
}
if (routeResult.context.url) {
contextParts.push(`URL: ${routeResult.context.url}`);
}
if (routeResult.context.args) {
contextParts.push(`Args: ${routeResult.context.args}`);
}
if (routeResult.context.branch) {
contextParts.push(`Branch: ${routeResult.context.branch}`);
}
if (routeResult.context.diffStat) {
contextParts.push(`Diff: ${routeResult.context.diffStat}`);
}
const contextStr = contextParts.length > 0
? `\n\nContext:\n${contextParts.join("\n")}`
: "";
// Include the original user message after the skill prompt.
// For issue_comment events, include the issue title and body so
// skills have full context about the issue (not just the comment).
let userMessage: string;
if (eventName === "issue_comment") {
const commentBody = event.comment?.body ?? "";
if (title || body) {
userMessage = `Issue: ${title}\n\n${body}\n\n---\n\nComment:\n${commentBody}`;
} else {
userMessage = commentBody;
}
} else {
userMessage = `${title}\n\n${body}`;
}
prompt = `${skillPrompt}${contextStr}\n\n---\n\nUser message:\n${userMessage}`;
console.log(`Skill prompt loaded: ${routeResult.skill} (${skillPath})`);
} else {
console.warn(`Skill file not found: ${skillPath}, falling back to general conversation`);
routeResult = null;
}
} else if (eventName !== "issues" && eventName !== "issue_comment") {
// Non-conversation event with no matching route — exit cleanly.
console.log("No route matched for non-conversation event, exiting cleanly");
succeeded = true;
return;
}
} catch (e) {
console.warn(`Router error: ${e}. Falling back to general conversation.`);
routeResult = null;
}
}
// ── Honor the router's sessionMode directive ──────────────────────────────────
// The session-resolution block above eagerly sets mode="resume" whenever a
// prior mapping exists. Some skills explicitly opt out of continuity:
// • "none" — one-shot pipeline (e.g. autoplan): discard any prior session.
// • "new" — always start a fresh session (e.g. PR review): discard any prior session.
// • "resume" — keep the session that was resolved above (default for slash commands).
if (routeResult) {
if (routeResult.sessionMode === "none" || routeResult.sessionMode === "new") {
if (mode === "resume") {
console.log(`Route "${routeResult.skill}" requires sessionMode="${routeResult.sessionMode}", overriding resume → fresh start`);
}
mode = "new";
sessionPath = "";
}
}
// ── Skip reserved-prefix messages for other AI agents ───────────────────────
// Certain leading characters signal that this message is intended for another
// AI agent. If the issue title (for new issues) or comment body (for comments)
// starts with any of these characters, exit cleanly without responding so that
// the designated agent can react instead.
// When a route matched a slash command, skip this check — the router already
// interpreted the `/` prefix as a skill command.
if (!routeResult) {
const textToCheck = eventName === "issue_comment" ? event.comment.body : title;
if (textToCheck && RESERVED_PREFIXES.has(textToCheck[0])) {
console.log(`Skipping: first character "${textToCheck[0]}" is a reserved prefix for another agent.`);
succeeded = true;
return;
}
}
// ── Validate provider API key ────────────────────────────────────────────────
// This check is inside the try block so that the finally clause always runs
// (adding the outcome reaction) and a helpful comment can be posted to the issue.
const providerKeyMap: Record<string, string> = {
anthropic: "ANTHROPIC_API_KEY",
openai: "OPENAI_API_KEY",
google: "GEMINI_API_KEY",
xai: "XAI_API_KEY",
openrouter: "OPENROUTER_API_KEY",
mistral: "MISTRAL_API_KEY",
groq: "GROQ_API_KEY",
};
const requiredKeyName = providerKeyMap[configuredProvider];
if (requiredKeyName && !process.env[requiredKeyName]) {
await gh(
"issue", "comment", String(targetNumber),
"--body",
`## ⚠️ Missing API Key: \`${requiredKeyName}\`\n\n` +
`The configured provider is \`${configuredProvider}\`, but the \`${requiredKeyName}\` secret is not available to this workflow run.\n\n` +
`### How to fix\n\n` +
`**Option A — Repository secret** _(simplest)_\n` +
`1. Go to **Settings → Secrets and variables → Actions → New repository secret**\n` +
`2. Name: \`${requiredKeyName}\`, Value: your API key\n\n` +
`**Option B — Organization secret** _(already have one?)_\n` +
`Organization secrets are only available to workflows if the secret has been explicitly granted to this repository:\n` +
`1. Go to your **Organization Settings → Secrets and variables → Actions**\n` +
`2. Click the \`${requiredKeyName}\` secret → **Repository access**\n` +
`3. Add **this repository** to the selected repositories list\n\n` +
`Once the secret is accessible, re-trigger this workflow by posting a new comment on this issue.`
);
throw new Error(
`${requiredKeyName} is not available to this workflow run. ` +
`If you have set it as a repository secret, verify the secret name matches exactly. ` +
`If you have set it as an organization secret, ensure this repository has been granted access ` +
`(Organization Settings → Secrets and variables → Actions → ${requiredKeyName} → Repository access).`
);
}
// ── Run the pi agent ─────────────────────────────────────────────────────────
// Pipe agent output through `tee` so we get:
// • a live stream to stdout (visible in the Actions log in real time), and
// • a persisted copy at `/tmp/agent-raw.jsonl` for post-processing below.
const piBin = resolve(minimumIntelligenceDir, "node_modules", ".bin", "pi");
const piArgs = [
piBin,
"--mode",
"json",
"--tools",
"read,bash,edit,write,grep,find,ls",
"--provider",
configuredProvider,
"--model",
configuredModel,
...(configuredThinking ? ["--thinking", configuredThinking] : []),
"--session-dir",
sessionsDirRelative,
"-p",
prompt,
];
if (mode === "resume" && sessionPath) {
// Pass the prior session transcript so the agent can recall earlier context.
piArgs.push("--session", sessionPath);
}
const pi = Bun.spawn(piArgs, { stdout: "pipe", stderr: "inherit" });
const tee = Bun.spawn(["tee", "/tmp/agent-raw.jsonl"], { stdin: pi.stdout, stdout: "inherit" });
await tee.exited;
// Check if the pi agent exited successfully.
const piExitCode = await pi.exited;
if (piExitCode !== 0) {
// Surface the provider/model in the error so that an invalid or
// misspelled model ID doesn't fail silently — the most common cause of
// unexpected non-zero exits from the pi agent is an unrecognised model.
throw new Error(
`pi agent exited with code ${piExitCode} (provider: ${configuredProvider}, model: ${configuredModel}). ` +
`This may indicate an invalid or misspelled model ID in .pi/settings.json. ` +
`Check the workflow logs above for details.`
);
}
// ── Extract final assistant text ─────────────────────────────────────────────
// Parse the JSONL output natively instead of piping through `tac | jq`, which
// is fragile and emits confusing errors to the CI log when the JSONL contains
// non-JSON lines, partial writes, or is empty. We iterate in reverse to find
// the most recent `message_end` where the role is `assistant` AND the content
// contains at least one `text` block. This correctly handles cases where the
// final event has empty content (e.g., a 400 API error after a successful tool
// call) by falling back to an earlier assistant message.
const agentText = extractAgentText("/tmp/agent-raw.jsonl");
// ── Determine latest session file ────────────────────────────────────────────
// After the agent run, the newest `.jsonl` file in the sessions directory is
// the session transcript that was just written (or extended).
const { stdout: latestSession } = await run([
"bash", "-c", `ls -t ${sessionsDirRelative}/*.jsonl 2>/dev/null | head -1`,
]);
// ── Persist issue → session mapping ─────────────────────────────────────────
// Write (or overwrite) the mapping file so that the next run for this issue
// can locate the correct session transcript and resume the conversation.
// For pull_request and automated events, session mapping is skipped — each
// run is a one-shot operation.
if (latestSession && !isPullRequest && !isAutomatedEvent) {
writeFileSync(
mappingFile,
JSON.stringify({
issueNumber: targetNumber,
sessionPath: latestSession,
updatedAt: new Date().toISOString(),
}, null, 2) + "\n"
);
console.log(`Saved mapping: issue #${targetNumber} -> ${latestSession}`);
} else if (!latestSession && !isPullRequest && !isAutomatedEvent) {
console.log("Warning: no session file found to map");
}
// ── Persist review/security results ──────────────────────────────────────────
// Write a structured result file for review and CSO skills so downstream skills
// (e.g. /ship) can verify that a review has been completed.
if (routeResult && (routeResult.skill === "review" || routeResult.skill === "cso")) {
const resultSubdir = routeResult.skill === "cso" ? "security" : routeResult.skill;
const resultDir = resolve(stateDir, "results", resultSubdir);
mkdirSync(resultDir, { recursive: true });
// For review/CSO skills routed from PR events, prNumber is always set by
// the router. The targetNumber fallback handles the edge case where the
// skill is invoked via a slash command on an issue comment.
const resultNumber = routeResult.context.prNumber ?? targetNumber;
const result = {
prNumber: resultNumber,
skill: routeResult.skill,
timestamp: new Date().toISOString(),
status: "completed",
commit: process.env.GITHUB_SHA ?? null,
};
writeFileSync(
resolve(resultDir, `pr-${resultNumber}.json`),
JSON.stringify(result, null, 2) + "\n"
);
console.log(`Persisted ${routeResult.skill} result for PR #${resultNumber}`);
}
// ── Persist QA / QA-only / design-review results ────────────────────────────
// Write a structured result file for browser-based skills so the agent can
// track QA runs over time and downstream skills can reference prior results.
if (routeResult && (routeResult.skill === "qa" || routeResult.skill === "qa-only" || routeResult.skill === "design-review")) {
const resultSubdir = routeResult.skill === "design-review" ? "design-review" : "qa";
const resultDir = resolve(stateDir, "results", resultSubdir);
mkdirSync(resultDir, { recursive: true });
const resultIdentifier = routeResult.context.prNumber ?? routeResult.context.issueNumber ?? targetNumber;
const resultFilename = routeResult.context.prNumber
? `pr-${resultIdentifier}.json`
: `issue-${resultIdentifier}.json`;
const result = {
...(routeResult.context.prNumber
? { prNumber: resultIdentifier }
: { issueNumber: resultIdentifier }),
skill: routeResult.skill,
url: routeResult.context.url ?? null,
timestamp: new Date().toISOString(),
status: "completed",
commit: process.env.GITHUB_SHA ?? null,
};
writeFileSync(
resolve(resultDir, resultFilename),
JSON.stringify(result, null, 2) + "\n"
);
console.log(`Persisted ${routeResult.skill} result for #${resultIdentifier}`);
}
// ── Persist retro results ───────────────────────────────────────────────────
// Retro reports are saved as date-stamped JSON in state/results/retro/ so
// subsequent retros can compare trends across weeks.
if (routeResult && routeResult.skill === "retro") {
const resultDir = resolve(stateDir, "results", "retro");
mkdirSync(resultDir, { recursive: true });
const dateStr = new Date().toISOString().slice(0, 10);
const result = {
skill: "retro",
date: dateStr,
timestamp: new Date().toISOString(),
status: "completed",
commit: process.env.GITHUB_SHA ?? null,
};
writeFileSync(
resolve(resultDir, `${dateStr}.json`),
JSON.stringify(result, null, 2) + "\n"
);
console.log(`Persisted retro result for ${dateStr}`);
}
// ── Persist benchmark results ───────────────────────────────────────────────
// Benchmark results are saved as date-stamped JSON in state/benchmarks/history/
// and the baseline file is referenced for comparison.
if (routeResult && routeResult.skill === "benchmark") {
const historyDir = resolve(stateDir, "benchmarks", "history");
mkdirSync(historyDir, { recursive: true });
const dateStr = new Date().toISOString().slice(0, 10);
const result = {
skill: "benchmark",
date: dateStr,
timestamp: new Date().toISOString(),
status: "completed",
commit: process.env.GITHUB_SHA ?? null,
};
writeFileSync(
resolve(historyDir, `${dateStr}.json`),
JSON.stringify(result, null, 2) + "\n"
);
console.log(`Persisted benchmark result for ${dateStr}`);
}
// ── Persist canary results ──────────────────────────────────────────────────
// Canary monitoring results track deployment health checks over time.
if (routeResult && routeResult.skill === "canary") {
const resultDir = resolve(stateDir, "results", "canary");
mkdirSync(resultDir, { recursive: true });
const timestamp = new Date().toISOString();
const result = {
skill: "canary",
url: routeResult.context.url ?? null,
timestamp,
status: "completed",
commit: process.env.GITHUB_SHA ?? null,
};
writeFileSync(
resolve(resultDir, `${timestamp.slice(0, 19).replace(/:/g, "-")}.json`),
JSON.stringify(result, null, 2) + "\n"
);
console.log(`Persisted canary result`);
}
// ── Persist document-release results ────────────────────────────────────────
// Track which releases have been documented by the agent.
if (routeResult && routeResult.skill === "document-release") {
const resultDir = resolve(stateDir, "results", "releases");
mkdirSync(resultDir, { recursive: true });
const tagName = event.release?.tag_name ?? "unknown";
const result = {
skill: "document-release",
tag: tagName,
timestamp: new Date().toISOString(),
status: "completed",
commit: process.env.GITHUB_SHA ?? null,
};
writeFileSync(
resolve(resultDir, `${tagName.replace(/[^a-zA-Z0-9._-]/g, "_")}.json`),
JSON.stringify(result, null, 2) + "\n"
);
console.log(`Persisted document-release result for ${tagName}`);
}
// ── Persist health results ──────────────────────────────────────────────────
// Health check results are saved as date-stamped JSON in state/results/health/
// so trend tracking across runs is possible.
if (routeResult && routeResult.skill === "health") {
const resultDir = resolve(stateDir, "results", "health");
mkdirSync(resultDir, { recursive: true });
const dateStr = new Date().toISOString().slice(0, 10);
const result = {
skill: "health",
date: dateStr,
timestamp: new Date().toISOString(),
status: "completed",
commit: process.env.GITHUB_SHA ?? null,
};
writeFileSync(
resolve(resultDir, `${dateStr}.json`),
JSON.stringify(result, null, 2) + "\n"
);
console.log(`Persisted health result for ${dateStr}`);
}
// ── Persist devex-review results ────────────────────────────────────────────
// Track DX audit results per issue so downstream skills can reference prior audits.
if (routeResult && routeResult.skill === "devex-review") {
const resultDir = resolve(stateDir, "results", "devex-review");
mkdirSync(resultDir, { recursive: true });
const resultIdentifier = routeResult.context.issueNumber ?? targetNumber;
const result = {
issueNumber: resultIdentifier,
skill: "devex-review",
timestamp: new Date().toISOString(),
status: "completed",
commit: process.env.GITHUB_SHA ?? null,
};
writeFileSync(
resolve(resultDir, `issue-${resultIdentifier}.json`),
JSON.stringify(result, null, 2) + "\n"
);
console.log(`Persisted devex-review result for issue #${resultIdentifier}`);
}
// ── Persist autoplan results ────────────────────────────────────────────────
// Track autoplan runs per issue so the agent knows a full review gauntlet
// has been executed.
if (routeResult && routeResult.skill === "autoplan") {
const resultDir = resolve(stateDir, "results", "autoplan");
mkdirSync(resultDir, { recursive: true });
const resultIdentifier = routeResult.context.issueNumber ?? targetNumber;
const result = {
issueNumber: resultIdentifier,
skill: "autoplan",
timestamp: new Date().toISOString(),
status: "completed",
commit: process.env.GITHUB_SHA ?? null,
};
writeFileSync(
resolve(resultDir, `issue-${resultIdentifier}.json`),
JSON.stringify(result, null, 2) + "\n"
);
console.log(`Persisted autoplan result for issue #${resultIdentifier}`);
}
// ── Commit and push state changes ───────────────────────────────────────────
// Stage all changes (session log, mapping JSON, any files the agent edited),
// commit only if the index is dirty, then push with a retry-on-conflict loop.
const addResult = await run(["git", "add", "-A"]);
if (addResult.exitCode !== 0) {
console.error("git add failed with exit code", addResult.exitCode);
}
const { exitCode } = await run(["git", "diff", "--cached", "--quiet"]);
if (exitCode !== 0) {
// exitCode !== 0 means there are staged changes to commit.
const commitMsg = isPullRequest
? `gstack-intelligence: review PR #${targetNumber}`
: isAutomatedEvent
? `gstack-intelligence: ${routeResult?.skill ?? eventName} run`
: `gstack-intelligence: work on issue #${targetNumber}`;
const commitResult = await run(["git", "commit", "-m", commitMsg]);
if (commitResult.exitCode !== 0) {
console.error("git commit failed with exit code", commitResult.exitCode);
}
}
// Retry push up to 10 times with increasing backoff delays, rebasing on
// each conflict with `-X theirs` to auto-resolve in favour of the remote.
const pushBackoffs = [1000, 2000, 3000, 5000, 7000, 8000, 10000, 12000, 12000, 15000];
let pushSucceeded = false;
for (let i = 1; i <= 10; i++) {
const push = await run(["git", "push", "origin", `HEAD:${defaultBranch}`]);
if (push.exitCode === 0) { pushSucceeded = true; break; }
if (i < 10) {
console.log(`Push failed, rebasing and retrying (${i}/10)...`);
await run(["git", "pull", "--rebase", "-X", "theirs", "origin", defaultBranch]);
await new Promise(r => setTimeout(r, pushBackoffs[i - 1]));
}
}
// ── Post reply as comment ───────────────────────────────────────────────────
// Always post the comment first so the user receives the agent's response even
// if the push later fails. The push failure throw (below) must come AFTER the
// comment is posted — otherwise the throw would skip the comment entirely and
// the user would get no reply.
// For automated events (schedule, release, deployment_status), there is no
// target issue/PR to comment on — results are committed to state only.
// For pull_request events, post as a PR comment; for issue events, post as an
// issue comment. Both use the same underlying GitHub API.
if (!isAutomatedEvent) {
const trimmedText = agentText.trim();
let commentBody = trimmedText.length > 0
? trimmedText.slice(0, MAX_COMMENT_LENGTH)
: `✅ The agent ran successfully but did not produce a text response. Check the repository for any file changes that were made.\n\nFor full details, see the [workflow run logs](https://github.com/${repo}/actions).`;
if (!pushSucceeded) {
commentBody += `\n\n---\n⚠️ **Warning:** The agent's session state could not be pushed to the repository. Conversation context may not be preserved for follow-up comments. See the [workflow run logs](https://github.com/${repo}/actions) for details.`;
}
// Append the agent signature as a hidden HTML comment for bot-loop prevention.
// The router checks incoming comments for this signature and skips them.
commentBody += "\n" + AGENT_SIGNATURE;
if (isPullRequest) {
await gh("pr", "comment", String(targetNumber), "--body", commentBody);
} else {
await gh("issue", "comment", String(targetNumber), "--body", commentBody);
}
} else {
console.log(`Automated event (${eventName}) — skipping comment posting, results committed to state`);
}
// Throw push failure AFTER the comment has been posted so the user always
// receives the agent's response. The throw still causes the workflow step to
// fail and adds a 👎 reaction via the `finally` block.
if (!pushSucceeded) {
throw new Error(
"All 10 push attempts failed. Auto-reconciliation could not be completed. " +
"Session state was not persisted to remote. Check the workflow logs for details."
);
}
// Mark the run as successful so the `finally` block adds 👍 instead of 👎.
succeeded = true;
} finally {
// ── Guaranteed outcome reaction: 👍 on success, 👎 on error ─────────────────
// This block always executes — even when the try block throws. The 🚀 rocket
// from the Authorize step is intentionally left in place; we only
// ADD the outcome reaction here.
if (reactionState) {
try {
const { reactionTarget, commentId: stateCommentId } = reactionState;
const outcomeContent = succeeded ? "+1" : "-1";
if (reactionTarget === "comment" && stateCommentId) {
// Add outcome reaction to the triggering comment.
await gh("api", `repos/${repo}/issues/comments/${stateCommentId}/reactions`, "-f", `content=${outcomeContent}`);
} else {
// Add outcome reaction to the issue (or PR — PRs are issues in GitHub).
await gh("api", `repos/${repo}/issues/${targetNumber}/reactions`, "-f", `content=${outcomeContent}`);
}
} catch (e) {
// Log but do not re-throw — a failed reaction should not mask the original error.
console.error("Failed to add outcome reaction:", e);
}
}
}
}
main();