mirror of
https://github.com/garrytan/gstack.git
synced 2026-09-27 15:11:47 +02:00
v1.87.6.0 fix: make checks reliable and everyday validation faster (#2898)
* fix: acknowledge seeded plans before invoking review skills * fix: distinguish current plan input from conversation history * fix: keep hermetic plan reviews on manual permissions * fix: distinguish tool discovery from file permission ownership * fix: preserve initial plan mode in observation tests * fix: wait for scope decisions before writing review findings * fix: carry autoplan decisions consistently into review artifacts * test: retain native failure context in periodic assertions * fix: advance active file permissions before queued questions * fix: finish red-team attempts before retry and cleanup * fix: finalize plan format captures and judges before retry * fix: cancel setup-gbrain SDK attempts before fixture cleanup * test: select periodic consumers of the bounded attempt helper * fix native Bash permission cards and queued questions * fix: preserve independent decisions and review scope Keep CEO approach, engineering scope and outside-review choices from approving independent remedies together. Carry declared contracts through DX polish and resolve new gaps before editing the plan. Regenerate every host and retain existing stop boundaries. Validation: 654 focused tests passed across nine files; all-host generation passed. Full free and periodic validation pending. Co-Authored-By: OpenAI Codex <noreply@openai.com> * fix: require approval before design plan amendments Align the Design review philosophy and rating recipe with its section protocol: resolve one proposed fix, then apply only that approved decision and retain honest scores for declined fixes. Validation: 469 focused tests passed across four files; all-host generation passed. Co-Authored-By: OpenAI Codex <noreply@openai.com> * fix: observe native question completion before transcript persistence Match owned completion hooks to submitted choices, reject conflicting or late answers, and retain bounded failure evidence. * test: recognize review posture in acknowledged native questions Require the selected mode acknowledgement, a completed follow-up question, and its current decoded display while preserving existing posture assertions. * fix: preserve settled CEO choices and isolate pending remedies Resolve established approach gates with cited authority and keep independent fixes out of unrelated option commitments and plan amendments. * fix: carry approved DX choices through later review steps Choose documentation approaches within the accepted scope and map resolved confusion points without reopening them through a bulk menu. * test: handle native settings-file edit prompts Keep one-time owned-file approvals and retain the actual sampled Autoplan permission frame with its matching barrier state. * test: accept standard CEO reply directives with tuning footers Recognize the exact trailing preference footer and letter-list directive while preserving current-display and exact acknowledgement checks. * test: scope split reviewers to their generated plan artifacts * test: observe native Bash permissions and invocation results * test: handle owned Bash prompts during mode preference checks * test: preserve synchronous subprocess rejection in Codex fixture * Fix periodic review handoff navigation Recognize review-first and explicit manual-next-step labels while preserving exact action families, manual preference, and ambiguous-menu rejection. Co-authored-by: OpenAI Codex <noreply@openai.com> * Bind pending file permissions to distinct current targets Allow one captured file request to own the complete current dialog while unrelated file work is pending. Preserve same-path ambiguity, exact input ownership, and one-time grant checks. Co-authored-by: OpenAI Codex <noreply@openai.com> * Make paired CEO verification choices genuinely unresolved Start the positive control with proposed manual checks so its unchanged oracle measures two new coverage decisions. Preserve runtime contracts, targets, count bounds, and all assertions. Co-authored-by: OpenAI Codex <noreply@openai.com> * Keep CEO review options and verification within approved scope Audit every offered option for independent add-ons and keep new verification depth pending until accepted. Preserve already requested coverage and trace plan changes to the actual decision. Co-authored-by: OpenAI Codex <noreply@openai.com> * Assemble DX review artifacts before appending the final report Keep early DX evidence above decisions, update artifact sections in place, and append the report using the actual current file suffix. Re-read after deleting an existing report before choosing the append anchor. Co-authored-by: OpenAI Codex <noreply@openai.com> * Keep outside plan reviews exclusive and invocation-owned Follow one preflight-selected backend, terminate failed Codex work before fallback, and allocate extra prompt/output files uniquely. Consume only the current invocation’s completed output. Co-authored-by: OpenAI Codex <noreply@openai.com> * Select periodic completion evaluations for report writer changes Register the shared review resolver for eight missing consumers and regress selection for all nine completion cases without changing their IDs or tiers. Co-authored-by: OpenAI Codex <noreply@openai.com> * Keep permission ambiguity fixtures on the same normalized target Use distinct raw spellings of one target in the four negative fixtures so they exercise the normalized duplicate-owner guard after exact current-file disambiguation. Preserve the existing exception, no-input, diagnostic and cleanup assertions. Co-authored-by: OpenAI Codex <noreply@openai.com> * Clarify preserved contracts in engineering review fixture Co-authored-by: OpenAI Codex <noreply@openai.com> * Recognize the offered DX follow-up handoff Co-authored-by: OpenAI Codex <noreply@openai.com> * Check independent commitments before presenting review options Co-authored-by: OpenAI Codex <noreply@openai.com> * Keep Codex review output and status in one shell invocation Co-authored-by: OpenAI Codex <noreply@openai.com> * Distinguish seeded plans from reports written by a test attempt Co-authored-by: OpenAI Codex <noreply@openai.com> * Recover clipped Autoplan file approvals with bounded viewport resizing Co-authored-by: OpenAI Codex <noreply@openai.com> * Recover clipped Bash approvals before binding the complete command Co-authored-by: OpenAI Codex <noreply@openai.com> * Isolate setup message tests from the shared checkout Run the real installer in a temporary payload with private config, require successful completion, and guard source and binary contents and mtimes. Co-authored-by: OpenAI Codex <noreply@openai.com> * Fix periodic native permission and report completion handling Match the pinned CLI's soft wraps and clipped headings without granting from incomplete frames. Retire completed file requests, retain mode annotations, and ask section captures for a short final acknowledgement after their full report is saved. Co-authored-by: OpenAI Codex <noreply@openai.com> * Preserve review approvals and validate DX comparison artifacts Keep independent remedies and approved amendments explicit. Give the synthetic DX review its existing documentation and validate peer comparison as required analysis alongside four native decisions. Add positive and negative semantic calibrations while preserving review counts, model budgets and prompt size limits. Co-authored-by: OpenAI Codex <noreply@openai.com> * Make the five-finding CEO fixture's application boundary explicit Materialize the request adapter and service composition used by the synthetic payment application. Explicitly declare the revised unregistered-event and mail-telemetry assumptions while preserving uncaught handler errors, the original invoice path and all five unresolved findings. Co-authored-by: OpenAI Codex <noreply@openai.com> * Keep CEO state-path checks scoped to directory preparation Co-authored-by: OpenAI Codex <noreply@openai.com> * Use checked ports and bounded cleanup in pair-agent tests Discover the daemon port from its owned state file, retain startup diagnostics, and await failed-start cleanup. Add occupied-port, early-exit, deadline, and foreign-state regressions while preserving the existing HTTP assertions and hook budgets. Co-authored-by: Codex <noreply@openai.com> * Preserve queued edit identity and recover clipped Bash permissions Distinguish separately queued unfinished edits from mutation of one native tool ID. Keep grants bound to an exact owned request and reject reused IDs, ambiguous inputs, and competing owners. Support the pinned renderer's literal em dash and request a repaint when only the Bash card's top rule is clipped. Grants still require the complete fresh card and an exact native acknowledgment. Validation: 413 integrated parser/event tests passed; private repaint controls and joint source review passed. Full canonical suite and native periodic rerun remain pending. Co-authored-by: Codex <noreply@openai.com> * Keep periodic reviews within their approved contracts and deliverables Carry exact approvals through engineering review, preserve declared contracts when amending CEO plans, and keep prioritization at the requested decision level. Materialize the revised synthetic SDK reference contract while retaining the five original documentation gaps. Accept the observed semicolon in the finite DX handoff menu and register the direct source dependencies used by the engineering cases. Regenerate canonical review documents without changing model budgets, retries, count bands, or native completion assertions. Validation: all-host generation and 275 review, fixture, selection and parity tests passed. Full free-suite and native periodic validation remain pending. Co-authored-by: Codex <noreply@openai.com> * Keep Eng approval cadence and independence guards explicit * Accept ordinary punctuation in manual review handoffs * Recover file permissions alongside queued Bash calls * Carry approved DX work through later review findings * Clarify the synthetic auth internal failure decision * Bound the periodic DX fixture to onboarding changes * Recognize native Design review handoff labels * Hold scope in the integration-choice review fixture * Carry approved Design decisions through review evidence * Capture listener state when feedback reload fails * Exclude workspace caches before checking deprecated flags * Verify Design UI scope against a seeded review plan * Clarify plan review decisions and outside-voice approval flow * Reject setup menus in the Design UI gate * docs: require focused repair validation before final acceptance * fix: separate review commitments within existing prompt budgets * docs: align generation and contributor validation guidance * fix: advance native review prompts and count acknowledged findings * chore: bump version and changelog (v1.87.1.0) Co-Authored-By: OpenAI Codex <noreply@openai.com> * chore: enforce cheap checks and side-effect-free validation previews * fix: handle owned Fetch permissions and oversized native cards * test: ground review fixtures in independent executable contracts * fix: preserve review decisions and verify reports before completion * test: construct the synthetic credential URL without a scanner false positive * test: materialize DX examples and verify their actual local behavior * fix: clarify CEO review decisions and execution order * fix: clarify review workflow ordering and select Design quality checks * Fix review decision gates and incomplete evaluation fixtures Persist CEO and engineering commitment ledgers before menus, preserve exact approvals, and distinguish implementation structure from feature scope. Route Autoplan through the canonical CEO Step 0 ordering. Classify DX findings before requesting approval and ground runtime claims in actual evidence. Complete neutral non-target fixture contracts and accept the captured Design handoff purpose without relaxing its ownership or acknowledgment checks. Record runtime-capability verification in AGENTS.md validation discipline. Validation: 1,335 focused tests passed across 21 files; build, all-host freshness, skill validation (647 artifacts / 107 tracked), and credential checks passed. Prior paid failures are preserved; behavioral acceptance remains pending. * Fix review decision boundaries and owned Read prompts Preserve exact approvals across review options, compare consistent DX milestones, and keep proposed implementation separate from review evidence. Bind modern Read prompts to one immutable native request and wait for its result. Retain captured regression verdicts, correct fixture error names, improve import probe diagnostics, and record focused-first validation discipline in AGENTS.md. * Clarify CEO and engineering review decisions Use explicit decision steps, one engineering ledger, and clear scope/write transitions. Preserve exact approvals and distinguish pending test requirements. Keep unrelated generated content unchanged. * Fix review decision ordering and native evaluation interactions * Clarify engineering decisions and test artifact order * Clarify pending choices and approvals in CEO reviews * Make CEO review phases sequential and clarify completion * Fix Design board submission intent matching * Seed an existing browser test baseline for Autoplan * Document decision-log payloads before state initialization * Preserve exact review scope and decide one change before drafting options * Require input identity before repeating passing model judges * Honor permitted storage throughout CEO review completion * Match complete native permission text within the pinned renderer contract * Align review approvals, independent choices, and bounded validation * fix: preserve reopened approvals and declare fixture interfaces * fix: isolate review artifacts and audit complete questions * fix: match detector artifact permissions to configured storage * fix: complete native permissions and review fixture workflows * fix: order CEO review work and separate engineering guarantees * fix: preserve native validation and separate review choices * fix: clarify review decisions and judge complete report context * fix: constrain review judgments and retain parse failures * fix: compare each affected value before review decisions * fix: make engineering review decisions and completion order explicit * fix: give the complete Autoplan evaluation a bounded chain budget * fix(cso): diagnose forbidden Docker endpoints before tool lookup * fix(reviews): reconcile workflow contracts and generated artifacts after main integration * fix(evals): migrate retained regressions to the native review harness * fix(tests): close native harness and workflow integration regressions * fix(evals): preserve complete permission context and native menu contracts * fix(tests): capture synchronous command output without pipe drain stalls * fix(reviews): clarify decision and completion ordering * fix(reviews): separate decision readiness from final completion checks * refactor(reviews): consolidate decision rules and completion branches * fix(plan-eng-review): order preparation and clarify decision routing * fix(plan-eng-review): restore size and question-format guard parity * fix(plan-eng-review): clarify scope phases and blocked completion * fix(plan-eng-review): unify review flow and report destination * fix(plan-eng-review): define bootstrap and question stage ownership * fix(plan-eng-review): clarify review structure and design lookup * fix(plan-eng-review): render report examples and show saved decisions * fix: consolidate Eng review decisions and select their evaluations * test: cover overlapping terminal attachments and clean merged runner type * fix: preserve Office Hours relationship closings during review updates * fix: retain pasted review targets across slash invocations * docs: preserve validation traces and correct release scope * test: cover pasted targets in both review skills * fix: validate report artifacts before recording success * fix: redact source roots at CSO report boundaries * fix: bind native Design questions before answering * test: select report privacy and native recovery regressions * test: bind rejection predicate in extracted observers * fix: bind complete boxed native questions * test: keep the Design UI fixture on native review * fix: preserve review decisions and evaluation completion outcomes * fix: clarify CEO approval and report completion order * fix: align native review evaluation ownership and completion * fix: bind review evaluators to native decisions and owned artifacts * fix: validate review decisions against native outcomes * fix: preserve review evidence and Autoplan phase handoffs * test: bind review evidence to owned decisions and completion * fix: retain owned native history across compaction * fix(evals): validate current review decisions and setup choices * fix: bind Autoplan reviews and phase completion to current amended input * fix: reconcile native review evidence and close Autoplan phases * test: recognize owned whole-candidate complexity decisions * test: preserve report freshness for approved investigation handoffs * fix: recognize scoped review findings and isolate dual voice fixtures * fix: make review handoffs and question dispatch self-contained * test: recognize complete CEO decisions and procedural pauses * fix: bind current CEO comparison options and risk intervals * test: bind engineering decisions and completion to owned evidence * fix: publish Autoplan phase reports before continuing tools * test: verify actual Autoplan dual-review dispatch evidence * test: select dual review when shared evidence fixtures change * fix: clarify plan review decisions and completion gates * fix: make CEO review decisions and return paths explicit * test: keep Autoplan prompt files inside attempt state * test: preserve source whitespace across permission dialog wraps * fix: publish Autoplan phase reports before continuing * test: recognize current CEO comparisons and reject inactive records * fix: reconcile engineering decision states before completion * test: recognize complete Design decisions and reports * test: verify current engineering decisions before navigation * Recognize source-owned component reduction choices * fix: recognize current CEO ledger and commitment grids * test: supply RequestPolicy context to Eng count fixture * fix: save complete engineering decisions before asking * fix: bind Autoplan publication to the complete phase readback * chore: prepare 1.87.5.0 reliability release * fix: clarify engineering review completion and preserve log failures * fix: bind CEO saved choices and current section ancestry * fix(evals): bind review execution and completion evidence * fix(plan-ceo-review): verify complete decisions before asking * fix(evals): preserve complete engineering choice records * fix(evals): preserve complete review outcomes and bounded fixtures * fix(autoplan): publish phase reports before advancing * fix(plan-ceo-review): validate option fields before asking * fix(plan-eng-review): verify current decisions after answers * fix(evals): bind review decisions and bound fixture scope * fix(plan-ceo-review): verify decision rows and edit saved checkpoints * fix(evals): bind review evidence and scope document lookup * fix(plan-eng-review): update resolution state with its answer * fix(reviews): preserve complete questions through dispatch * fix(evals): recognize completed mode declarations * fix(evals): define cache consistency at wrapper completion * fix(evals): validate owned initial scope and completed review handoffs * fix: assemble complete CEO decision fields before saving * fix: authenticate automatic mode decisions without guessing selectors * fix: bind engineering coverage to approved regression contracts * fix(evals): supply review helpers to native Eng capture * fix(plan-eng-review): preserve the full selected option scope * fix(evals): recognize owned engineering seed and regression evidence * fix(evals): bind engineering retry reports to native approvals * docs: clarify release guarantees (v1.87.5.0) Co-Authored-By: OpenAI Codex <noreply@openai.com> * fix(evals): recognize owned engineering decisions and handoffs * fix(evals): bind engineering decisions and completion evidence * fix(tests): align review contracts and selection fixtures * fix(skills): restore review prompt size limits * fix(plan-eng-review): clarify review execution and completion * fix(evals): preserve configured retries through all supervision layers * Clarify Engineering decisions and report completion * Keep native decision assertions within their source boundary * fix: recognize owned engineering decisions and completed navigation * fix: bind completed auto decisions to their current review * fix: recognize explicit CEO source attribution * fix: dispatch verified CEO decisions without recomposing fields * test: expose existing execution deadlines to review actors * fix: distinguish CEO decision records from incidental headings * test: bind split-scope choices to the registered native actor * test: connect reviewed regressions to required evaluation coverage * Clarify CEO decision routing and completion stages * test: expose existing section review deadlines to fixture actors * test: recognize complete native CEO pacing inventories * test: exclude answered history from current CEO payloads * test: detect phase entry through owned skill HOME aliases * test: validate native review completion and owned report permissions * fix: make Autoplan close packets carry the parent handoff steps * test: assess source-bound HOLD decisions within the existing deadline * fix: keep CEO native decision fields under one formatting authority * test: register integrated review and permission dependencies * test: align native review adapters and finding coverage Preserve explicit AUTO decisions, apply native single-select defaults, and bind complete cropped questions and report permissions to their owned requests. Require seeded review findings instead of crediting setup menus. Keep captured failure controls and additive selection dependencies. The integrated candidate passed 3,099 focused tests across 65 files; affected paid validation remains required before publication. * fix(autoplan): require phase reports before advancing * fix(evals): bind setup and evidence to complete attempts * fix(evals): bind native answers and pending writes to fixture scope Preserve complete option rows when native descriptions wrap, retain current owned Write arguments before journal publication, and keep engineering and DX answers within their declared fixture interfaces. Add captured free regressions without increasing model budgets or relaxing completion checks. * fix(autoplan): verify phase reports across native tool paths Guard owned methodology reads and reviewer dispatches, detect complete driver loads through Bash, and distinguish report-only edits from implementation changes. Follow authenticated native UUID ancestry when journal writes arrive out of order and verify earlier native content for cached phase reads. Keep current close acknowledgment and parent publication in order, require CEO entry before later phases, and register captured failure regressions. * fix(evals): honor native input and collection lifecycles Match complete native Edit panes and truncated question borders, reject stderr close before EOF, and stop the CEO split fixture once its acknowledged scope decisions are collected. Keep semantic validation, process failures, report requirements, and absolute deadlines authoritative. Add captured-event and real-process regressions with selection dependencies. Focused checks pass; final integrated paid and full-suite acceptance remain pending. * fix(autoplan): retain native session ownership across directory changes Recover missed native UUID ancestry through the existing strict graph while preserving ordinary event order and legacy scoping. Bind publication hooks to Claude's original project directory while retaining current cwd for requested file paths. Captured public-event regressions, existing caller checks, and a pinned native CLI loopback verify both fixes. Preserve failed attempts and require fresh paid and final full-suite acceptance. * docs: align evaluation limits and completion version * fix(autoplan): allow authenticated phase reads during journal streaming * fix(evals): bind clipped native questions and owned edit dialogs * fix: preserve overlay retries and bounded cleanup * fix: recognize owned planning preludes in native questions * docs: explain overlay scheduling and cleanup guarantees * fix: require fresh publication after Autoplan phase reruns * Release gstack 1.87.6 * fix: preserve CI paths, process identity, and test deadlines * fix: keep informational setup commands independent of install probes * fix: clarify plan review decisions and bound source audit reports * Fix remaining Windows identity and native path CI failures * Clarify CEO review decision and reviewer-result routing * test: accept no-install planner in retry supervision * fix(ceo-review): make review decisions and report completion explicit * perf(test): add fast PR gates, input-keyed judge reuse and isolated free shards * fix(test): start isolated CEO smoke from its existing project plan * fix(test): repair CI fixture races and preserve retry evidence * fix(ceo-review): clarify approvals, depth and saved completion --------- Co-authored-by: OpenAI Codex <noreply@openai.com>
This commit is contained in:
co-authored by
OpenAI Codex
parent
35dd014c58
commit
636175d349
+332
-479
@@ -9,8 +9,9 @@
|
||||
* Used by skill:check and CI freshness checks.
|
||||
*/
|
||||
|
||||
import { discoverTemplates, discoverSectionTemplates } from './discover-skills';
|
||||
import { writeLlmsTxt } from './gen-llms-txt';
|
||||
import { discoverTemplates, discoverSectionTemplates, includesSkill } from './discover-skills';
|
||||
import { generateLlmsTxt } from './gen-llms-txt';
|
||||
import { generateAgentsDigest, DIGEST_RELPATH, DIGEST_BYTE_BUDGET } from './gen-agents-digest';
|
||||
import { generateDesignChecklistMd } from './resolvers/design-checklist';
|
||||
import { DOM_DUMP_SCRIPT, DOM_DUMP_FILE } from '../lib/dom-dump-script';
|
||||
import * as fs from 'fs';
|
||||
@@ -18,190 +19,123 @@ import * as path from 'path';
|
||||
import type { Host, TemplateContext } from './resolvers/types';
|
||||
import { HOST_PATHS } from './resolvers/types';
|
||||
import { RESOLVERS } from './resolvers/index';
|
||||
import { ALL_HOST_CONFIGS, ALL_HOST_NAMES, resolveHostArg, getHostConfig } from '../hosts/index';
|
||||
import { ALL_HOST_NAMES, resolveHostArg, getHostConfig } from '../hosts/index';
|
||||
import type { HostConfig } from './host-config';
|
||||
|
||||
const ROOT = path.resolve(import.meta.dir, '..');
|
||||
const DRY_RUN = process.argv.includes('--dry-run');
|
||||
import { ALL_MODEL_NAMES, resolveModel, type Model } from './models';
|
||||
|
||||
// ─── GBrain Detection Override ──────────────────────────────
|
||||
// When --respect-detection is passed, read ~/.gstack/gbrain-detection.json
|
||||
// and un-suppress GBRAIN_CONTEXT_LOAD + GBRAIN_SAVE_RESULTS for hosts that
|
||||
// statically suppress them (claude, codex, slate, factory, opencode,
|
||||
// openclaw, cursor, kiro). Detection state is produced by
|
||||
// bin/gstack-gbrain-detect and persisted by `gstack-config gbrain-refresh`
|
||||
// or by ./setup.
|
||||
//
|
||||
// Default (no flag): static suppressedResolvers honored as-is. Used by
|
||||
// `bun run gen:skill-docs` (CI + canonical checked-in SKILL.md files) so
|
||||
// the committed output is reproducible regardless of any developer's
|
||||
// local gbrain installation state. Use `bun run gen:skill-docs:user`
|
||||
// (which adds --respect-detection) for user-local installs.
|
||||
const RESPECT_DETECTION = process.argv.includes('--respect-detection');
|
||||
type HostArg = Host | 'all';
|
||||
|
||||
function loadGbrainOverride(): { detected: boolean } {
|
||||
if (!RESPECT_DETECTION) return { detected: false };
|
||||
/** Internal render settings. Inputs always come from ROOT; output routing and
|
||||
* content links are separate so checks can render canonical bytes into scratch. */
|
||||
export interface GenerationOptions {
|
||||
host?: HostArg;
|
||||
dryRun?: boolean;
|
||||
outputRoot?: string;
|
||||
contentLinkRoot?: string | null;
|
||||
model?: Model | null;
|
||||
catalogMode?: 'trim' | 'full';
|
||||
explainLevel?: 'default' | 'terse';
|
||||
respectDetection?: boolean;
|
||||
log?: (message: string) => void;
|
||||
}
|
||||
|
||||
interface RenderOptions {
|
||||
outputRoot: string;
|
||||
contentLinkRoot: string | null;
|
||||
model: Model | null;
|
||||
catalogMode: 'trim' | 'full';
|
||||
explainLevel: 'default' | 'terse';
|
||||
gbrainDetected: boolean;
|
||||
}
|
||||
|
||||
export interface GeneratedArtifact {
|
||||
relativePath: string;
|
||||
kind: 'skill' | 'section' | 'metadata' | 'openclaw' | 'index' | 'digest' | 'asset';
|
||||
host?: Host;
|
||||
}
|
||||
|
||||
export interface GenerationDiagnostic {
|
||||
kind: 'stale' | 'error' | 'warning' | 'skipped';
|
||||
message: string;
|
||||
host?: Host;
|
||||
relativePath?: string;
|
||||
}
|
||||
|
||||
export interface GenerationResult {
|
||||
exitCode: 0 | 1;
|
||||
artifacts: GeneratedArtifact[];
|
||||
diagnostics: GenerationDiagnostic[];
|
||||
}
|
||||
|
||||
/** Canonical generation never reads local detection state unless opted in. */
|
||||
function loadGbrainOverride(respectDetection: boolean): boolean {
|
||||
if (!respectDetection) return false;
|
||||
const stateDir = process.env.GSTACK_HOME || path.join(process.env.HOME || '', '.gstack');
|
||||
const detectionPath = path.join(stateDir, 'gbrain-detection.json');
|
||||
try {
|
||||
const json = JSON.parse(fs.readFileSync(detectionPath, 'utf-8')) as { gbrain_local_status?: string };
|
||||
// "timeout" = slow-but-healthy engine (#1964); "thin-client" = remote-HTTP
|
||||
// MCP brain with no local engine by design (#2051); "engine-locked" = same
|
||||
// class (#2456): PGLite is single-writer, so a live `gbrain serve` (e.g.
|
||||
// an MCP server) owns the embedded DB — gbrain is installed and healthy,
|
||||
// a legitimate holder has the lock, so a transient lock must not silently
|
||||
// strip brain blocks from every SKILL.md. All usable — same treatment as
|
||||
// "ok", matching gstack-gbrain-detect --is-ok.
|
||||
const USABLE = ['ok', 'timeout', 'thin-client', 'engine-locked'];
|
||||
return { detected: USABLE.includes(json.gbrain_local_status ?? '') };
|
||||
const json = JSON.parse(fs.readFileSync(path.join(stateDir, 'gbrain-detection.json'), 'utf-8'));
|
||||
// Slow, remote, and locked engines are still usable (#1964/#2051/#2456).
|
||||
return ['ok', 'timeout', 'thin-client', 'engine-locked'].includes(json.gbrain_local_status ?? '');
|
||||
} catch {
|
||||
return { detected: false };
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const GBRAIN_OVERRIDE = loadGbrainOverride();
|
||||
|
||||
/**
|
||||
* Compute effective suppressedResolvers for a host, applying the gbrain
|
||||
* detection override when enabled. When the override fires, GBRAIN_*
|
||||
* resolvers are removed from the suppression set so they render in the
|
||||
* generated SKILL.md.
|
||||
*/
|
||||
function effectiveSuppressedResolvers(hostConfig: HostConfig): Set<string> {
|
||||
function effectiveSuppressedResolvers(hostConfig: HostConfig, options: RenderOptions): Set<string> {
|
||||
let list = hostConfig.suppressedResolvers || [];
|
||||
if (GBRAIN_OVERRIDE.detected) {
|
||||
if (options.gbrainDetected) {
|
||||
list = list.filter(r => r !== 'GBRAIN_CONTEXT_LOAD' && r !== 'GBRAIN_SAVE_RESULTS');
|
||||
}
|
||||
return new Set(list);
|
||||
}
|
||||
|
||||
// ─── Host Detection (config-driven) ─────────────────────────
|
||||
|
||||
const HOST_ARG = process.argv.find(a => a.startsWith('--host'));
|
||||
type HostArg = Host | 'all';
|
||||
const HOST_ARG_VAL: HostArg = (() => {
|
||||
if (!HOST_ARG) return 'claude';
|
||||
const val = HOST_ARG.includes('=') ? HOST_ARG.split('=')[1] : process.argv[process.argv.indexOf(HOST_ARG) + 1];
|
||||
if (val === 'all') return 'all';
|
||||
try {
|
||||
return resolveHostArg(val) as Host;
|
||||
} catch {
|
||||
throw new Error(`Unknown host: ${val}. Use ${ALL_HOST_NAMES.join(', ')}, or all.`);
|
||||
/** Parse CLI settings only when executing, never when imported by tests/checks. */
|
||||
function parseGenerationArgs(args: string[]): GenerationOptions {
|
||||
const value = (flag: string): string | undefined => {
|
||||
const index = args.findIndex(arg => arg === flag || arg.startsWith(`${flag}=`));
|
||||
if (index < 0) return undefined;
|
||||
const arg = args[index];
|
||||
const result = arg.startsWith(`${flag}=`) ? arg.slice(flag.length + 1) : args[index + 1];
|
||||
if (!result || result.startsWith('--')) throw new Error(`${flag} requires a value`);
|
||||
return result;
|
||||
};
|
||||
const hostValue = value('--host') ?? 'claude';
|
||||
const host = hostValue === 'all' ? 'all' : resolveHostArg(hostValue) as Host;
|
||||
const modelValue = value('--model');
|
||||
const model = modelValue === undefined ? null : resolveModel(modelValue);
|
||||
if (modelValue !== undefined && !model) {
|
||||
throw new Error(`Unknown model: ${modelValue}. Use ${ALL_MODEL_NAMES.join(', ')}, or a family variant (e.g., claude-opus-4-7, gpt-5.4-mini, o3).`);
|
||||
}
|
||||
})();
|
||||
|
||||
// For single-host mode, HOST is the host. For --host all, it's set per iteration below.
|
||||
let HOST: Host = HOST_ARG_VAL === 'all' ? 'claude' : HOST_ARG_VAL;
|
||||
|
||||
// ─── Model Overlay Selection ────────────────────────────────
|
||||
// --model is explicit. Without it, each host uses HostConfig.defaultModel.
|
||||
// Host defaults are generation fallbacks, not claims that host === model.
|
||||
// Missing overlay file → empty string (graceful).
|
||||
import { ALL_MODEL_NAMES, resolveModel, type Model } from './models';
|
||||
const MODEL_ARG = process.argv.find(a => a.startsWith('--model'));
|
||||
const MODEL_ARG_VAL: Model | null = (() => {
|
||||
if (!MODEL_ARG) return null;
|
||||
const val = MODEL_ARG.includes('=') ? MODEL_ARG.split('=')[1] : process.argv[process.argv.indexOf(MODEL_ARG) + 1];
|
||||
const resolved = resolveModel(val);
|
||||
if (!resolved) {
|
||||
throw new Error(`Unknown model: ${val}. Use ${ALL_MODEL_NAMES.join(', ')}, or a family variant (e.g., claude-opus-4-7, gpt-5.4-mini, o3).`);
|
||||
const catalogMode = value('--catalog-mode') ?? 'trim';
|
||||
if (catalogMode !== 'trim' && catalogMode !== 'full') {
|
||||
throw new Error(`Unknown catalog mode: ${catalogMode}. Use 'trim' (default) or 'full'.`);
|
||||
}
|
||||
return resolved;
|
||||
})();
|
||||
|
||||
function generationModelForHost(host: Host): Model {
|
||||
return MODEL_ARG_VAL ?? getHostConfig(host).defaultModel;
|
||||
const explainLevel = value('--explain-level') ?? 'default';
|
||||
if (explainLevel !== 'default' && explainLevel !== 'terse') {
|
||||
throw new Error(`Unknown explain level: ${explainLevel}. Use 'default' or 'terse'.`);
|
||||
}
|
||||
const outDir = value('--out-dir');
|
||||
const linkRoot = value('--link-root');
|
||||
// Swap-in callers use --link-root for the FINAL serving path (#2692).
|
||||
// Direct --out-dir callers retain their existing links into the render.
|
||||
return {
|
||||
host, model, catalogMode, explainLevel,
|
||||
dryRun: args.includes('--dry-run'),
|
||||
respectDetection: args.includes('--respect-detection'),
|
||||
outputRoot: outDir === undefined ? ROOT : path.resolve(outDir),
|
||||
contentLinkRoot: linkRoot !== undefined ? path.resolve(linkRoot)
|
||||
: outDir !== undefined ? path.resolve(outDir) : null,
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Catalog Mode (v1.45.0.0 T4) ────────────────────────────
|
||||
// 'trim' (default): shorten frontmatter description to lead sentence and
|
||||
// move routing/voice prose into a "## When to invoke" body section.
|
||||
// 'full': legacy v1.44 behavior — full description stays in frontmatter.
|
||||
const CATALOG_MODE_ARG = process.argv.find(a => a.startsWith('--catalog-mode'));
|
||||
const CATALOG_MODE: 'trim' | 'full' = (() => {
|
||||
if (!CATALOG_MODE_ARG) return 'trim';
|
||||
const val = CATALOG_MODE_ARG.includes('=')
|
||||
? CATALOG_MODE_ARG.split('=')[1]
|
||||
: process.argv[process.argv.indexOf(CATALOG_MODE_ARG) + 1];
|
||||
if (val !== 'trim' && val !== 'full') {
|
||||
throw new Error(`Unknown catalog mode: ${val}. Use 'trim' (default) or 'full'.`);
|
||||
}
|
||||
return val;
|
||||
})();
|
||||
|
||||
// ─── Explain-level Overlay ──────────────────────────────────
|
||||
// --explain-level=terse compresses preamble prose (writing-style, completeness,
|
||||
// confusion-protocol, context-health) to a single pointer line at gen time.
|
||||
// Default keeps the runtime-conditional behavior (sections render unconditionally,
|
||||
// the model skips them when EXPLAIN_LEVEL: terse appears in the preamble echo).
|
||||
// Opt-in via the build flag so most users get the runtime-flexible default.
|
||||
const EXPLAIN_LEVEL_ARG = process.argv.find(a => a.startsWith('--explain-level'));
|
||||
const EXPLAIN_LEVEL: 'default' | 'terse' = (() => {
|
||||
if (!EXPLAIN_LEVEL_ARG) return 'default';
|
||||
const val = EXPLAIN_LEVEL_ARG.includes('=')
|
||||
? EXPLAIN_LEVEL_ARG.split('=')[1]
|
||||
: process.argv[process.argv.indexOf(EXPLAIN_LEVEL_ARG) + 1];
|
||||
if (val !== 'default' && val !== 'terse') {
|
||||
throw new Error(`Unknown explain level: ${val}. Use 'default' or 'terse'.`);
|
||||
}
|
||||
return val;
|
||||
})();
|
||||
|
||||
// ─── Out-dir (dev workspace render isolation) ───────────────
|
||||
// --out-dir <abs-dir> redirects ALL generated output (Claude SKILL.md +
|
||||
// sections, external-host trees like .agents/.factory, openclaw docs,
|
||||
// gstack/llms.txt) into a separate (untracked) directory instead of writing
|
||||
// in place. OUTPUTS ONLY: inputs (templates, sections/, host configs) are
|
||||
// always read from ROOT. For the Claude host it ALSO rewrites the literal
|
||||
// section-base path (`~/.claude/skills/gstack/<skill>/sections/`) inside
|
||||
// generated content so section Reads resolve to the rendered copy — that
|
||||
// rewrite stays Claude-only (external hosts have their own path grammar).
|
||||
// Consumers: bin/dev-setup (renders the gbrain `:user` variant for a
|
||||
// Conductor workspace — byte-compat pinned by gen-skill-docs-out-dir tests)
|
||||
// and the former TREE_MUTATING tests, which render into a mkdtemp instead
|
||||
// of mutating the live tree. Default (unset) = in-place, unchanged.
|
||||
/** Parse `--flag <path>` / `--flag=<path>` into an absolute path, or null when absent. */
|
||||
function parsePathFlag(flag: string): string | null {
|
||||
const arg = process.argv.find(a => a.startsWith(flag));
|
||||
if (!arg) return null;
|
||||
const val = arg.includes('=')
|
||||
? arg.split('=')[1]
|
||||
: process.argv[process.argv.indexOf(arg) + 1];
|
||||
if (!val) throw new Error(`${flag} requires a directory path`);
|
||||
return path.resolve(val);
|
||||
}
|
||||
const OUT_DIR: string | null = parsePathFlag('--out-dir');
|
||||
|
||||
// External-host outputs rendered in THIS run, keyed by host. Used after the
|
||||
// render to prune `gstack-*` output dirs whose skill no longer exists: the
|
||||
// generator never deleted, so a retired skill stayed rendered (and linked by
|
||||
// setup) forever, still reading config keys the DEFAULTS table had dropped.
|
||||
const RENDERED_EXTERNAL: Map<string, Set<string>> = new Map();
|
||||
|
||||
// #2692: callers that render into a TMP dir and atomically swap it into place
|
||||
// (bin/gstack-config gbrain-refresh, setup — the #2569 pattern) must pass the
|
||||
// FINAL directory here, or rewriteSectionBase bakes the tmp path
|
||||
// (…/render/claude.tmp.<pid>/…) into the rendered CONTENT and every section
|
||||
// Read dies after the swap. Defaults to OUT_DIR for direct-render callers
|
||||
// (bin/dev-setup, scripts/dev-skill.ts, mkdtemp tests), where out-dir IS the
|
||||
// serving path.
|
||||
const LINK_ROOT: string | null = parsePathFlag('--link-root') ?? OUT_DIR;
|
||||
|
||||
/**
|
||||
* When rendering to an out-dir, repoint the literal section-base path at the
|
||||
* link root (--link-root, defaulting to --out-dir) so section Reads resolve
|
||||
* to the SERVED copy, not the global install.
|
||||
* Surgical: ONLY paths containing `/sections/` are rewritten — bin/, browse/,
|
||||
* docs/ references keep pointing at `~/.claude/skills/gstack` (the global
|
||||
* install, which still works). No-op when neither flag is set.
|
||||
*/
|
||||
function rewriteSectionBase(content: string): string {
|
||||
if (!LINK_ROOT) return content;
|
||||
// Replacement CALLBACK, not a template string: `$` sequences in a
|
||||
// configured path are special in JS replacement strings ($&, $', $1…).
|
||||
/** Repoint only Claude section links, retaining global bin/browse/doc paths. */
|
||||
function rewriteSectionBase(content: string, linkRoot: string | null): string {
|
||||
if (!linkRoot) return content;
|
||||
// Callback replacement preserves literal $ sequences in configured paths.
|
||||
return content.replace(
|
||||
/~\/\.claude\/skills\/gstack\/([^\s)`"'*]+\/sections\/)/g,
|
||||
(_m, p1: string) => `${LINK_ROOT}/${p1}`,
|
||||
(_m, p1: string) => `${linkRoot}/${p1}`,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -224,7 +158,7 @@ function externalSkillName(skillDir: string, frontmatterName?: string): string {
|
||||
return `gstack-${baseName}`;
|
||||
}
|
||||
|
||||
function extractNameAndDescription(content: string): { name: string; description: string } {
|
||||
export function extractNameAndDescription(content: string): { name: string; description: string } {
|
||||
const fmStart = content.indexOf('---\n');
|
||||
if (fmStart !== 0) return { name: '', description: '' };
|
||||
const fmEnd = content.indexOf('\n---', fmStart + 4);
|
||||
@@ -724,12 +658,13 @@ function resolvePlaceholders(
|
||||
ctx: TemplateContext,
|
||||
hostConfig: HostConfig,
|
||||
relTmplPath: string,
|
||||
options: RenderOptions,
|
||||
): string {
|
||||
assertSinglePreamble(tmplContent, relTmplPath);
|
||||
// effectiveSuppressedResolvers() honors --respect-detection: when gbrain is
|
||||
// detected locally, GBRAIN_* resolvers un-suppress. Shared by SKILL.md and
|
||||
// section generation so both paths get the same gbrain-aware behavior.
|
||||
const suppressed = effectiveSuppressedResolvers(hostConfig);
|
||||
const suppressed = effectiveSuppressedResolvers(hostConfig, options);
|
||||
const onePass = (input: string): string =>
|
||||
input.replace(/\{\{(\w+(?::[^}]+)?)\}\}/g, (_match, fullKey) => {
|
||||
const parts = fullKey.split(':');
|
||||
@@ -771,6 +706,7 @@ function buildContext(
|
||||
tmplContent: string,
|
||||
tmplPath: string,
|
||||
host: Host,
|
||||
options: RenderOptions,
|
||||
skillNameOverride?: string,
|
||||
): TemplateContext {
|
||||
const { name: extractedName } = extractNameAndDescription(tmplContent);
|
||||
@@ -785,7 +721,7 @@ function buildContext(
|
||||
const interactive = interactiveMatch ? interactiveMatch[1] === 'true' : undefined;
|
||||
return {
|
||||
skillName, tmplPath, benefitsFrom, host, paths: HOST_PATHS[host],
|
||||
preambleTier, model: generationModelForHost(host), interactive, explainLevel: EXPLAIN_LEVEL,
|
||||
preambleTier, model: options.model ?? getHostConfig(host).defaultModel, interactive, explainLevel: options.explainLevel,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -800,16 +736,14 @@ function processExternalHost(
|
||||
skillDir: string,
|
||||
extractedDescription: string,
|
||||
ctx: TemplateContext,
|
||||
options: RenderOptions,
|
||||
frontmatterName?: string,
|
||||
): { content: string; outputPath: string; outputDir: string; symlinkLoop: boolean } {
|
||||
): { content: string; outputPath: string; symlinkLoop: boolean; metadata?: { outputPath: string; content: string } } {
|
||||
const hostConfig = getHostConfig(host);
|
||||
|
||||
const name = externalSkillName(skillDir === '.' ? '' : skillDir, frontmatterName);
|
||||
// --out-dir mirrors the host tree (outputs only; inputs read from ROOT).
|
||||
const outputDir = path.join(OUT_DIR ?? ROOT, hostConfig.hostSubdir, 'skills', name);
|
||||
if (!RENDERED_EXTERNAL.has(host)) RENDERED_EXTERNAL.set(host, new Set());
|
||||
RENDERED_EXTERNAL.get(host)!.add(name);
|
||||
fs.mkdirSync(outputDir, { recursive: true });
|
||||
const outputDir = path.join(options.outputRoot, hostConfig.hostSubdir, 'skills', name);
|
||||
const outputPath = path.join(outputDir, 'SKILL.md');
|
||||
|
||||
// Guard against symlink loops
|
||||
@@ -842,17 +776,15 @@ function processExternalHost(
|
||||
result = applyHostRewrites(result, hostConfig);
|
||||
|
||||
// Config-driven: generate metadata (e.g., openai.yaml for Codex)
|
||||
if (hostConfig.generation.generateMetadata && !symlinkLoop) {
|
||||
const agentsDir = path.join(outputDir, 'agents');
|
||||
fs.mkdirSync(agentsDir, { recursive: true });
|
||||
const shortDescription = condenseOpenAIShortDescription(extractedDescription);
|
||||
fs.writeFileSync(path.join(agentsDir, 'openai.yaml'), generateOpenAIYaml(name, shortDescription));
|
||||
}
|
||||
const metadata = hostConfig.generation.generateMetadata && !symlinkLoop ? {
|
||||
outputPath: path.join(outputDir, 'agents', 'openai.yaml'),
|
||||
content: generateOpenAIYaml(name, condenseOpenAIShortDescription(extractedDescription)),
|
||||
} : undefined;
|
||||
|
||||
return { content: result, outputPath, outputDir, symlinkLoop };
|
||||
return { content: result, outputPath, symlinkLoop, metadata };
|
||||
}
|
||||
|
||||
function processTemplate(tmplPath: string, host: Host = 'claude'): { outputPath: string; content: string; symlinkLoop?: boolean } {
|
||||
function processTemplate(tmplPath: string, host: Host, options: RenderOptions): { outputPath: string; content: string; symlinkLoop?: boolean; metadata?: { outputPath: string; content: string } } {
|
||||
// Normalize to LF at the entry point. Templates may have CRLF on disk when
|
||||
// checked out on Windows with core.autocrlf=true. Downstream regexes
|
||||
// (processVoiceTriggers, transformFrontmatter) hardcode \n, so without
|
||||
@@ -868,9 +800,9 @@ function processTemplate(tmplPath: string, host: Host = 'claude'): { outputPath:
|
||||
const skillDir = path.relative(ROOT, path.dirname(tmplPath));
|
||||
|
||||
// --out-dir: mirror the skill tree into the out-dir instead of writing in
|
||||
// place (external hosts compute their own OUT_DIR-aware paths below).
|
||||
if (OUT_DIR && host === 'claude') {
|
||||
outputPath = path.join(OUT_DIR, skillDir, path.basename(tmplPath).replace(/\.tmpl$/, ''));
|
||||
// place (external hosts compute their own output paths below).
|
||||
if (host === 'claude') {
|
||||
outputPath = path.join(options.outputRoot, skillDir, path.basename(tmplPath).replace(/\.tmpl$/, ''));
|
||||
}
|
||||
|
||||
// Extract name/description: name drives external skill naming + setup symlinks
|
||||
@@ -880,11 +812,11 @@ function processTemplate(tmplPath: string, host: Host = 'claude'): { outputPath:
|
||||
const { name: extractedName, description: extractedDescription } = extractNameAndDescription(tmplContent);
|
||||
|
||||
const currentHostConfig = getHostConfig(host);
|
||||
const ctx = buildContext(tmplContent, tmplPath, host);
|
||||
const ctx = buildContext(tmplContent, tmplPath, host, options);
|
||||
const skillName = ctx.skillName;
|
||||
|
||||
// Replace placeholders + assert none remain (shared path with section generation).
|
||||
let content = resolvePlaceholders(tmplContent, ctx, currentHostConfig, relTmplPath);
|
||||
let content = resolvePlaceholders(tmplContent, ctx, currentHostConfig, relTmplPath, options);
|
||||
|
||||
// Preprocess voice triggers: fold into description, strip field from frontmatter.
|
||||
// Must run BEFORE transformFrontmatter so all hosts see the updated description,
|
||||
@@ -898,13 +830,15 @@ function processTemplate(tmplPath: string, host: Host = 'claude'): { outputPath:
|
||||
// For Claude: strip sensitive: field (only Factory uses it)
|
||||
// For external hosts: route output, transform frontmatter, rewrite paths
|
||||
let symlinkLoop = false;
|
||||
let metadata: { outputPath: string; content: string } | undefined;
|
||||
if (host === 'claude') {
|
||||
content = transformFrontmatter(content, host);
|
||||
} else {
|
||||
const result = processExternalHost(content, tmplContent, host, skillDir, postProcessDescription, ctx, extractedName || undefined);
|
||||
const result = processExternalHost(content, tmplContent, host, skillDir, postProcessDescription, ctx, options, extractedName || undefined);
|
||||
content = result.content;
|
||||
outputPath = result.outputPath;
|
||||
symlinkLoop = result.symlinkLoop;
|
||||
metadata = result.metadata;
|
||||
}
|
||||
|
||||
// Prepend generated header (after frontmatter)
|
||||
@@ -918,15 +852,15 @@ function processTemplate(tmplPath: string, host: Host = 'claude'): { outputPath:
|
||||
}
|
||||
|
||||
// Catalog trim (Claude only — external hosts have their own frontmatter shapes)
|
||||
if (host === 'claude' && CATALOG_MODE === 'trim') {
|
||||
if (host === 'claude' && options.catalogMode === 'trim') {
|
||||
const trimmed = applyCatalogTrim(content, skillName);
|
||||
if (trimmed) content = trimmed.content;
|
||||
}
|
||||
|
||||
// --out-dir: repoint section-base paths to the out-dir (no-op otherwise).
|
||||
if (host === 'claude') content = rewriteSectionBase(content);
|
||||
if (host === 'claude') content = rewriteSectionBase(content, options.contentLinkRoot);
|
||||
|
||||
return { outputPath, content, symlinkLoop };
|
||||
return { outputPath, content, symlinkLoop, metadata };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -945,7 +879,8 @@ function processTemplate(tmplPath: string, host: Host = 'claude'): { outputPath:
|
||||
function processSectionTemplate(
|
||||
sectionTmplPath: string,
|
||||
skillDir: string,
|
||||
host: Host = 'claude',
|
||||
host: Host,
|
||||
options: RenderOptions,
|
||||
): { outputPath: string; content: string } {
|
||||
const tmplContent = fs.readFileSync(sectionTmplPath, 'utf-8');
|
||||
const relTmplPath = path.relative(ROOT, sectionTmplPath);
|
||||
@@ -956,10 +891,10 @@ function processSectionTemplate(
|
||||
const parentTmplPath = path.join(ROOT, skillDir, 'SKILL.md.tmpl');
|
||||
const parentContent = fs.existsSync(parentTmplPath) ? fs.readFileSync(parentTmplPath, 'utf-8') : '';
|
||||
const parentName = (parentContent && extractNameAndDescription(parentContent).name) || skillDir;
|
||||
const ctx = buildContext(parentContent || tmplContent, parentTmplPath, host, parentName);
|
||||
const ctx = buildContext(parentContent || tmplContent, parentTmplPath, host, options, parentName);
|
||||
|
||||
// Resolve placeholders against the section body (shared guard catches stragglers).
|
||||
let content = resolvePlaceholders(tmplContent, ctx, hostConfig, relTmplPath);
|
||||
let content = resolvePlaceholders(tmplContent, ctx, hostConfig, relTmplPath, options);
|
||||
|
||||
// External hosts: rewrite cross-reference paths/tools (no frontmatter to transform).
|
||||
if (host !== 'claude') {
|
||||
@@ -967,7 +902,7 @@ function processSectionTemplate(
|
||||
} else {
|
||||
// --out-dir: a section may cross-reference another section by absolute path;
|
||||
// repoint those to the out-dir too (no-op when --out-dir is unset).
|
||||
content = rewriteSectionBase(content);
|
||||
content = rewriteSectionBase(content, options.contentLinkRoot);
|
||||
}
|
||||
|
||||
// Plain generated header (no frontmatter to insert after).
|
||||
@@ -976,321 +911,239 @@ function processSectionTemplate(
|
||||
const fileName = path.basename(sectionTmplPath).replace(/\.tmpl$/, '');
|
||||
let outputPath: string;
|
||||
if (host === 'claude') {
|
||||
outputPath = path.join(OUT_DIR || ROOT, skillDir, 'sections', fileName);
|
||||
outputPath = path.join(options.outputRoot, skillDir, 'sections', fileName);
|
||||
} else {
|
||||
const externalName = externalSkillName(skillDir, parentName);
|
||||
outputPath = path.join(OUT_DIR ?? ROOT, hostConfig.hostSubdir, 'skills', externalName, 'sections', fileName);
|
||||
outputPath = path.join(options.outputRoot, hostConfig.hostSubdir, 'skills', externalName, 'sections', fileName);
|
||||
}
|
||||
if (!DRY_RUN) fs.mkdirSync(path.dirname(outputPath), { recursive: true });
|
||||
return { outputPath, content };
|
||||
}
|
||||
|
||||
// ─── Main ───────────────────────────────────────────────────
|
||||
|
||||
function findTemplates(): string[] {
|
||||
return discoverTemplates(ROOT).map(t => path.join(ROOT, t.tmpl));
|
||||
}
|
||||
|
||||
const ALL_HOSTS: Host[] = ALL_HOST_NAMES as Host[];
|
||||
|
||||
/**
|
||||
* Write one generated file, or under DRY_RUN compare it to what is on disk and
|
||||
* print STALE/FRESH. Returns true when the file is stale (dry run) — the caller
|
||||
* folds that into its host-level `hasChanges`. Shared by sections and the
|
||||
* lib-derived assets; the SKILL.md loop keeps its own copy because it also
|
||||
* handles symlink loops and the token budget.
|
||||
*/
|
||||
function emitGenerated(outputPath: string, content: string): boolean {
|
||||
const relOutput = path.relative(OUT_DIR || ROOT, outputPath);
|
||||
if (DRY_RUN) {
|
||||
const existing = fs.existsSync(outputPath) ? fs.readFileSync(outputPath, 'utf-8') : '';
|
||||
if (existing !== content) {
|
||||
console.log(`STALE: ${relOutput}`);
|
||||
return true;
|
||||
}
|
||||
console.log(`FRESH: ${relOutput}`);
|
||||
return false;
|
||||
}
|
||||
if (OUT_DIR) fs.mkdirSync(path.dirname(outputPath), { recursive: true });
|
||||
fs.writeFileSync(outputPath, content);
|
||||
console.log(`GENERATED: ${relOutput}`);
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* The generator's whole executable body. Import-purity contract: importing
|
||||
* this module must NEVER touch the tree — test/gen-skill-docs.test.ts pulls
|
||||
* assertSinglePreamble via require(), test/catalog-trim.test.ts imports
|
||||
* helpers, and before this guard existed every such import regenerated all
|
||||
* 71 SKILL.md in place at module-load time (the root cause of half the
|
||||
* TREE_MUTATING serial shard; hazard class #2532). Pinned by
|
||||
* test/gen-skill-docs-import-purity.test.ts.
|
||||
/** Render each artifact once. Artifact writes go through emit(); stale external
|
||||
* caches are pruned only after a successful host render. Dry runs use the same
|
||||
* inventory as normal generation, including metadata and
|
||||
* shared outputs. Options are per invocation so imports/concurrent runs cannot
|
||||
* inherit another caller's model, detection, or output paths.
|
||||
*
|
||||
* Returns the process exit code. Kept synchronous so the module stays
|
||||
* require()-able (see the llms.txt IIFE note below).
|
||||
* templates + host settings -> render -> emit -> dry-run: compare only
|
||||
* | -> normal: mkdir + write
|
||||
* shared index/digest ---------------+ -> artifact inventory + diagnostics
|
||||
* successful external host -----------------> normal only: prune retired caches
|
||||
*/
|
||||
export async function runGeneration(settings: GenerationOptions = {}): Promise<GenerationResult> {
|
||||
const options: RenderOptions = {
|
||||
outputRoot: path.resolve(settings.outputRoot ?? ROOT),
|
||||
contentLinkRoot: settings.contentLinkRoot ?? null,
|
||||
model: settings.model ?? null,
|
||||
catalogMode: settings.catalogMode ?? 'trim',
|
||||
explainLevel: settings.explainLevel ?? 'default',
|
||||
gbrainDetected: loadGbrainOverride(settings.respectDetection ?? false),
|
||||
};
|
||||
const hosts = settings.host === 'all' ? ALL_HOST_NAMES as Host[] : [settings.host ?? 'claude'];
|
||||
const log = settings.log ?? (() => {});
|
||||
const artifacts: GeneratedArtifact[] = [];
|
||||
const diagnostics: GenerationDiagnostic[] = [];
|
||||
const templates = discoverTemplates(ROOT);
|
||||
const sections = discoverSectionTemplates(ROOT);
|
||||
const rel = (outputPath: string) => path.relative(options.outputRoot, outputPath).split(path.sep).join('/');
|
||||
|
||||
export function main(): number {
|
||||
const hostsToRun: Host[] = HOST_ARG_VAL === 'all' ? ALL_HOSTS : [HOST];
|
||||
const failures: { host: string; error: Error }[] = [];
|
||||
|
||||
for (const currentHost of hostsToRun) {
|
||||
HOST = currentHost;
|
||||
|
||||
try {
|
||||
let hasChanges = false;
|
||||
const tokenBudget: Array<{ skill: string; lines: number; tokens: number }> = [];
|
||||
|
||||
const currentHostConfig = getHostConfig(currentHost);
|
||||
for (const tmplPath of findTemplates()) {
|
||||
const dir = path.basename(path.dirname(tmplPath));
|
||||
|
||||
// includeSkills allowlist (union logic: include minus skip)
|
||||
if (currentHostConfig.generation.includeSkills?.length) {
|
||||
if (!currentHostConfig.generation.includeSkills.includes(dir)) continue;
|
||||
}
|
||||
// skipSkills denylist (subtracts from includeSkills or full set)
|
||||
if (currentHostConfig.generation.skipSkills?.length) {
|
||||
if (currentHostConfig.generation.skipSkills.includes(dir)) continue;
|
||||
}
|
||||
|
||||
const { outputPath, content, symlinkLoop } = processTemplate(tmplPath, currentHost);
|
||||
const relOutput = path.relative(OUT_DIR || ROOT, outputPath);
|
||||
|
||||
if (symlinkLoop) {
|
||||
console.log(`SKIPPED (symlink loop): ${relOutput}`);
|
||||
} else if (DRY_RUN) {
|
||||
const existing = fs.existsSync(outputPath) ? fs.readFileSync(outputPath, 'utf-8') : '';
|
||||
function emit(outputPath: string, content: string, kind: GeneratedArtifact['kind'], host?: Host): void {
|
||||
const relativePath = rel(outputPath);
|
||||
artifacts.push({ relativePath, kind, ...(host ? { host } : {}) });
|
||||
try {
|
||||
if (settings.dryRun) {
|
||||
let existing: string | undefined;
|
||||
try {
|
||||
existing = fs.readFileSync(outputPath, 'utf-8');
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
|
||||
// Windows reports ENOENT for a child of a regular file. Distinguish
|
||||
// that filesystem error from a missing artifact without writing.
|
||||
let parent = path.dirname(outputPath);
|
||||
while (true) {
|
||||
try {
|
||||
if (!fs.statSync(parent).isDirectory()) {
|
||||
throw Object.assign(new Error(`ENOTDIR: output ancestor is not a directory: ${parent}`, { cause: error }), { code: 'ENOTDIR' });
|
||||
}
|
||||
break;
|
||||
} catch (ancestorError) {
|
||||
if ((ancestorError as NodeJS.ErrnoException).code !== 'ENOENT') throw ancestorError;
|
||||
const next = path.dirname(parent);
|
||||
if (next === parent) throw error;
|
||||
parent = next;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (existing !== content) {
|
||||
console.log(`STALE: ${relOutput}`);
|
||||
hasChanges = true;
|
||||
diagnostics.push({ kind: 'stale', relativePath, host, message: `STALE: ${relativePath}` });
|
||||
log(`STALE: ${relativePath}`);
|
||||
} else {
|
||||
console.log(`FRESH: ${relOutput}`);
|
||||
log(`FRESH: ${relativePath}`);
|
||||
}
|
||||
} else {
|
||||
// In-place writes land in existing dirs; --out-dir needs the mirrored
|
||||
// skill dir created first.
|
||||
if (OUT_DIR) fs.mkdirSync(path.dirname(outputPath), { recursive: true });
|
||||
fs.mkdirSync(path.dirname(outputPath), { recursive: true });
|
||||
fs.writeFileSync(outputPath, content);
|
||||
console.log(`GENERATED: ${relOutput}`);
|
||||
}
|
||||
|
||||
// Track token budget
|
||||
const lines = content.split('\n').length;
|
||||
const tokens = Math.round(content.length / 4); // ~4 chars per token
|
||||
tokenBudget.push({ skill: relOutput, lines, tokens });
|
||||
|
||||
// Token ceiling check: warn if any generated SKILL.md exceeds ~40K tokens (160KB).
|
||||
// The ceiling is a "watch for feature bloat" guardrail, not a hard gate. Modern
|
||||
// flagship models have 200K-1M context windows, so 40K (4-20% of window) is fine.
|
||||
// Prompt caching further reduces the marginal cost of larger skills. This ceiling
|
||||
// exists to catch a runaway preamble or resolver that's grown by 10K+ tokens in
|
||||
// a release, not to force compression on carefully-tuned big skills (ship,
|
||||
// plan-ceo-review, office-hours all legitimately pack 25-35K tokens of behavior).
|
||||
const TOKEN_CEILING_BYTES = 160_000;
|
||||
if (content.length > TOKEN_CEILING_BYTES) {
|
||||
console.warn(`⚠️ TOKEN CEILING: ${relOutput} is ${content.length} bytes (~${tokens} tokens), exceeds ${TOKEN_CEILING_BYTES} byte ceiling (~40K tokens)`);
|
||||
log(`GENERATED: ${relativePath}`);
|
||||
}
|
||||
} catch (error) {
|
||||
throw Object.assign(new Error(`${relativePath}: ${(error as Error).message}`), { relativePath });
|
||||
}
|
||||
|
||||
// ─── Section generation (v2 plan T9, Claude-first carve) ───
|
||||
// On-demand sections/*.md for carved skills. Generated for CLAUDE ONLY:
|
||||
// every other host inlines section content via the {{SECTION:id}} resolver
|
||||
// (keeping the full monolith skill), so they need no section files and we
|
||||
// sidestep host-portable section paths until that plumbing lands. No-op for
|
||||
// any skill without a sections/ dir. Mirrors the SKILL.md DRY_RUN handling so
|
||||
// sections participate in the freshness gate.
|
||||
for (const sec of currentHost === 'claude' ? discoverSectionTemplates(ROOT) : []) {
|
||||
if (currentHostConfig.generation.includeSkills?.length &&
|
||||
!currentHostConfig.generation.includeSkills.includes(sec.skillDir)) continue;
|
||||
if (currentHostConfig.generation.skipSkills?.length &&
|
||||
currentHostConfig.generation.skipSkills.includes(sec.skillDir)) continue;
|
||||
|
||||
const { outputPath, content } = processSectionTemplate(path.join(ROOT, sec.tmpl), sec.skillDir, currentHost);
|
||||
const relOutput = path.relative(OUT_DIR || ROOT, outputPath);
|
||||
if (emitGenerated(outputPath, content)) hasChanges = true;
|
||||
|
||||
tokenBudget.push({
|
||||
skill: relOutput,
|
||||
lines: content.split('\n').length,
|
||||
tokens: Math.round(content.length / 4),
|
||||
});
|
||||
}
|
||||
|
||||
// ─── review/design-checklist.md (generated from lib/design-catalog.ts) ───
|
||||
// A Claude-side runtime asset: setup links it from review/ and the other
|
||||
// hosts copy or inline the Claude render (hosts/opencode.ts), so it is
|
||||
// written for the CLAUDE host only. Honors OUT_DIR (outputs-only rule) and
|
||||
// takes part in the DRY_RUN freshness gate exactly like sections above.
|
||||
if (currentHost === 'claude'
|
||||
&& !(currentHostConfig.generation.includeSkills?.length && !currentHostConfig.generation.includeSkills.includes('review'))
|
||||
&& !currentHostConfig.generation.skipSkills?.includes('review')) {
|
||||
// Two runtime assets derived from lib/ source: the checklist (from the
|
||||
// catalog) and the DOM-dump script the browser engines load at runtime
|
||||
// (from lib/dom-dump-script.ts, so the prose never carries the script).
|
||||
const generatedAssets: Array<[string, string]> = [
|
||||
[path.join('review', 'design-checklist.md'), generateDesignChecklistMd()],
|
||||
[DOM_DUMP_FILE, DOM_DUMP_SCRIPT + '\n'],
|
||||
];
|
||||
for (const [rel, content] of generatedAssets) {
|
||||
if (emitGenerated(path.join(OUT_DIR ?? ROOT, rel), content)) hasChanges = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Generate the OpenClaw orchestrator-injection docs (gstack-lite / gstack-full /
|
||||
// gstack-plan CLAUDE.md snippets). Sources live in openclaw/templates/ —
|
||||
// plain markdown, no placeholder resolution — and are copied byte-for-byte
|
||||
// to openclaw/ at gen time.
|
||||
if (currentHost === 'openclaw' && !DRY_RUN) {
|
||||
// Inputs from ROOT, outputs into OUT_DIR when set (outputs-only rule).
|
||||
const openclawTemplatesDir = path.join(ROOT, 'openclaw', 'templates');
|
||||
const openclawOutDir = path.join(OUT_DIR ?? ROOT, 'openclaw');
|
||||
if (OUT_DIR) fs.mkdirSync(openclawOutDir, { recursive: true });
|
||||
for (const variant of ['lite', 'full', 'plan'] as const) {
|
||||
const fileName = `gstack-${variant}-CLAUDE.md`;
|
||||
const content = fs.readFileSync(path.join(openclawTemplatesDir, fileName), 'utf-8');
|
||||
fs.writeFileSync(path.join(openclawOutDir, fileName), content);
|
||||
console.log(`GENERATED: openclaw/${fileName}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (DRY_RUN && hasChanges) {
|
||||
console.error(`\nGenerated SKILL.md files are stale (${currentHost} host). Run: bun run gen:skill-docs --host ${currentHost}`);
|
||||
if (HOST_ARG_VAL !== 'all') return 1;
|
||||
failures.push({ host: currentHost, error: new Error('Stale files detected') });
|
||||
}
|
||||
|
||||
// Print token budget summary
|
||||
if (!DRY_RUN && tokenBudget.length > 0) {
|
||||
tokenBudget.sort((a, b) => b.lines - a.lines);
|
||||
const totalLines = tokenBudget.reduce((s, t) => s + t.lines, 0);
|
||||
const totalTokens = tokenBudget.reduce((s, t) => s + t.tokens, 0);
|
||||
|
||||
console.log('');
|
||||
console.log(`Token Budget (${currentHost} host)`);
|
||||
console.log('═'.repeat(60));
|
||||
for (const t of tokenBudget) {
|
||||
const hostSubdirs = ALL_HOST_CONFIGS.map(c => c.hostSubdir.replace('.', '\\.')).join('|');
|
||||
const name = t.skill.replace(/\/SKILL\.md$/, '').replace(new RegExp(`^\\.(${hostSubdirs})\\/skills\\/`), '');
|
||||
console.log(` ${name.padEnd(30)} ${String(t.lines).padStart(5)} lines ~${String(t.tokens).padStart(6)} tokens`);
|
||||
}
|
||||
console.log('─'.repeat(60));
|
||||
console.log(` ${'TOTAL'.padEnd(30)} ${String(totalLines).padStart(5)} lines ~${String(totalTokens).padStart(6)} tokens`);
|
||||
console.log('');
|
||||
}
|
||||
} catch (e) {
|
||||
failures.push({ host: currentHost, error: e as Error });
|
||||
console.error(`WARNING: ${currentHost} generation failed: ${(e as Error).message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// --host all: any host failure fails the build. Previously only claude failures
|
||||
// exited nonzero, which let a stale or broken external-host output (e.g. a
|
||||
// section that failed to generate for Factory) slip through the freshness gate
|
||||
// silently. With sections fanned out across every host, "all hosts regenerated
|
||||
// in the same commit" is only a real gate if every host failure is fatal here.
|
||||
if (failures.length > 0 && HOST_ARG_VAL === 'all') {
|
||||
console.error(`\n${failures.length} host(s) failed: ${failures.map(f => f.host).join(', ')}`);
|
||||
return 1;
|
||||
}
|
||||
// Single host dry-run failure already handled above
|
||||
function failed(error: unknown, host?: Host): void {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
diagnostics.push({ kind: 'error', host, message, relativePath: (error as { relativePath?: string })?.relativePath });
|
||||
}
|
||||
|
||||
// After all hosts processed, warn if prefix patches may need re-applying
|
||||
if (!DRY_RUN) {
|
||||
for (const host of hosts) {
|
||||
try {
|
||||
const hostConfig = getHostConfig(host);
|
||||
const tokenBudget: Array<{ skill: string; lines: number; tokens: number }> = [];
|
||||
const renderedNames = new Set<string>();
|
||||
for (const template of templates) {
|
||||
const skillDir = path.dirname(template.tmpl);
|
||||
if (!includesSkill(hostConfig, skillDir)) continue;
|
||||
const result = processTemplate(path.join(ROOT, template.tmpl), host, options);
|
||||
const relativePath = rel(result.outputPath);
|
||||
if (host !== 'claude') renderedNames.add(path.basename(path.dirname(result.outputPath)));
|
||||
if (result.symlinkLoop) {
|
||||
diagnostics.push({ kind: 'skipped', relativePath, host, message: `SKIPPED (symlink loop): ${relativePath}` });
|
||||
log(`SKIPPED (symlink loop): ${relativePath}`);
|
||||
continue;
|
||||
}
|
||||
emit(result.outputPath, result.content, 'skill', host);
|
||||
if (result.metadata) emit(result.metadata.outputPath, result.metadata.content, 'metadata', host);
|
||||
tokenBudget.push({ skill: relativePath, lines: result.content.split('\n').length, tokens: Math.round(result.content.length / 4) });
|
||||
const TOKEN_CEILING_BYTES = 160_000;
|
||||
if (result.content.length > TOKEN_CEILING_BYTES) {
|
||||
const message = `⚠️ TOKEN CEILING: ${relativePath} is ${result.content.length} bytes (~${Math.round(result.content.length / 4)} tokens), exceeds ${TOKEN_CEILING_BYTES} byte ceiling (~40K tokens)`;
|
||||
diagnostics.push({ kind: 'warning', host, relativePath, message });
|
||||
}
|
||||
}
|
||||
|
||||
// Claude carves sections; every external host inlines these templates.
|
||||
for (const section of host === 'claude' ? sections : []) {
|
||||
if (!includesSkill(hostConfig, section.skillDir)) continue;
|
||||
const result = processSectionTemplate(path.join(ROOT, section.tmpl), section.skillDir, host, options);
|
||||
emit(result.outputPath, result.content, 'section', host);
|
||||
tokenBudget.push({ skill: rel(result.outputPath), lines: result.content.split('\n').length, tokens: Math.round(result.content.length / 4) });
|
||||
}
|
||||
|
||||
// Claude owns these catalog-derived runtime assets. Use the same host
|
||||
// inclusion rule and compare-or-write path as every other artifact.
|
||||
if (host === 'claude' && includesSkill(hostConfig, 'review')) {
|
||||
emit(path.join(options.outputRoot, 'review', 'design-checklist.md'),
|
||||
generateDesignChecklistMd(), 'asset', host);
|
||||
emit(path.join(options.outputRoot, DOM_DUMP_FILE), DOM_DUMP_SCRIPT + '\n', 'asset', host);
|
||||
}
|
||||
|
||||
if (host === 'openclaw') {
|
||||
for (const variant of ['lite', 'full', 'plan'] as const) {
|
||||
const fileName = `gstack-${variant}-CLAUDE.md`;
|
||||
emit(path.join(options.outputRoot, 'openclaw', fileName),
|
||||
fs.readFileSync(path.join(ROOT, 'openclaw', 'templates', fileName), 'utf-8'), 'openclaw', host);
|
||||
}
|
||||
}
|
||||
|
||||
// A failed render exits this try before pruning: its inventory is partial.
|
||||
// Only remove generated directories owned by this host; sidecars and user
|
||||
// skills survive. Dry runs never create, rewrite, or remove any directory.
|
||||
if (!settings.dryRun && host !== 'claude') {
|
||||
const skillsRoot = path.join(options.outputRoot, hostConfig.hostSubdir, 'skills');
|
||||
let entries: fs.Dirent[] = [];
|
||||
try {
|
||||
entries = fs.readdirSync(skillsRoot, { withFileTypes: true });
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (entry.isSymbolicLink() || !entry.isDirectory() || !entry.name.startsWith('gstack-') || renderedNames.has(entry.name)) continue;
|
||||
// Keep the old render usable until setup has migrated installed copies/links.
|
||||
if (entry.name === 'gstack-claude' && process.env.GSTACK_DEFER_CLAUDE_RENAME_PRUNE === '1') continue;
|
||||
let generated = false;
|
||||
try {
|
||||
generated = fs.readFileSync(path.join(skillsRoot, entry.name, 'SKILL.md'), 'utf-8').includes('<!-- AUTO-GENERATED from');
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
|
||||
}
|
||||
if (!generated) {
|
||||
log(` kept ${host} skills/${entry.name}: not a gstack render (no generated banner)`);
|
||||
continue;
|
||||
}
|
||||
fs.rmSync(path.join(skillsRoot, entry.name), { recursive: true, force: true });
|
||||
log(` pruned stale ${host} render: ${entry.name}`);
|
||||
if (entry.name === 'gstack-claude') {
|
||||
log(' /claude is now /claude-code. Run ./setup to migrate installed skill links; generation only updates render files.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!settings.dryRun && tokenBudget.length > 0) {
|
||||
tokenBudget.sort((a, b) => b.lines - a.lines);
|
||||
log(`\nToken Budget (${host} host)`);
|
||||
log('═'.repeat(60));
|
||||
for (const item of tokenBudget) {
|
||||
const name = item.skill.replace(/\/SKILL\.md$/, '').replace(`${hostConfig.hostSubdir}/skills/`, '');
|
||||
log(` ${name.padEnd(30)} ${String(item.lines).padStart(5)} lines ~${String(item.tokens).padStart(6)} tokens`);
|
||||
}
|
||||
log('─'.repeat(60));
|
||||
log(` ${'TOTAL'.padEnd(30)} ${String(tokenBudget.reduce((sum, t) => sum + t.lines, 0)).padStart(5)} lines ~${String(tokenBudget.reduce((sum, t) => sum + t.tokens, 0)).padStart(6)} tokens\n`);
|
||||
}
|
||||
} catch (error) {
|
||||
failed(error, host);
|
||||
}
|
||||
}
|
||||
|
||||
// Shared artifacts are awaited in both modes. A failure must reach the CLI
|
||||
// exit code, never disappear in a fire-and-forget auxiliary writer.
|
||||
try {
|
||||
const configPath = path.join(process.env.HOME || '', '.gstack', 'config.yaml');
|
||||
if (fs.existsSync(configPath)) {
|
||||
const config = fs.readFileSync(configPath, 'utf-8');
|
||||
if (/^skill_prefix:\s*true/m.test(config)) {
|
||||
console.log('\nNote: skill_prefix is true. Run gstack-relink to re-apply name: patches (it patches both the install and any active gbrain render).');
|
||||
}
|
||||
}
|
||||
} catch { /* non-fatal */ }
|
||||
}
|
||||
|
||||
// Prune stale external-host outputs. A run always renders every skill for the
|
||||
// chosen host(s) (there is no per-skill filter), so any `gstack-*` directory
|
||||
// left in <host>/skills/ that this run did not write belongs to a skill that
|
||||
// no longer exists. Symlinks (the `gstack` sidecar), non-prefixed entries, and
|
||||
// gstack-* directories without the generated banner (someone's own skill) are
|
||||
// never touched.
|
||||
if (!DRY_RUN) {
|
||||
// A host whose generation threw has a PARTIAL rendered set: pruning against
|
||||
// it would delete every valid render the loop never reached. Skip those.
|
||||
const failedHosts = new Set(failures.map((f) => f.host));
|
||||
for (const [host, names] of RENDERED_EXTERNAL) {
|
||||
if (failedHosts.has(host)) { console.error(` prune skipped for ${host}: generation failed, rendered set is partial`); continue; }
|
||||
const skillsRoot = path.join(OUT_DIR ?? ROOT, getHostConfig(host as Host).hostSubdir, 'skills');
|
||||
let entries: fs.Dirent[] = [];
|
||||
try { entries = fs.readdirSync(skillsRoot, { withFileTypes: true }); } catch { continue; }
|
||||
for (const e of entries) {
|
||||
if (e.isSymbolicLink() || !e.isDirectory() || !e.name.startsWith('gstack-') || names.has(e.name)) continue;
|
||||
// setup migrates installed links/copies before retiring this renamed render.
|
||||
// A failed migration must remain usable through later build/generation passes.
|
||||
if (e.name === 'gstack-claude' && process.env.GSTACK_DEFER_CLAUDE_RENAME_PRUNE === '1') continue;
|
||||
// Only a directory we provably rendered (the generated banner in its
|
||||
// SKILL.md) may be deleted whole — a hand-authored gstack-* dir is kept.
|
||||
let generated = false;
|
||||
try { generated = fs.readFileSync(path.join(skillsRoot, e.name, 'SKILL.md'), 'utf-8').includes('<!-- AUTO-GENERATED from'); } catch { generated = false; }
|
||||
if (!generated) { console.log(` kept ${host} skills/${e.name}: not a gstack render (no generated banner)`); continue; }
|
||||
fs.rmSync(path.join(skillsRoot, e.name), { recursive: true, force: true });
|
||||
console.log(` pruned stale ${host} render: ${e.name}`);
|
||||
if (e.name === 'gstack-claude') {
|
||||
console.log(' /claude is now /claude-code. Run ./setup to migrate installed skill links; generation only updates render files.');
|
||||
}
|
||||
}
|
||||
const index = await generateLlmsTxt();
|
||||
emit(path.join(options.outputRoot, 'gstack', 'llms.txt'), index.content, 'index');
|
||||
for (const warning of index.warnings) diagnostics.push({ kind: 'warning', message: `[gen-llms-txt] ${warning}` });
|
||||
} catch (error) {
|
||||
failed(error);
|
||||
}
|
||||
try {
|
||||
const digest = generateAgentsDigest();
|
||||
emit(path.join(options.outputRoot, DIGEST_RELPATH), digest.content, 'digest');
|
||||
if (!settings.dryRun) log(`[gen-agents-digest] ${DIGEST_RELPATH}: ${digest.bytes} bytes (budget ${DIGEST_BYTE_BUDGET})`);
|
||||
} catch (error) {
|
||||
failed(error);
|
||||
}
|
||||
|
||||
return { exitCode: diagnostics.some(d => d.kind === 'error' || d.kind === 'stale') ? 1 : 0, artifacts, diagnostics };
|
||||
}
|
||||
|
||||
// Regenerate gstack/llms.txt — single-file capability index for AI agents.
|
||||
// Runs after SKILL.md generation so it sees current skill descriptions and
|
||||
// browse command list. Wrapped in an IIFE so the await-import doesn't make
|
||||
// this module async (test/gen-skill-docs.test.ts uses require() to pull
|
||||
// extractVoiceTriggers/processVoiceTriggers, which fails on async modules).
|
||||
// Freshness is asserted in test/llms-txt-shape.test.ts.
|
||||
if (!DRY_RUN) {
|
||||
void (async () => {
|
||||
try {
|
||||
const result = await writeLlmsTxt(
|
||||
// Outputs-only rule: under --out-dir even this index lands there
|
||||
// (a catalog-mode render must never rewrite the tracked llms.txt).
|
||||
OUT_DIR ? { outputPath: path.join(OUT_DIR, 'gstack', 'llms.txt') } : {},
|
||||
);
|
||||
if (result.warnings.length > 0) {
|
||||
for (const w of result.warnings) console.error(`[gen-llms-txt] WARN: ${w}`);
|
||||
} else {
|
||||
console.log(`[gen-llms-txt] gstack/llms.txt: ${result.skills.length} skills, ${result.browseCommands.length} browse commands`);
|
||||
}
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
console.error(`[gen-llms-txt] FAILED: ${msg}`);
|
||||
/** Importing this module never executes generation or reads CLI/user settings.
|
||||
* Async main is require()-compatible: only top-level await would break callers. */
|
||||
export async function main(args = process.argv.slice(2)): Promise<number> {
|
||||
try {
|
||||
const settings = parseGenerationArgs(args);
|
||||
const result = await runGeneration({ ...settings, log: console.log });
|
||||
for (const diagnostic of result.diagnostics) {
|
||||
if (diagnostic.kind === 'error') console.error(`ERROR${diagnostic.host ? ` (${diagnostic.host})` : ''}: ${diagnostic.message}`);
|
||||
if (diagnostic.kind === 'warning') console.error(diagnostic.message);
|
||||
}
|
||||
// Regenerate agents-digest/gstack-AGENTS.md — the instruction-only tier
|
||||
// for rules-reading hosts with no skill install. Committed artifact;
|
||||
// freshness + byte budget asserted in test/agents-digest.test.ts.
|
||||
try {
|
||||
const { writeAgentsDigest, DIGEST_BYTE_BUDGET } = await import('./gen-agents-digest');
|
||||
// Outputs-only rule: under --out-dir the digest lands there too — a
|
||||
// workspace render must never rewrite the tracked committed artifact.
|
||||
const digest = writeAgentsDigest(OUT_DIR ? { outRoot: OUT_DIR } : {});
|
||||
console.log(`[gen-agents-digest] agents-digest/gstack-AGENTS.md: ${digest.bytes} bytes (budget ${DIGEST_BYTE_BUDGET})`);
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
console.error(`[gen-agents-digest] FAILED: ${msg}`);
|
||||
// The digest is a committed freshness-gated artifact: a local build
|
||||
// that silently ships it stale defers the red to CI. Fail the build.
|
||||
process.exitCode = 1;
|
||||
if (result.diagnostics.some(d => d.kind === 'stale')) {
|
||||
console.error(`\nGenerated files are stale. Run: bun run gen:skill-docs --host ${settings.host ?? 'claude'}`);
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
return 0;
|
||||
if (!settings.dryRun) {
|
||||
try {
|
||||
const config = fs.readFileSync(path.join(process.env.HOME || '', '.gstack', 'config.yaml'), 'utf-8');
|
||||
if (/^skill_prefix:\s*true/m.test(config)) {
|
||||
console.log('\nNote: skill_prefix is true. Run gstack-relink to re-apply name: patches (it patches both the install and any active gbrain render).');
|
||||
}
|
||||
} catch { /* optional local install note */ }
|
||||
}
|
||||
return result.exitCode;
|
||||
} catch (error) {
|
||||
console.error(`ERROR: ${(error as Error).message}`);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (import.meta.main) {
|
||||
// Failure exits are immediate (matching the old top-level process.exit
|
||||
// behavior); success leaves the event loop to drain so the llms.txt
|
||||
// fire-and-forget IIFE inside main() finishes its write.
|
||||
const code = main();
|
||||
if (code !== 0) process.exit(code);
|
||||
void main().then(code => { process.exitCode = code; });
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user