-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrefresh.ts
More file actions
810 lines (712 loc) · 40.4 KB
/
refresh.ts
File metadata and controls
810 lines (712 loc) · 40.4 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
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "fs";
import { dirname, relative, resolve } from "path";
import { fileURLToPath } from "url";
const lifecycleDir = dirname(fileURLToPath(import.meta.url));
const agentDir = process.env.GSTACK_INTELLIGENCE_DIR
? resolve(process.env.GSTACK_INTELLIGENCE_DIR)
: resolve(lifecycleDir, "..");
const skillsDir = resolve(agentDir, "skills");
const referencesDir = resolve(skillsDir, "references");
const sourceRepo = process.env.GSTACK_SOURCE_REPO ?? "garrytan/gstack";
const sourceRef = process.env.GSTACK_SOURCE_REF ?? "main";
const sourceMetadataPath = resolve(skillsDir, "source.json");
const GENERATED_MARKER = "<!-- GSTACK-INTELLIGENCE: GENERATED FILE -->";
const SOURCE_FILES: Record<string, string> = {
// Foundational documents
ethos: "ETHOS.md",
architecture: "ARCHITECTURE.md",
agents: "AGENTS.md",
rootSkillTemplate: "SKILL.md.tmpl",
// Review skill + supplementary files
reviewTemplate: "review/SKILL.md.tmpl",
reviewChecklist: "review/checklist.md",
reviewDesignChecklist: "review/design-checklist.md",
reviewTodosFormat: "review/TODOS-format.md",
reviewGreptileTriage: "review/greptile-triage.md",
reviewSpecialistApiContract: "review/specialists/api-contract.md",
reviewSpecialistDataMigration: "review/specialists/data-migration.md",
reviewSpecialistMaintainability: "review/specialists/maintainability.md",
reviewSpecialistPerformance: "review/specialists/performance.md",
reviewSpecialistRedTeam: "review/specialists/red-team.md",
reviewSpecialistSecurity: "review/specialists/security.md",
reviewSpecialistTesting: "review/specialists/testing.md",
// CSO skill
csoTemplate: "cso/SKILL.md.tmpl",
csoAcknowledgements: "cso/ACKNOWLEDGEMENTS.md",
// Tier 1 skills (event-driven, no user interaction)
shipTemplate: "ship/SKILL.md.tmpl",
benchmarkTemplate: "benchmark/SKILL.md.tmpl",
retroTemplate: "retro/SKILL.md.tmpl",
documentReleaseTemplate: "document-release/SKILL.md.tmpl",
// Tier 2 skills (brief input via issues)
qaTemplate: "qa/SKILL.md.tmpl",
qaIssueTaxonomy: "qa/references/issue-taxonomy.md",
qaReportTemplate: "qa/templates/qa-report-template.md",
qaOnlyTemplate: "qa-only/SKILL.md.tmpl",
designReviewTemplate: "design-review/SKILL.md.tmpl",
planDesignReviewTemplate: "plan-design-review/SKILL.md.tmpl",
investigateTemplate: "investigate/SKILL.md.tmpl",
canaryTemplate: "canary/SKILL.md.tmpl",
// Tier 3 skills (multi-turn conversation)
officeHoursTemplate: "office-hours/SKILL.md.tmpl",
planCeoReviewTemplate: "plan-ceo-review/SKILL.md.tmpl",
planEngReviewTemplate: "plan-eng-review/SKILL.md.tmpl",
designConsultationTemplate: "design-consultation/SKILL.md.tmpl",
autoplanTemplate: "autoplan/SKILL.md.tmpl",
// Additional skills
carefulTemplate: "careful/SKILL.md.tmpl",
designHtmlTemplate: "design-html/SKILL.md.tmpl",
designShotgunTemplate: "design-shotgun/SKILL.md.tmpl",
devexReviewTemplate: "devex-review/SKILL.md.tmpl",
guardTemplate: "guard/SKILL.md.tmpl",
healthTemplate: "health/SKILL.md.tmpl",
landAndDeployTemplate: "land-and-deploy/SKILL.md.tmpl",
learnTemplate: "learn/SKILL.md.tmpl",
planDevexReviewTemplate: "plan-devex-review/SKILL.md.tmpl",
planDevexReviewDxHallOfFame: "plan-devex-review/dx-hall-of-fame.md",
// Additional root-level reference documents
designDoc: "DESIGN.md",
browserDoc: "BROWSER.md",
claudeDoc: "CLAUDE.md",
contributingDoc: "CONTRIBUTING.md",
todosDoc: "TODOS.md",
// Help and documentation
readmeDoc: "README.md",
changelogDoc: "CHANGELOG.md",
skillsGuideDoc: "docs/skills.md",
// Additional skill templates (local-only skills, stored as reference)
browseTemplate: "browse/SKILL.md.tmpl",
codexTemplate: "codex/SKILL.md.tmpl",
freezeTemplate: "freeze/SKILL.md.tmpl",
unfreezeTemplate: "unfreeze/SKILL.md.tmpl",
gstackUpgradeTemplate: "gstack-upgrade/SKILL.md.tmpl",
// OpenClaw integration documentation
openclawDoc: "docs/OPENCLAW.md",
addingHostDoc: "docs/ADDING_A_HOST.md",
openclawAgentsSection: "openclaw/agents-gstack-section.md",
openclawFullClaude: "openclaw/gstack-full-CLAUDE.md",
openclawLiteClaude: "openclaw/gstack-lite-CLAUDE.md",
openclawPlanClaude: "openclaw/gstack-plan-CLAUDE.md",
};
function rawUrl(path: string) {
return `https://raw.githubusercontent.com/${sourceRepo}/${sourceRef}/${path}`;
}
function gitHubApiUrl(path: string) {
return `https://api.github.com/repos/${sourceRepo}/${path}`;
}
function requestHeaders() {
const headers: Record<string, string> = {
"User-Agent": "github-gstack-intelligence-refresh",
"Accept": "application/vnd.github+json",
};
if (process.env.GITHUB_TOKEN) {
headers.Authorization = `Bearer ${process.env.GITHUB_TOKEN}`;
}
return headers;
}
async function fetchText(path: string): Promise<string> {
console.log(`Fetching ${path} from ${sourceRepo}@${sourceRef}`);
const response = await fetch(rawUrl(path), { headers: requestHeaders() });
if (!response.ok) {
throw new Error(`Failed to fetch ${path}: ${response.status} ${response.statusText}`);
}
return await response.text();
}
async function fetchSourceCommit(): Promise<string | null> {
const response = await fetch(gitHubApiUrl(`commits/${sourceRef}`), { headers: requestHeaders() });
if (!response.ok) {
console.warn(
`Could not resolve source commit for ${sourceRepo}@${sourceRef}: ` +
`${response.status} ${response.statusText}. Recording the configured ref only.`,
);
return null;
}
const payload = await response.json();
return payload.sha ?? null;
}
function ensureDir(path: string) {
mkdirSync(path, { recursive: true });
}
function writeFile(path: string, content: string) {
ensureDir(dirname(path));
writeFileSync(path, content.endsWith("\n") ? content : `${content}\n`, "utf-8");
}
function resolveManagedOutput(relativePath: string) {
const absolutePath = resolve(agentDir, relativePath);
const relativePathFromRoot = relative(agentDir, absolutePath);
if (relativePathFromRoot === "" || relativePathFromRoot.startsWith("..")) {
throw new Error(`Refusing to access output outside ${agentDir}: ${relativePath}`);
}
return absolutePath;
}
function readPreviousOutputs(): string[] {
if (!existsSync(sourceMetadataPath)) {
return [];
}
try {
const payload = JSON.parse(readFileSync(sourceMetadataPath, "utf-8")) as { outputs?: unknown };
return Array.isArray(payload.outputs)
? payload.outputs.filter((value): value is string => typeof value === "string")
: [];
} catch (error) {
console.warn(`Could not read previous source metadata from ${sourceMetadataPath}.`, error);
return [];
}
}
function removeStaleOutputs(previousOutputs: string[], currentOutputs: string[]) {
const currentOutputSet = new Set(currentOutputs);
for (const relativePath of previousOutputs) {
if (currentOutputSet.has(relativePath)) {
continue;
}
const absolutePath = resolveManagedOutput(relativePath);
if (existsSync(absolutePath)) {
rmSync(absolutePath, { force: true });
console.log(`Removed stale generated output ${relativePath}`);
}
}
}
function assertOutputsExist(outputs: string[]) {
const missingOutputs = outputs.filter((relativePath) => !existsSync(resolveManagedOutput(relativePath)));
if (missingOutputs.length > 0) {
throw new Error(`Refresh completed without writing expected outputs: ${missingOutputs.join(", ")}`);
}
}
function removeAskUserQuestionFromFrontmatter(content: string): string {
return content.replace(/^ - AskUserQuestion\n/gm, "");
}
function replaceAll(content: string, replacements: Array<[string, string]>): string {
return replacements.reduce(
(next, [searchValue, replacementValue]) => next.replaceAll(searchValue, replacementValue),
content,
);
}
/**
* Replace any remaining {{TOKENS}} with a CI-ADAPTED HTML comment so that
* new upstream tokens never break the build. Intended as a final catch-all
* after all known replacements have been applied.
*/
function replaceRemainingTokens(content: string): string {
return content.replace(/\{\{[A-Z][A-Z0-9_]*\}\}/g, (token) =>
`<!-- CI-ADAPTED: ${token} expansion is omitted. Implement the GitHub-native replacement in the lifecycle layer when this skill is activated. -->`,
);
}
function buildGeneratedHeader(skillName: string, sourcePath: string, sourceCommit: string | null): string {
const sourceMarker = sourceCommit
? `\`${sourceCommit.slice(0, 12)}\``
: `ref \`${sourceRef}\``;
return [
GENERATED_MARKER,
"<!--",
"GENERATED FILE — imported from gstack during run-refresh-gstack.",
"Do not edit this file unless you intentionally forfeit clean upgrades and re-imports.",
"-->",
"",
"> [!CAUTION]",
`> **Do not touch** — imported from gstack. Editing this file forfeits clean upgrades.`,
`> Generated by \`.github-gstack-intelligence/lifecycle/refresh.ts\`.`,
`> Source: \`${sourceRepo}\` @ ${sourceMarker} from \`${sourcePath}\`.`,
"> This copy is adapted for GitHub-native execution and refresh-time extraction.",
"> Re-run `run-refresh-gstack` to pull upstream gstack changes back into this repository.",
"",
"## GitHub-native execution notes",
"",
`- This is the extracted \`/${skillName}\` skill prompt committed into the repository at refresh time.`,
"- Inject GitHub workflow context directly in the invoking lifecycle code instead of relying on local preamble expansion.",
"- Replace interactive approval steps with issue or pull-request comments plus a follow-up GitHub event.",
"- Use repository-local reference files under `.github-gstack-intelligence/skills/references/` instead of `~/.claude/skills/...` paths.",
"",
].join("\n");
}
function buildImportedDocumentHeader(sourcePath: string, sourceCommit: string | null): string {
const sourceMarker = sourceCommit
? `\`${sourceCommit.slice(0, 12)}\``
: `ref \`${sourceRef}\``;
return [
GENERATED_MARKER,
"<!--",
"GENERATED FILE — imported from gstack during run-refresh-gstack.",
"Do not edit this file unless you intentionally forfeit clean upgrades and re-imports.",
"-->",
"",
"> [!CAUTION]",
`> **Do not touch** — imported from gstack. Editing this file forfeits clean upgrades.`,
`> Imported from \`${sourceRepo}\` @ ${sourceMarker} from \`${sourcePath}\`.`,
"> Re-run `run-refresh-gstack` to copy upstream gstack changes back into this repository.",
"",
].join("\n");
}
function wrapImportedMarkdown(content: string, sourcePath: string, sourceCommit: string | null): string {
return `${buildImportedDocumentHeader(sourcePath, sourceCommit)}${content}`;
}
function adaptReviewSkill(template: string, sourceCommit: string | null): string {
const withoutAskUserQuestion = removeAskUserQuestionFromFrontmatter(template);
const withDirectReplacements = replaceAll(withoutAskUserQuestion, [
["{{PREAMBLE}}", buildGeneratedHeader("review", SOURCE_FILES.reviewTemplate, sourceCommit)],
["{{BASE_BRANCH_DETECT}}", "Use the GitHub event payload, checked-out refs, and repository default branch to determine the review base branch."],
["{{PLAN_COMPLETION_AUDIT_REVIEW}}", "If planning artifacts are unavailable, treat the issue body, pull request body, and commit history as the stated intent and continue."],
["{{LEARNINGS_SEARCH}}", "Search repository-local state and issue context first before making review recommendations."],
["{{CONFIDENCE_CALIBRATION}}", "Use the same confidence bar, but report through GitHub comments and persisted state files rather than local CLI prompts."],
["{{DESIGN_REVIEW_LITE}}", "If frontend files changed, use `.github-gstack-intelligence/skills/references/review-design-checklist.md` as the design-review-lite source."],
["{{TEST_COVERAGE_AUDIT_REVIEW}}", "Use the checked-out repository diff and existing tests to reason about coverage; persist only the final GitHub-native findings."],
["{{ADVERSARIAL_STEP}}", "Before finalizing findings, do one adversarial pass that tries to disprove each claim using the checked-out code and current GitHub context."],
["{{LEARNINGS_LOG}}", "Persist durable review outcomes in `.github-gstack-intelligence/state/results/review/` when the lifecycle layer is ready to store them."],
["Read `.claude/skills/review/checklist.md`.", "Read `.github-gstack-intelligence/skills/references/review-checklist.md`."],
["use individual AskUserQuestion calls instead of batching.", "use individual GitHub follow-up comments instead of batching."],
["AskUserQuestion", "GitHub follow-up comment"],
["~/.claude/skills/gstack/bin/gstack-review-log", ".github-gstack-intelligence/state/results/review/review-log.json"],
]);
const withGreptileNote = withDirectReplacements.replace(
/## Step 2\.5: Check for Greptile review comments[\s\S]*?## Step 3: Get the diff/,
[
"## Step 2.5: Check for GitHub review signals",
"",
"If the repository has existing review comments or automation findings, treat them as supplemental inputs.",
"Skip silently when none are available. The extracted skill must remain runnable without local Greptile integration.",
"",
"## Step 3: Get the diff",
].join("\n"),
);
// Apply common replacements to catch tokens added upstream after the review-specific ones
let adapted = replaceAll(withGreptileNote, COMMON_TOKEN_REPLACEMENTS);
adapted = replaceAll(adapted, LOCAL_PATH_REPLACEMENTS);
// Gracefully replace any remaining upstream tokens so new additions never break the build
return replaceRemainingTokens(adapted);
}
function adaptCsoSkill(template: string, sourceCommit: string | null): string {
const withoutAskUserQuestion = removeAskUserQuestionFromFrontmatter(template);
let adapted = replaceAll(withoutAskUserQuestion, [
["{{PREAMBLE}}", buildGeneratedHeader("cso", SOURCE_FILES.csoTemplate, sourceCommit)],
["{{CONFIDENCE_CALIBRATION}}", "Use the same confidence-gated reporting thresholds, but publish the final posture report through GitHub comments and repository-local state instead of local CLI interactions."],
["AskUserQuestion", "GitHub follow-up comment"],
['"Phase 8 can scan your globally installed AI coding agent skills and hooks for malicious patterns. This reads files outside the repo. Want to include this?"', '"Phase 8 can scan globally installed AI coding agent skills and hooks for malicious patterns. Post a GitHub follow-up comment asking for approval before reading files outside the repo."'],
]);
// Apply common replacements to catch tokens added upstream after the cso-specific ones
adapted = replaceAll(adapted, COMMON_TOKEN_REPLACEMENTS);
adapted = replaceAll(adapted, LOCAL_PATH_REPLACEMENTS);
// Gracefully replace any remaining upstream tokens so new additions never break the build
return replaceRemainingTokens(adapted);
}
/**
* Common template token replacements used for CI-adapted skill extraction.
* These map local-execution template variables to GitHub-native equivalents.
*/
const COMMON_TOKEN_REPLACEMENTS: Array<[string, string]> = [
// Branch detection
["{{BASE_BRANCH_DETECT}}", "Use the GitHub event payload, checked-out refs, and repository default branch to determine the review base branch."],
// Browse and local tooling
["{{BROWSE_SETUP}}", "Use Playwright for browser automation. Launch a fresh Chromium instance per workflow run with `npx playwright install chromium`. Replace `$B <command>` patterns with Playwright API calls (`page.goto()`, `page.screenshot()`, `page.evaluate()`, etc.). Browser state does not persist between workflow runs."],
// Confidence and learnings
["{{CONFIDENCE_CALIBRATION}}", "Use the same confidence-gated reporting thresholds, but publish findings through GitHub comments and repository-local state instead of local CLI interactions."],
["{{LEARNINGS_SEARCH}}", "Search repository-local state and issue context first before making recommendations."],
["{{LEARNINGS_LOG}}", "Persist durable outcomes in `.github-gstack-intelligence/state/results/` when the lifecycle layer is ready to store them."],
// Review-adjacent
["{{ADVERSARIAL_STEP}}", "Before finalizing findings, do one adversarial pass that tries to disprove each claim using the checked-out code and current GitHub context."],
["{{DESIGN_REVIEW_LITE}}", "If frontend files changed, use `.github-gstack-intelligence/skills/references/review-design-checklist.md` as the design-review-lite source."],
["{{REVIEW_DASHBOARD}}", "Check for prior review results in `.github-gstack-intelligence/state/results/` and GitHub PR review status."],
// Test-related
["{{TEST_BOOTSTRAP}}", "Use the repository's existing test setup. If no test framework is detected, note it in the output and continue."],
["{{TEST_FAILURE_TRIAGE}}", "Triage test failures by checking whether they are pre-existing (present on the base branch) or introduced by the current changes. Pre-existing failures should be noted but not block the workflow."],
["{{TEST_COVERAGE_AUDIT_SHIP}}", "Use the checked-out repository diff and existing tests to reason about coverage; persist only the final GitHub-native findings."],
["{{TEST_COVERAGE_AUDIT_REVIEW}}", "Use the checked-out repository diff and existing tests to reason about coverage; persist only the final GitHub-native findings."],
["{{TEST_COVERAGE_AUDIT_PLAN}}", "Review the plan's test coverage approach. Identify gaps in edge case handling, error paths, and integration boundaries. Use repository-local test patterns as reference."],
// Plan-related
["{{PLAN_COMPLETION_AUDIT_REVIEW}}", "If planning artifacts are unavailable, treat the issue body, pull request body, and commit history as the stated intent and continue."],
["{{PLAN_COMPLETION_AUDIT_SHIP}}", "Check whether the implementation matches the stated plan. If no plan artifact exists, use the PR body and issue context as the plan reference."],
["{{PLAN_VERIFICATION_EXEC}}", "Verify that the implementation matches the stated plan by comparing the diff against any plan artifacts, issue descriptions, or PR bodies."],
// Ship-specific
["{{SCOPE_DRIFT}}", "Monitor for scope drift by comparing the current diff against the original plan or PR description. Flag changes that extend beyond the stated scope."],
["{{CHANGELOG_WORKFLOW}}", "Generate CHANGELOG entries from the diff and commit history. Use the repository's existing CHANGELOG format if one exists."],
["{{CO_AUTHOR_TRAILER}}", "Co-authored-by: github-gstack-intelligence[bot] <github-gstack-intelligence[bot]@users.noreply.github.com>"],
// QA-specific
["{{QA_METHODOLOGY}}", "Follow the standard QA methodology: navigate pages, test interactions, check console errors, verify responsive layouts, test forms and validation, and document all findings with screenshots and reproduction steps."],
// Slug (local project identification)
["{{SLUG_EVAL}}", 'SLUG=$(basename "$(git rev-parse --show-toplevel 2>/dev/null || pwd)")'],
["{{SLUG_SETUP}}", 'SLUG=$(basename "$(git rev-parse --show-toplevel 2>/dev/null || pwd)")\nmkdir -p .github-gstack-intelligence/state/results'],
// Design-specific
["{{DESIGN_SETUP}}", "Design mockup generation is not available in CI mode. Visual design decisions should be documented in DESIGN.md and reviewed through screenshots and Playwright-captured visual evidence."],
["{{DESIGN_METHODOLOGY}}", "Audit the live site for visual consistency, spacing, hierarchy, and design system adherence. Capture screenshots at multiple viewports. Compare against DESIGN.md if it exists."],
["{{DESIGN_HARD_RULES}}", "AI slop blacklist: reject generic card grids, centered hero sections with stock photos, 3-column feature layouts, gradient buttons with drop shadows, and any pattern that looks like every other AI-generated site."],
["{{DESIGN_OUTSIDE_VOICES}}", "Cross-reference design findings against industry standards and the project's stated design system. Surface conflicting recommendations for user resolution."],
["{{DESIGN_SHOTGUN_LOOP}}", "Generate design variants sequentially in CI mode. Present comparison boards for human review through GitHub comments or issue attachments."],
// Snapshot/command reference (root skill)
["{{SNAPSHOT_FLAGS}}", "Snapshot system is replaced by Playwright's accessibility tree (`page.accessibility.snapshot()`) and screenshot capabilities in CI mode."],
["{{COMMAND_REFERENCE}}", "Browse command reference is replaced by Playwright API in CI mode. Use `page.goto()`, `page.screenshot()`, `page.evaluate()`, `page.click()`, `page.fill()`, `page.locator()`, and `page.waitForSelector()` for equivalent functionality."],
// Benefits-from and outside tooling
["{{BENEFITS_FROM}}", "Check for prior skill outputs in `.github-gstack-intelligence/state/results/` that may provide useful context for this skill execution."],
["{{CODEX_PLAN_REVIEW}}", "Multi-model second-opinion review is not available in CI mode. Use the repository's existing review signals (PR reviews, automated checks) as supplementary inputs."],
// Review coordination
["{{REVIEW_ARMY}}", "In CI mode, a single reviewer handles all categories. If the diff is large (>500 lines) or touches security-sensitive files, note in the output that a second human review is recommended for the affected areas. Do not attempt to spawn parallel reviewers."],
["{{CROSS_REVIEW_DEDUP}}", "Before reporting findings, deduplicate: if the same file:line appears in multiple checklist categories, merge into a single finding with the highest severity. Group related findings (e.g., missing null check + missing test for that path) into one actionable item."],
// Plan file review report (shared dashboard for review chaining)
["{{PLAN_FILE_REVIEW_REPORT}}", "Display a Review Readiness Dashboard by reading all JSON entries from `.github-gstack-intelligence/state/results/review/review-log.json`. For each prior review, show: skill name, status (clean/issues_open), timestamp, and commit hash. Flag any review whose commit hash differs from the current HEAD as potentially stale. If the review log file does not exist or contains no entries, show an empty dashboard and note that no prior reviews have been recorded yet."],
// Spec review loop (design doc / plan approval gate)
["{{SPEC_REVIEW_LOOP}}", "Present the completed spec/plan to the user via GitHub follow-up comment with three options: A) Approve — mark as APPROVED and proceed, B) Revise — specify which sections need changes (loop back to revise those sections only), C) Start over — return to the beginning. Do not proceed to the next phase until the user responds. If running in CI without interactive input, mark as PENDING and note that approval is required via a follow-up comment on the issue."],
// DX framework (developer experience methodology)
["{{DX_FRAMEWORK}}", "DX Framework: Score every developer-facing dimension on a 1-10 scale with evidence. Key dimensions: Getting Started (TTHW — Time To Hello World), API/CLI Ergonomics, Error Messages (actionable, not cryptic), Documentation (complete, accurate, findable), Upgrade Path (non-breaking, guided migration), Dev Environment (reproducible, fast), Community (responsive, welcoming), Measurement (analytics, feedback loops). Use `.github-gstack-intelligence/skills/references/devex-dx-hall-of-fame.md` as the competitive benchmark reference. A score below 7 in any dimension requires a concrete remediation plan in the review output."],
// Deploy bootstrap (deploy platform detection)
["{{DEPLOY_BOOTSTRAP}}", "Detect deploy platform by scanning the repository for platform indicators: `.fly.toml` (Fly.io), `Procfile` (Heroku), `vercel.json` (Vercel), `netlify.toml` (Netlify), `render.yaml` (Render), `railway.json` (Railway), `.github/workflows/*deploy*.yml` or `*cd*.yml` (GitHub Actions CD), `Dockerfile` + cloud config (container-based). Also check CLAUDE.md and `.github-gstack-intelligence/config.json` for persisted `deploymentUrl` or `platform` settings. If a production URL is detected or configured, verify reachability with `curl -sf <url> -o /dev/null -w '%{http_code}'`. Output detected platform, production URL (if any), deploy workflow (if any), and confidence level."],
// Codex second opinion (multi-model challenge)
["{{CODEX_SECOND_OPINION}}", "Multi-model second opinion is not available in CI mode. Instead, perform a self-adversarial check: before proceeding, re-examine your premises from the opposite perspective. For each premise, ask: 'What evidence would disprove this?' If you cannot articulate counter-evidence, the premise may be under-examined. Note any premises that survived the adversarial check with reduced confidence."],
// Design mockup and sketch (visual artifact generation)
["{{DESIGN_MOCKUP}}", "Design mockup generation via local tools is not available in CI mode. If a mockup would be valuable, describe the mockup in detail (layout, components, interactions, responsive behavior) in the GitHub comment so the user can visualize or create it. Reference DESIGN.md if it exists for design system constraints."],
["{{DESIGN_SKETCH}}", "Quick sketch generation via local tools is not available in CI mode. If a sketch would clarify an approach, describe it as a text-based wireframe using ASCII art or a structured layout description in the GitHub comment. Focus on information hierarchy and user flow, not visual polish."],
];
/**
* Common local path replacements for CI-adapted skill extraction.
*/
const LOCAL_PATH_REPLACEMENTS: Array<[string, string]> = [
["Read `.claude/skills/review/checklist.md`.", "Read `.github-gstack-intelligence/skills/references/review-checklist.md`."],
["~/.claude/skills/gstack/bin/gstack-review-log", ".github-gstack-intelligence/state/results/review/review-log.json"],
["~/.claude/skills/gstack/bin/gstack-slug", 'basename "$(git rev-parse --show-toplevel 2>/dev/null || pwd)"'],
["~/.claude/skills/gstack/browse/bin/remote-slug", 'basename "$(git rev-parse --show-toplevel 2>/dev/null || pwd)"'],
["~/.claude/skills/gstack/bin/gstack-diff-scope", "git diff --name-only"],
["~/.claude/skills/gstack/bin/gstack-config", ".github-gstack-intelligence/config.json"],
["~/.claude/skills/gstack/", ".github-gstack-intelligence/skills/"],
["~/.claude/skills/review/", ".github-gstack-intelligence/skills/references/"],
["~/.claude/skills/", ".github-gstack-intelligence/skills/"],
["~/.gstack/projects/", ".github-gstack-intelligence/state/results/"],
["~/.gstack/", ".github-gstack-intelligence/state/"],
[".gstack/", ".github-gstack-intelligence/state/local/"],
["gstack-config set ", "# gstack-config is not available in CI mode: "],
["gstack-config", ".github-gstack-intelligence/config.json"],
];
function adaptGenericSkill(skillName: string, template: string, sourcePath: string, sourceCommit: string | null): string {
let adapted = removeAskUserQuestionFromFrontmatter(template);
const header = buildGeneratedHeader(skillName, sourcePath, sourceCommit);
if (adapted.includes("{{PREAMBLE}}")) {
adapted = adapted.replaceAll("{{PREAMBLE}}", header);
} else {
// Upstream template lacks {{PREAMBLE}} — inject the generated header
// after the YAML frontmatter closing delimiter.
const fmClose = adapted.indexOf("\n---", 1);
if (fmClose !== -1) {
// Skip past the "\n---" (4 chars) to find the next newline after the closing delimiter.
const insertAt = adapted.indexOf("\n", fmClose + 4);
adapted = insertAt !== -1
? adapted.slice(0, insertAt) + "\n\n" + header + "\n" + adapted.slice(insertAt)
: adapted + "\n\n" + header;
} else {
adapted = header + "\n" + adapted;
}
}
adapted = replaceAll(adapted, COMMON_TOKEN_REPLACEMENTS);
adapted = replaceAll(adapted, LOCAL_PATH_REPLACEMENTS);
adapted = replaceAll(adapted, [
["use individual AskUserQuestion calls instead of batching.", "use individual GitHub follow-up comments instead of batching."],
["AskUserQuestion", "GitHub follow-up comment"],
]);
return replaceRemainingTokens(adapted);
}
async function main() {
const sourceCommit = await fetchSourceCommit();
const generatedAt = new Date().toISOString();
const sourceMarker = sourceCommit ?? `ref ${sourceRef}`;
console.log(`Refreshing gstack resources from ${sourceRepo} (${sourceMarker})`);
const fetched = Object.fromEntries(
await Promise.all(
Object.entries(SOURCE_FILES).map(async ([key, path]) => [key, await fetchText(path)] as const),
),
);
ensureDir(skillsDir);
ensureDir(referencesDir);
const managedOutputs = [
// Foundational documents (imported as-is with header)
{
path: "ETHOS.md",
content: wrapImportedMarkdown(fetched.ethos, SOURCE_FILES.ethos, sourceCommit),
},
{
path: "skills/references/gstack-architecture.md",
content: wrapImportedMarkdown(fetched.architecture, SOURCE_FILES.architecture, sourceCommit),
},
{
path: "skills/references/gstack-agents.md",
content: wrapImportedMarkdown(fetched.agents, SOURCE_FILES.agents, sourceCommit),
},
{
path: "skills/references/gstack-root-skill.md",
content: adaptGenericSkill("gstack", fetched.rootSkillTemplate, SOURCE_FILES.rootSkillTemplate, sourceCommit),
},
// Review skill + supplementary references
{
path: "skills/references/review-checklist.md",
content: wrapImportedMarkdown(fetched.reviewChecklist, SOURCE_FILES.reviewChecklist, sourceCommit),
},
{
path: "skills/references/review-design-checklist.md",
content: wrapImportedMarkdown(fetched.reviewDesignChecklist, SOURCE_FILES.reviewDesignChecklist, sourceCommit),
},
{
path: "skills/references/review-todos-format.md",
content: wrapImportedMarkdown(fetched.reviewTodosFormat, SOURCE_FILES.reviewTodosFormat, sourceCommit),
},
{
path: "skills/references/review-greptile-triage.md",
content: wrapImportedMarkdown(fetched.reviewGreptileTriage, SOURCE_FILES.reviewGreptileTriage, sourceCommit),
},
{
path: "skills/references/review-specialist-api-contract.md",
content: wrapImportedMarkdown(fetched.reviewSpecialistApiContract, SOURCE_FILES.reviewSpecialistApiContract, sourceCommit),
},
{
path: "skills/references/review-specialist-data-migration.md",
content: wrapImportedMarkdown(fetched.reviewSpecialistDataMigration, SOURCE_FILES.reviewSpecialistDataMigration, sourceCommit),
},
{
path: "skills/references/review-specialist-maintainability.md",
content: wrapImportedMarkdown(fetched.reviewSpecialistMaintainability, SOURCE_FILES.reviewSpecialistMaintainability, sourceCommit),
},
{
path: "skills/references/review-specialist-performance.md",
content: wrapImportedMarkdown(fetched.reviewSpecialistPerformance, SOURCE_FILES.reviewSpecialistPerformance, sourceCommit),
},
{
path: "skills/references/review-specialist-red-team.md",
content: wrapImportedMarkdown(fetched.reviewSpecialistRedTeam, SOURCE_FILES.reviewSpecialistRedTeam, sourceCommit),
},
{
path: "skills/references/review-specialist-security.md",
content: wrapImportedMarkdown(fetched.reviewSpecialistSecurity, SOURCE_FILES.reviewSpecialistSecurity, sourceCommit),
},
{
path: "skills/references/review-specialist-testing.md",
content: wrapImportedMarkdown(fetched.reviewSpecialistTesting, SOURCE_FILES.reviewSpecialistTesting, sourceCommit),
},
// CSO skill + references
{
path: "skills/references/cso-acknowledgements.md",
content: wrapImportedMarkdown(fetched.csoAcknowledgements, SOURCE_FILES.csoAcknowledgements, sourceCommit),
},
// QA supplementary references
{
path: "skills/references/qa-issue-taxonomy.md",
content: wrapImportedMarkdown(fetched.qaIssueTaxonomy, SOURCE_FILES.qaIssueTaxonomy, sourceCommit),
},
{
path: "skills/references/qa-report-template.md",
content: wrapImportedMarkdown(fetched.qaReportTemplate, SOURCE_FILES.qaReportTemplate, sourceCommit),
},
// Adapted skill prompts — review and cso use specialized adapters
{
path: "skills/review.md",
content: adaptReviewSkill(fetched.reviewTemplate, sourceCommit),
},
{
path: "skills/cso.md",
content: adaptCsoSkill(fetched.csoTemplate, sourceCommit),
},
// Tier 1 skills (event-driven)
{
path: "skills/ship.md",
content: adaptGenericSkill("ship", fetched.shipTemplate, SOURCE_FILES.shipTemplate, sourceCommit),
},
{
path: "skills/benchmark.md",
content: adaptGenericSkill("benchmark", fetched.benchmarkTemplate, SOURCE_FILES.benchmarkTemplate, sourceCommit),
},
{
path: "skills/retro.md",
content: adaptGenericSkill("retro", fetched.retroTemplate, SOURCE_FILES.retroTemplate, sourceCommit),
},
{
path: "skills/document-release.md",
content: adaptGenericSkill("document-release", fetched.documentReleaseTemplate, SOURCE_FILES.documentReleaseTemplate, sourceCommit),
},
// Tier 2 skills (brief input)
{
path: "skills/qa.md",
content: adaptGenericSkill("qa", fetched.qaTemplate, SOURCE_FILES.qaTemplate, sourceCommit),
},
{
path: "skills/qa-only.md",
content: adaptGenericSkill("qa-only", fetched.qaOnlyTemplate, SOURCE_FILES.qaOnlyTemplate, sourceCommit),
},
{
path: "skills/design-review.md",
content: adaptGenericSkill("design-review", fetched.designReviewTemplate, SOURCE_FILES.designReviewTemplate, sourceCommit),
},
{
path: "skills/plan-design-review.md",
content: adaptGenericSkill("plan-design-review", fetched.planDesignReviewTemplate, SOURCE_FILES.planDesignReviewTemplate, sourceCommit),
},
{
path: "skills/investigate.md",
content: adaptGenericSkill("investigate", fetched.investigateTemplate, SOURCE_FILES.investigateTemplate, sourceCommit),
},
{
path: "skills/canary.md",
content: adaptGenericSkill("canary", fetched.canaryTemplate, SOURCE_FILES.canaryTemplate, sourceCommit),
},
// Tier 3 skills (multi-turn)
{
path: "skills/office-hours.md",
content: adaptGenericSkill("office-hours", fetched.officeHoursTemplate, SOURCE_FILES.officeHoursTemplate, sourceCommit),
},
{
path: "skills/plan-ceo-review.md",
content: adaptGenericSkill("plan-ceo-review", fetched.planCeoReviewTemplate, SOURCE_FILES.planCeoReviewTemplate, sourceCommit),
},
{
path: "skills/plan-eng-review.md",
content: adaptGenericSkill("plan-eng-review", fetched.planEngReviewTemplate, SOURCE_FILES.planEngReviewTemplate, sourceCommit),
},
{
path: "skills/design-consultation.md",
content: adaptGenericSkill("design-consultation", fetched.designConsultationTemplate, SOURCE_FILES.designConsultationTemplate, sourceCommit),
},
{
path: "skills/autoplan.md",
content: adaptGenericSkill("autoplan", fetched.autoplanTemplate, SOURCE_FILES.autoplanTemplate, sourceCommit),
},
// Additional skills
{
path: "skills/careful.md",
content: adaptGenericSkill("careful", fetched.carefulTemplate, SOURCE_FILES.carefulTemplate, sourceCommit),
},
{
path: "skills/design-html.md",
content: adaptGenericSkill("design-html", fetched.designHtmlTemplate, SOURCE_FILES.designHtmlTemplate, sourceCommit),
},
{
path: "skills/design-shotgun.md",
content: adaptGenericSkill("design-shotgun", fetched.designShotgunTemplate, SOURCE_FILES.designShotgunTemplate, sourceCommit),
},
{
path: "skills/devex-review.md",
content: adaptGenericSkill("devex-review", fetched.devexReviewTemplate, SOURCE_FILES.devexReviewTemplate, sourceCommit),
},
{
path: "skills/guard.md",
content: adaptGenericSkill("guard", fetched.guardTemplate, SOURCE_FILES.guardTemplate, sourceCommit),
},
{
path: "skills/health.md",
content: adaptGenericSkill("health", fetched.healthTemplate, SOURCE_FILES.healthTemplate, sourceCommit),
},
{
path: "skills/land-and-deploy.md",
content: adaptGenericSkill("land-and-deploy", fetched.landAndDeployTemplate, SOURCE_FILES.landAndDeployTemplate, sourceCommit),
},
{
path: "skills/learn.md",
content: adaptGenericSkill("learn", fetched.learnTemplate, SOURCE_FILES.learnTemplate, sourceCommit),
},
{
path: "skills/plan-devex-review.md",
content: adaptGenericSkill("plan-devex-review", fetched.planDevexReviewTemplate, SOURCE_FILES.planDevexReviewTemplate, sourceCommit),
},
// Additional reference documents
{
path: "skills/references/devex-dx-hall-of-fame.md",
content: wrapImportedMarkdown(fetched.planDevexReviewDxHallOfFame, SOURCE_FILES.planDevexReviewDxHallOfFame, sourceCommit),
},
{
path: "skills/references/gstack-design.md",
content: wrapImportedMarkdown(fetched.designDoc, SOURCE_FILES.designDoc, sourceCommit),
},
{
path: "skills/references/gstack-browser.md",
content: wrapImportedMarkdown(fetched.browserDoc, SOURCE_FILES.browserDoc, sourceCommit),
},
{
path: "skills/references/gstack-claude.md",
content: wrapImportedMarkdown(fetched.claudeDoc, SOURCE_FILES.claudeDoc, sourceCommit),
},
{
path: "skills/references/gstack-contributing.md",
content: wrapImportedMarkdown(fetched.contributingDoc, SOURCE_FILES.contributingDoc, sourceCommit),
},
{
path: "skills/references/gstack-todos.md",
content: wrapImportedMarkdown(fetched.todosDoc, SOURCE_FILES.todosDoc, sourceCommit),
},
// Help and documentation
{
path: "skills/references/gstack-readme.md",
content: wrapImportedMarkdown(fetched.readmeDoc, SOURCE_FILES.readmeDoc, sourceCommit),
},
{
path: "skills/references/gstack-changelog.md",
content: wrapImportedMarkdown(fetched.changelogDoc, SOURCE_FILES.changelogDoc, sourceCommit),
},
{
path: "skills/references/gstack-skills-guide.md",
content: wrapImportedMarkdown(fetched.skillsGuideDoc, SOURCE_FILES.skillsGuideDoc, sourceCommit),
},
// Additional skill templates (local-only, stored as reference)
{
path: "skills/references/gstack-browse-skill.md",
content: adaptGenericSkill("browse", fetched.browseTemplate, SOURCE_FILES.browseTemplate, sourceCommit),
},
{
path: "skills/references/gstack-codex-skill.md",
content: adaptGenericSkill("codex", fetched.codexTemplate, SOURCE_FILES.codexTemplate, sourceCommit),
},
{
path: "skills/references/gstack-freeze-skill.md",
content: adaptGenericSkill("freeze", fetched.freezeTemplate, SOURCE_FILES.freezeTemplate, sourceCommit),
},
{
path: "skills/references/gstack-unfreeze-skill.md",
content: adaptGenericSkill("unfreeze", fetched.unfreezeTemplate, SOURCE_FILES.unfreezeTemplate, sourceCommit),
},
{
path: "skills/references/gstack-upgrade-skill.md",
content: adaptGenericSkill("gstack-upgrade", fetched.gstackUpgradeTemplate, SOURCE_FILES.gstackUpgradeTemplate, sourceCommit),
},
// OpenClaw integration documentation
{
path: "skills/references/gstack-openclaw.md",
content: wrapImportedMarkdown(fetched.openclawDoc, SOURCE_FILES.openclawDoc, sourceCommit),
},
{
path: "skills/references/gstack-adding-host.md",
content: wrapImportedMarkdown(fetched.addingHostDoc, SOURCE_FILES.addingHostDoc, sourceCommit),
},
{
path: "skills/references/openclaw-agents-section.md",
content: wrapImportedMarkdown(fetched.openclawAgentsSection, SOURCE_FILES.openclawAgentsSection, sourceCommit),
},
{
path: "skills/references/openclaw-full-claude.md",
content: wrapImportedMarkdown(fetched.openclawFullClaude, SOURCE_FILES.openclawFullClaude, sourceCommit),
},
{
path: "skills/references/openclaw-lite-claude.md",
content: wrapImportedMarkdown(fetched.openclawLiteClaude, SOURCE_FILES.openclawLiteClaude, sourceCommit),
},
{
path: "skills/references/openclaw-plan-claude.md",
content: wrapImportedMarkdown(fetched.openclawPlanClaude, SOURCE_FILES.openclawPlanClaude, sourceCommit),
},
] as const;
const outputPaths = managedOutputs.map((output) => output.path);
removeStaleOutputs(readPreviousOutputs(), outputPaths);
for (const output of managedOutputs) {
writeFile(resolveManagedOutput(output.path), output.content);
}
assertOutputsExist(outputPaths);
writeFile(
sourceMetadataPath,
JSON.stringify(
{
extractedAt: generatedAt,
source: {
repo: sourceRepo,
ref: sourceRef,
commit: sourceCommit,
},
inputs: Object.values(SOURCE_FILES),
outputs: outputPaths,
},
null,
2,
),
);
console.log("Refresh complete.");
}
main().catch((error) => {
console.error(error);
process.exit(1);
});