Skill Tracer
Skills › gstack › gstack › runtime-root.ts

runtime-root.ts

129 lines · scripts/resolvers/runtime-root.ts at 3f79d81

1/**
2 * Runtime root for env-var hosts (C1, #1159): the one owner of how generated
3 * bash finds gstack on Codex and every other `usesEnvVars` host.
4 *
5 * Those hosts run each fenced block in a fresh shell, so `GSTACK_ROOT`, `B`,
6 * `D` and `P` set by an earlier block are gone. The preamble's root resolution and
7 * the per-fence prelude come from `runtimeRootPrelude()`; `insertRuntimePreludes()`
8 * is the single post-render pass (gen-skill-docs, before rewriteInstallRoot)
9 * that puts it into every fence that uses these variables without assigning
10 * them. Claude output is returned unchanged.
11 *
12 * Precedence: an exported `GSTACK_ROOT` that contains `bin/` and `lib/`; then,
13 * on a per-install render, the literal install root (no git call); otherwise the
14 * repo-local install, then the host's global root (`CODEX_HOME` on Codex). No
15 * root prints one line naming what was tried and the setup command, and exits.
16 */
17import { getHostConfig } from '../../hosts/index';
18import { toShellPath, type TemplateContext } from './types';
20/** Per-fence byte budget for the prelude (T-ENG1), asserted by the INV-3 test. */
21export const PRELUDE_BYTE_BUDGET = 400;
22/**
23 * make-pdf's dev-build override (E2), appended to `P`'s assignment. It is the
24 * one fixed segment outside PRELUDE_BYTE_BUDGET: root plus `P=...` fits the
25 * budget like `B`/`D` do, and the override is needed in every block that runs
26 * `$P` so readiness and use name the same binary.
27 */
28export const MAKE_PDF_OVERRIDE = ';[ -x "${MAKE_PDF_BIN:-}" ]&&P=$MAKE_PDF_BIN||:';
30const ROOT_VARS = /\$\{?GSTACK_(?:ROOT|BIN|BROWSE|DESIGN|MAKE_PDF)\b/;
31const assigns = (name: string) => new RegExp(`(?:^|[\\s;&|(])${name}=`, 'm');
32const uses = (name: string) => new RegExp(`\\$\\{?${name}\\b`);
34/**
35 * Root resolution only (sets `GSTACK_ROOT`). Kept compact: it repeats in every
36 * fence that needs it, under PRELUDE_BYTE_BUDGET together with its derived vars.
37 */
38function resolveRoot(ctx: TemplateContext): string {
39 const host = getHostConfig(ctx.host);
40 const fix = `Fix: ./setup --host ${host.name} from your gstack checkout; ./setup --status shows it.`;
41 const exported = '[ -d "${GSTACK_ROOT:-/-}/bin" ]&&[ -d "$GSTACK_ROOT/lib" ]||';
42 if (ctx.installRoot) {
43 return `${exported}{ GSTACK_ROOT="${ctx.installRoot.replace(/\/+$/, '')}";[ -d "$GSTACK_ROOT/bin" ]||{ echo "gstack: no install found (tried $GSTACK_ROOT). ${fix}">&2;exit 1;};}`;
44 }
45 const global = host.name === 'codex' ? '${CODEX_HOME:-~/.codex}/skills/gstack' : `~/${host.globalRoot}`;
46 return `${exported}{ _r=$(git rev-parse --show-toplevel 2>/dev/null)/${host.localSkillRoot};[ -d "$_r/bin" ]||_r=${global};[ -d "$_r/bin" ]||{ echo "gstack: no install found (tried $_r). ${fix}">&2;exit 1;};GSTACK_ROOT=$_r;}`;
49const DERIVED: Record<string, string> = { BIN: 'bin', BROWSE: 'browse/dist', DESIGN: 'design/dist', MAKE_PDF: 'make-pdf/dist' };
51/** The preamble's root resolution: GSTACK_ROOT plus GSTACK_BIN. */
52export function runtimeRootPrelude(ctx: TemplateContext): string {
53 if (!getHostConfig(ctx.host).usesEnvVars) return '';
54 return `${resolveRoot(ctx)}\nGSTACK_BIN=$GSTACK_ROOT/bin`;
57/**
58 * Lines that assign `B` (browse), `D` (design) or `P` (make-pdf). BROWSE SETUP,
59 * DESIGN SETUP, MAKE-PDF SETUP and the prelude all use this, so a later fence
60 * runs the binary setup checked. Env-var hosts derive from `GSTACK_ROOT`, which
61 * the prelude already points at the repo-local install when one exists; other
62 * hosts keep their repo-local-first probe. make-pdf's binary is
63 * `make-pdf/dist/pdf`, and `MAKE_PDF_BIN` (a contributor dev build) wins on
64 * every host.
65 */
66export function binaryAssignment(ctx: TemplateContext, tool: 'browse' | 'design' | 'make-pdf'): string {
67 if (tool === 'make-pdf') {
68 if (getHostConfig(ctx.host).usesEnvVars) return `P=$GSTACK_ROOT/make-pdf/dist/pdf${MAKE_PDF_OVERRIDE}`;
69 return `_ROOT=$(git rev-parse --show-toplevel 2>/dev/null)
70P=""
71[ -n "$MAKE_PDF_BIN" ] && [ -x "$MAKE_PDF_BIN" ] && P="$MAKE_PDF_BIN"
72[ -z "$P" ] && [ -n "$_ROOT" ] && [ -x "$_ROOT/${ctx.paths.localSkillRoot}/make-pdf/dist/pdf" ] && P="$_ROOT/${ctx.paths.localSkillRoot}/make-pdf/dist/pdf"
73[ -z "$P" ] && P="${toShellPath(ctx.paths.skillRoot)}/make-pdf/dist/pdf"`;
74 }
75 const v = tool === 'browse' ? 'B' : 'D';
76 const dir = tool === 'browse' ? ctx.paths.browseDir : ctx.paths.designDir;
77 if (getHostConfig(ctx.host).usesEnvVars) return `${v}=$GSTACK_ROOT/${tool}/dist/${tool}`;
78 return `_ROOT=$(git rev-parse --show-toplevel 2>/dev/null)
79${v}=""
80[ -n "$_ROOT" ] && [ -x "$_ROOT/${ctx.paths.localSkillRoot}/${tool}/dist/${tool}" ] && ${v}="$_ROOT/${ctx.paths.localSkillRoot}/${tool}/dist/${tool}"
81[ -z "$${v}" ] && ${v}="${toShellPath(dir)}/${tool}"`;
84/** The prelude one fence needs, or '' when it needs none. */
85export function fencePrelude(ctx: TemplateContext, body: string): string {
86 if (!getHostConfig(ctx.host).usesEnvVars) return '';
87 const needB = uses('B').test(body) && !assigns('B').test(body);
88 const needD = uses('D').test(body) && !assigns('D').test(body);
89 const needP = uses('P').test(body) && !assigns('P').test(body);
90 if (assigns('GSTACK_ROOT').test(body)) return '';
91 const needRoot = needB || needD || needP || ROOT_VARS.test(body);
92 const derived = Object.entries(DERIVED)
93 .filter(([name]) => uses(`GSTACK_${name}`).test(body) && !assigns(`GSTACK_${name}`).test(body))
94 .map(([name, dir]) => `GSTACK_${name}=$GSTACK_ROOT/${dir}`);
95 return [
96 needRoot ? resolveRoot(ctx) : '',
97 derived.join(' '),
98 needB ? binaryAssignment(ctx, 'browse') : '',
99 needD ? binaryAssignment(ctx, 'design') : '',
100 needP ? binaryAssignment(ctx, 'make-pdf') : '',
101 ].filter(Boolean).join('\n');
104/**
105 * Post-render pass: insert the prelude at the top of every top-level ```bash
106 * fence that needs it. Fences nested inside a longer fence are examples, not
107 * commands, and are left alone; an indented fence gets indented prelude lines.
108 */
109export function insertRuntimePreludes(content: string, ctx: TemplateContext): string {
110 if (!getHostConfig(ctx.host).usesEnvVars) return content;
111 const lines = content.split('\n');
112 const out: string[] = [];
113 for (let i = 0; i < lines.length; i++) {
114 const open = lines[i].match(/^(\s*)(`{3,})(.*)$/);
115 out.push(lines[i]);
116 if (!open) continue;
117 let end = i + 1;
118 while (end < lines.length && !new RegExp(`^\\s*\`{${open[2].length},}\\s*$`).test(lines[end])) end++;
119 const body = lines.slice(i + 1, end);
120 if (open[2].length === 3 && open[3].trim() === 'bash') {
121 const prelude = fencePrelude(ctx, body.join('\n'));
122 if (prelude) out.push(...prelude.split('\n').map(line => open[1] + line));
123 }
124 out.push(...body);
125 if (end < lines.length) out.push(lines[end]);
126 i = end;
127 }
128 return out.join('\n');