Skill Tracer
Skills › gstack › gstack › sections.ts

sections.ts

181 lines · scripts/resolvers/sections.ts at 3f79d81

1/**
2 * Section resolvers (v2 plan T9, Claude-first carve).
3 *
4 * A carved skill keeps its prose-heavy steps in `<skill>/sections/<id>.md`, read
5 * on demand. The SAME template ships to every host, so these resolvers make the
6 * carve host-aware:
7 *
8 * - On CLAUDE and for QA on every host: {{SECTION:id}} emits a STOP-Read pointer to the generated section
9 * file (the skeleton), and the section .md is generated + installed separately.
10 * - Other skills on external hosts: {{SECTION:id}} INLINES the section template's content,
11 * so external hosts keep the full monolith ship skill (no section files, no
12 * host-portable-path problem). Inlined content keeps its own {{RESOLVER}}
13 * tokens, which the generator's multi-pass resolve expands.
14 *
15 * {{SECTION_INDEX:skill}} renders the situation→section table from the PASSIVE
16 * manifest for lazy skills (empty for inlined skills). The manifest
17 * is the single source of id/file/title/trigger text (CM2; v2_PLAN.md:663).
18 */
20import * as fs from 'fs';
21import * as path from 'path';
22import type { Host, ResolverFn, TemplateContext } from './types';
24const ROOT = path.resolve(import.meta.dir, '..', '..');
26export const QA_ASSET_BLOCKER = 'If missing or unreadable, report a QA setup blocker and its affected probes as blocked; continue other safe probes (independent functional/static checks). Missing/unreadable assets block required QA.';
28/** Skills carved on every host: QA (portable assets), those whose external
29 * render would exceed SKILL_BYTE_CEILING inlined (C4, #2777), and design-review,
30 * whose on-demand craft audit stays out of every skeleton (GSTA-92). */
31const CARVED_ON_EVERY_HOST = ['qa', 'qa-only', 'ship', 'plan-ceo-review', 'office-hours', 'design-review'];
33/** Hosts read at most this many UTF-8 bytes of one SKILL.md (~40K tokens). */
34export const SKILL_BYTE_CEILING = 160_000;
36export function usesLazySections(host: Host, skill: string): boolean {
37 return host === 'claude' || CARVED_ON_EVERY_HOST.includes(skill);
40/**
41 * External hosts: a template's literal `~/.claude/skills/gstack/<skill>/sections/<file>`
42 * reference arrives here as `$GSTACK_ROOT/...` or `~/<globalRoot>/...`, and external
43 * runtime roots have no section trees. For a carved skill, point it at the installed copy;
44 * for this skill's own section inlined by {{SECTION}}, point at the inlined text.
45 */
46export function rewriteCarvedSectionRefs(content: string, ctx: TemplateContext): string {
47 if (ctx.host === 'claude') return content;
48 // The root arrives as $GSTACK_ROOT or as the host's literal ~/<globalRoot> (path rewrites).
49 return content.replace(/`(?:\$GSTACK_ROOT|~\/[\w./-]*?skills\/gstack)\/([a-z0-9-]+)\/sections\/([A-Za-z0-9._-]+)`/g, (match, skill: string, file: string) => {
50 if (!fs.existsSync(path.join(ROOT, skill, 'sections', `${file}.tmpl`))) return match;
51 if (usesLazySections(ctx.host, skill)) return `\`sections/${file}\` relative to the installed \`gstack-${skill}\` SKILL.md directory`;
52 const entry = loadManifest(skill).sections.find(e => e.file === file);
53 const inlined = skill === ctx.skillName && entry && fs.readFileSync(path.join(ROOT, skill, 'SKILL.md.tmpl'), 'utf-8').includes(`{{SECTION:${entry.id}}}`);
54 return inlined ? `the \`${file.replace(/\.md$/, '')}\` section inlined in this SKILL.md` : match;
55 });
58interface SectionEntry {
59 id: string;
60 file: string;
61 title: string;
62 trigger: string;
63 /** Plan B4: read by bin/gstack-autoplan alone; interactive renders ignore it. Default `always`. */
64 scope?: 'always' | 'ui' | 'dx' | 'db' | 'perf' | 'security' | 'incident';
65 /** Plan B4: a runner-profile section (the checklist) stays out of the Section index. */
66 runner_only?: boolean;
68interface SectionManifest {
69 skill: string;
70 sections: SectionEntry[];
73function loadManifest(skill: string): SectionManifest {
74 const p = path.join(ROOT, skill, 'sections', 'manifest.json');
75 const raw = fs.readFileSync(p, 'utf-8');
76 return JSON.parse(raw) as SectionManifest;
79function findSection(skill: string, id: string): SectionEntry {
80 const entry = loadManifest(skill).sections.find(s => s.id === id);
81 if (!entry) {
82 throw new Error(`{{SECTION:${id}}} — no section "${id}" in ${skill}/sections/manifest.json`);
83 }
84 return entry;
87/**
88 * Pointer to a carved section file. Claude keeps its global-root path; QA and
89 * every external host point relative to the installed skill directory, because
90 * external runtime roots (`$GSTACK_ROOT`) carry no `<skill>/sections/` tree
91 * while setup links or copies whole skill directories.
92 */
93export function sectionPath(ctx: TemplateContext, skill: string, id: string): string {
94 const entry = findSection(skill, id);
95 if (ctx.host !== 'claude' || skill === 'qa' || skill === 'qa-only') {
96 fs.accessSync(path.join(ROOT, skill, 'sections', `${entry.file}.tmpl`), fs.constants.R_OK);
97 const installedName = ctx.host === 'claude' ? `\`${skill}\`/\`gstack-${skill}\`` : `\`${skill.startsWith('gstack-') ? skill : `gstack-${skill}`}\``;
98 return `\`sections/${entry.file}\` relative to the installed ${installedName} SKILL.md directory`;
99 }
100 return `\`${ctx.paths.skillRoot}/${skill}/sections/${entry.file}\``;
103/**
104 * {{SECTION:id}} — installed-file pointer for QA; otherwise Claude pointers
105 * and external inline content retain their existing behavior.
106 */
107export const SECTION: ResolverFn = (ctx: TemplateContext, args?: string[]): string => {
108 const id = args?.[0];
109 if (!id) throw new Error('{{SECTION:id}} requires a section id');
110 const entry = findSection(ctx.skillName, id);
111 if (ctx.modules?.excluded.has(`section:${ctx.skillName}/${id}`)) {
112 return `> Not loaded in the ${ctx.modules!.name} loadout: skip ${entry.trigger}. Do not offer it, and treat it as not run.`;
113 }
115 if (usesLazySections(ctx.host, ctx.skillName)) {
116 if (ctx.skillName === 'qa' || ctx.skillName === 'qa-only') {
117 return [
118 `> **STOP.** Before ${entry.trigger}, Read ${sectionPath(ctx, ctx.skillName, id)} in full and follow it.`,
119 '> Use this host\'s installed path, never the product working directory or another host\'s assets.',
120 `> ${QA_ASSET_BLOCKER}`,
121 ].join('\n');
122 }
123 return [
124 `> **STOP.** Before ${entry.trigger}, Read ${sectionPath(ctx, ctx.skillName, id)} and execute it`,
125 `> in full. Do not work from memory — that section is the source of truth for this step.`,
126 ].join('\n');
127 }
129 // Non-Claude hosts inline the section template content (monolith preserved).
130 // Inner {{RESOLVER}} tokens are expanded by the generator's multi-pass resolve.
131 const tmplPath = path.join(ROOT, ctx.skillName, 'sections', `${entry.file}.tmpl`);
132 return fs.readFileSync(tmplPath, 'utf-8').trimEnd();
133};
135const SECTION_GUARD_RE = /\{\{IF_SECTION:([a-z0-9-]+)\}\}([\s\S]*?)\{\{\/IF_SECTION\}\}/g;
137/**
138 * {{IF_SECTION:id}}…{{/IF_SECTION}}: skeleton text that belongs to one of this
139 * skill's sections (an offer, a self-check naming it). The markers vanish and
140 * the text stays when the section loads, so `full` bytes are unchanged; a
141 * loadout that excludes the section drops the text with it.
142 */
143export function applySectionGuards(content: string, ctx: TemplateContext): string {
144 return content.replace(SECTION_GUARD_RE, (_match, id: string, inner: string) => {
145 findSection(ctx.skillName, id);
146 return ctx.modules?.excluded.has(`section:${ctx.skillName}/${id}`) ? '' : inner;
147 });
150/**
151 * {{SECTION_INDEX:skill}} — situation→section table from the passive manifest.
152 * Lazy skills only; an index would be noise for inlined skills.
153 */
154export const SECTION_INDEX: ResolverFn = (ctx: TemplateContext, args?: string[]): string => {
155 const skill = args?.[0] ?? ctx.skillName;
156 if (!usesLazySections(ctx.host, skill)) return '';
157 const manifest = loadManifest(skill);
158 const lines: string[] = [
159 '## Section index — Read each section when its situation applies',
160 '',
161 ...(skill === 'qa' || skill === 'qa-only'
162 ? ['Read sections in full when directed; do not work from memory.']
163 : ['This skill is a decision-tree skeleton. The steps below point to on-demand',
164 'sections. Read a section in full before doing its step; do not work from memory.']),
165 '',
166 '| When | Read this section |',
167 '|------|-------------------|',
168 ];
169 for (const s of manifest.sections) {
170 if (s.runner_only || ctx.modules?.excluded.has(`section:${skill}/${s.id}`)) continue;
171 const reference = skill === 'qa' || skill === 'qa-only' ? sectionPath(ctx, skill, s.id) : `\`sections/${s.file}\``;
172 if (skill === 'review' && s.id === 'review-army') {
173 lines.push(`| Select surfaces and read QA methods | Inline in [Step 4](#step-4-critical-pass-core-review); setup and probes run in Step 4.7 |`);
174 }
175 lines.push(`| ${s.trigger} | ${reference} |`);
176 if (skill === 'ship' && s.id === 'review-army') {
177 lines.push(`| exploratory QA before Fix-First (Step 9.2.1) | Use the QA Read directive in ${reference} |`);
178 }
179 }
180 return lines.join('\n');
181};