v1.91.317.0 feat(harness): trigger-first skill descriptions, hybrid OpenClaw layout, opt-in --context block (GSTA-135) (#3555)

* test(harness): pin the GSTACK_SESSION_KIND=spawned marker and its readers (GSTA-135)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* feat(harness): trigger-first skill descriptions, hybrid OpenClaw layout, opt-in --context block (GSTA-135)

Router lines and Hermes leads open with the skill's triggers; OpenClaw
defaults to hybrid (five task skills plus the router); --context writes the
routing block only into a named file, refusing SOUL.md and any new Hermes
rules file that would outrank one Hermes loads now.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* docs(harness): skill-use layout, --context and HARNESS_CONTEXT_REFUSED (GSTA-135)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

---------

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
This commit is contained in:
Garry Tanandcapy-ai[bot] authored and GitHub committed 2026-10-29 13:28:08 +00:00
1 parent c85dd0a799
commit 9f44f188d1
20 files changed
+772 -106

No files matched your search

+142 -68
View File
@@ -21,8 +21,9 @@ import * as path from 'node:path';
import { spawnSync } from 'node:child_process';
import { bunIsolationArgs } from './bun-isolation';
import { runBashSync } from './script-invocation';
import { frontmatterList, routerLine } from './skill-triggers';
export type SkillsMode = 'router' | 'all';
export type SkillsMode = 'router' | 'hybrid' | 'all';
export type TargetName = 'openclaw' | 'hermes' | 'dots' | 'generic' | 'qm' | 'muse' | 'grok';
type Env = Record<string, string | undefined>;
@@ -33,7 +34,9 @@ export const BLOCK_BEGIN = '<!-- gstack:begin harness-routing -->';
export const BLOCK_END = '<!-- gstack:end harness-routing -->';
/** Where a Dot keeps its own skills (feder-cr/dots nanobot/dots/skills.py DOT_SKILLS_DIR). */
export const DOT_SKILLS_DIR = '/home/dot/skills';
export const ROUTER_DESCRIPTION = 'gstack engineering workflows: code review, QA testing, debugging, security audit, plan and design review, shipping PRs, release docs, retros. Load first for any coding, review, test, plan or release task; it lists every gstack skill and where to read it.';
export const ROUTER_DESCRIPTION = 'Use to review a diff or PR, debug a bug or failing test, QA test a site, plan or review architecture, ship a PR, audit security or write release docs. Load first for any coding task: lists every gstack skill and where to read it.';
/** OpenClaw hybrid mode: these task skills are listed as skills of their own; the router carries the rest. */
export const HYBRID_SKILLS = ['review', 'investigate', 'qa', 'ship', 'plan-eng-review'];
export interface Target {
name: TargetName;
@@ -62,7 +65,7 @@ const ancestorIs = (ancestry: string[], name: string) => ancestry.some(id => {
export const TARGETS: Record<TargetName, Target> = {
openclaw: {
name: 'openclaw', displayName: 'OpenClaw', mechanism: 'skill-folder', render: 'host', defaultMode: 'router', modes: ['router', 'all'],
name: 'openclaw', displayName: 'OpenClaw', mechanism: 'skill-folder', render: 'host', defaultMode: 'hybrid', modes: ['router', 'hybrid', 'all'],
dest: (env, home) => path.join(env.OPENCLAW_STATE_DIR || path.join(home, '.openclaw'), 'skills'),
inside: (env, anc) => env.OPENCLAW_SHELL === 'exec' || ancestorIs(anc, 'openclaw'),
present: (env, home) => onPath('openclaw', env) || fs.existsSync(env.OPENCLAW_STATE_DIR || path.join(home, '.openclaw')),
@@ -109,7 +112,8 @@ export const TARGETS: Record<TargetName, Target> = {
export const HARNESS_CODES = {
HARNESS_UNKNOWN_TARGET: { anchor: 'harness-unknown-target', fix: 'name one of: openclaw, hermes, dots, generic, qm, muse, grok' },
HARNESS_NO_DESTINATION: { anchor: 'harness-no-destination', fix: 'pass --skills-dir <dir> or --context <file>, or --print to see the block without writing' },
HARNESS_MODE_UNSUPPORTED: { anchor: 'harness-mode-unsupported', fix: 'drop --skills, or pass a mode the target supports (Hermes opens only listed skills, so it takes all)' },
HARNESS_MODE_UNSUPPORTED: { anchor: 'harness-mode-unsupported', fix: 'drop --skills, or pass a mode the target supports (Hermes takes all: its skills index lists only skills registered as folders, so a router would leave the rest out of the listing)' },
HARNESS_CONTEXT_REFUSED: { anchor: 'harness-context-refused', fix: 'name a rules file the harness already loads (for Hermes, the existing .hermes.md, HERMES.md or AGENTS.md), never SOUL.md' },
HARNESS_UNSAFE_DESTINATION: { anchor: 'harness-unsafe-destination', fix: 'pick a destination that is a plain folder outside the gstack checkout, not your home folder, with no tab or newline in its path' },
HARNESS_UNOWNED_ENTRY: { anchor: 'harness-unowned-entry', fix: 'move or rename the existing entry (gstack did not write it), then register again' },
HARNESS_RENDER_FAILED: { anchor: 'harness-render-failed', fix: 'run bun install in the gstack checkout, then register again; the render output above names the failing skill' },
@@ -184,13 +188,6 @@ function frontmatterField(md: string, field: string): string {
return body.join(' ');
}
/** First sentence of a description, without the trailing "(gstack)" tag, at most 160 characters. */
export function oneLineUse(description: string): string {
const d = description.replace(/\s*\(gstack\)\s*$/, '').replace(/\s+/g, ' ').trim();
const s = (d.match(/^.*?[.!?](\s|$)/)?.[0] ?? d).trim();
return s.length > 160 ? s.slice(0, 157).trimEnd() + '...' : s;
}
/** Agent Skills frontmatter in its strictest reading (dots): single-line name equal to the folder, single-line description of at most 1024 characters. */
export function flatFrontmatter(md: string, name: string): string {
const end = md.startsWith('---\n') ? md.indexOf('\n---', 4) : -1;
@@ -199,14 +196,18 @@ export function flatFrontmatter(md: string, name: string): string {
return '---\nname: ' + name + '\ndescription: ' + (desc.length > 1024 ? desc.slice(0, 1021).trimEnd() + '...' : desc) + '\n---\n' + body;
}
function skillDirs(root: string): SkillEntry[] {
/** Generated skills under root; a render whose frontmatter dropped `triggers:` takes them from triggersByName (the checkout's skills, by name). */
function skillDirs(root: string, triggersByName = new Map<string, string[]>()): Array<SkillEntry & { triggers: string[] }> {
if (!fs.existsSync(root)) return [];
return fs.readdirSync(root).sort().flatMap(name => {
const md = path.join(root, name, 'SKILL.md');
return fs.readdirSync(root).sort().flatMap(dir => {
const md = path.join(root, dir, 'SKILL.md');
if (!fs.existsSync(md)) return [];
const text = fs.readFileSync(md, 'utf8');
if (!text.includes('AUTO-GENERATED')) return [];
return [{ name: frontmatterField(text, 'name') || name, use: oneLineUse(frontmatterField(text, 'description')), dir: path.join(root, name) }];
const name = frontmatterField(text, 'name') || dir;
const own = frontmatterList(text, 'triggers');
const triggers = own.length ? own : triggersByName.get(name) ?? triggersByName.get(name.replace(/^gstack-/, '')) ?? [];
return [{ name, use: routerLine(frontmatterField(text, 'description'), triggers), dir: path.join(root, dir), triggers }];
});
}
@@ -218,33 +219,43 @@ export function sourceSkills(target: Target, checkout: string, scratch: string):
const r = spawnSync(process.execPath, [...bunIsolationArgs(), 'scripts/gen-skill-docs.ts', '--host', target.name, '--install-root', checkout, '--out-dir', out],
{ cwd: checkout, encoding: 'utf8', timeout: 300_000 });
if (r.status !== 0) throw new HarnessError('HARNESS_RENDER_FAILED', 'could not render ' + target.name + ' skills: ' + ((r.stderr || r.stdout || '').trim().split('\n').slice(-3).join(' | ')));
const skills = skillDirs(path.join(out, '.' + target.name, 'skills'));
const skills = skillDirs(path.join(out, '.' + target.name, 'skills'), new Map(skillDirs(checkout).map(s => [s.name, s.triggers])));
if (!skills.length) throw new HarnessError('HARNESS_RENDER_FAILED', 'the ' + target.name + ' render produced no skills');
return skills;
}
export function routerSkill(skills: Array<{ name: string; use: string; path: string }>, target: Target): string {
/** The router skill; direct names the skills hybrid mode lists as skills of their own. */
export function routerSkill(skills: Array<{ name: string; use: string; path: string }>, target: Target, direct: string[] = []): string {
const claudeNote = target.render === 'claude'
? '\nThese files use Claude Code tool names (Bash, Read, Edit, Agent, AskUserQuestion); use your own equivalents.\n' : '';
const directNote = direct.length ? ' ' + direct.join(', ') + ' are skills of their own in your list; this router carries the rest.' : '';
return [
'---', 'name: gstack', 'description: ' + ROUTER_DESCRIPTION, '---',
'<!-- AUTO-GENERATED by gstack-harness register: rerun it instead of editing -->',
'# gstack skills', '',
'Pick the one skill whose line matches the task, then read that SKILL.md in full and follow it. Read nothing else up front.' + claudeNote,
'Pick the one skill whose line matches the task, then read that SKILL.md in full and follow it. Read nothing else up front.' + directNote + claudeNote,
...skills.map(s => '- **' + s.name + '**: ' + s.use + ' Read `' + s.path + '`'),
'',
].join('\n');
}
export function contextBlock(routerPath: string): string {
return [BLOCK_BEGIN, '## gstack skills',
"gstack's engineering workflows (code review, QA, debugging, security audit, plan review, shipping) are installed here. For a coding, review, test, plan or release task, read `" + routerPath + '`, pick the one skill whose line matches, then read and follow that skill. Load nothing else up front.',
BLOCK_END].join('\n');
/** The marked context block for the registration's mode: router (a router path), hybrid (a router path and direct skills) or all (no router). */
export function contextBlock(routerPath: string | null, direct: string[] = []): string {
const lead = "gstack's engineering workflows (code review, QA, debugging, security audit, plan review, shipping) are installed here. ";
const pick = ', pick the one skill whose line matches, then read and follow that skill. Load nothing else up front.';
const body = !routerPath
? 'For a coding, review, test, plan or release task, load the matching gstack skill from your skills list and follow it. Load nothing else up front.'
: direct.length
? 'For a task that ' + direct.join(', ') + ' fits, load that skill from your skills list; for any other coding, review, test, plan or release task, read `' + routerPath + '`' + pick
: 'For a coding, review, test, plan or release task, read `' + routerPath + '`' + pick;
return [BLOCK_BEGIN, '## gstack skills', lead + body, BLOCK_END].join('\n');
}
// --- ledger ----------------------------------------------------------------
export interface Ledger { meta: Record<string, string>; files: Array<{ sha: string; path: string }>; dirs: string[]; blocks: Array<{ sha: string; path: string }> }
/** pad: what gstack added before a block it appended, so uninstall restores the file byte for byte: new (it created the file), 0 (the file was empty), 1 (one blank line), 2 (a newline and a blank line); '' in ledgers that predate it. */
export interface LedgerBlock { sha: string; path: string; pad: string }
export interface Ledger { meta: Record<string, string>; files: Array<{ sha: string; path: string }>; dirs: string[]; blocks: LedgerBlock[] }
export const sha256 = (b: Buffer | string) => createHash('sha256').update(b).digest('hex');
export const ledgerDir = (stateRoot: string) => path.join(stateRoot, 'harness');
@@ -254,13 +265,15 @@ export const ledgerPath = (stateRoot: string, id: string) => path.join(ledgerDir
export function readLedger(file: string): Ledger | null {
if (!fs.existsSync(file)) return null;
const l: Ledger = { meta: {}, files: [], dirs: [], blocks: [] };
const pads = new Map<string, string>();
for (const line of fs.readFileSync(file, 'utf8').split('\n')) {
const [kind, a, ...rest] = line.split('\t');
const b = rest.join('\t');
if (kind === 'meta') l.meta[a] = b;
else if (kind === 'file') l.files.push({ sha: a, path: b });
else if (kind === 'dir') l.dirs.push(b);
else if (kind === 'block') l.blocks.push({ sha: a, path: b });
else if (kind === 'blockpad') pads.set(b, a);
else if (kind === 'block') l.blocks.push({ sha: a, path: b, pad: pads.get(b) ?? '' });
}
return l;
}
@@ -270,7 +283,7 @@ export function writeLedger(file: string, l: Ledger): void {
...Object.entries(l.meta).map(([k, v]) => 'meta\t' + k + '\t' + v),
...l.files.map(f => 'file\t' + f.sha + '\t' + f.path),
...l.dirs.map(d => 'dir\t-\t' + d),
...l.blocks.map(b => 'block\t' + b.sha + '\t' + b.path)];
...l.blocks.flatMap(b => [...(b.pad ? ['blockpad\t' + b.pad + '\t' + b.path] : []), 'block\t' + b.sha + '\t' + b.path])];
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
fs.writeFileSync(file + '.tmp', rows.join('\n') + '\n', { mode: 0o600 });
fs.renameSync(file + '.tmp', file);
@@ -290,8 +303,10 @@ export interface RegisterOptions {
mode?: SkillsMode;
/** Destination override: the harness skills folder (--skills-dir). */
skillsDir?: string;
/** Context file for the routing block (generic). */
/** Context file for the routing block: written only into the file named here (--context). */
context?: string;
/** Refresh: context only identifies a generic registration; blocks already recorded are kept while they are still in their files, never re-added. */
inherit?: boolean;
checkout: string;
stateRoot: string;
env: Env;
@@ -336,8 +351,8 @@ function resolveDest(opts: RegisterOptions, id?: string): string | null {
return opts.context && id ? path.join(ledgerDir(opts.stateRoot), id) : null;
}
/** Desired files (absolute path -> bytes) and the router path, for a skill-folder or generic target. */
export function planPayload(opts: RegisterOptions, dest: string, mode: SkillsMode, scratch: string): { files: Map<string, Buffer>; router: string | null; names: string[] } {
/** Desired files (absolute path -> bytes), the router path, the skill names the harness lists, the skills listed directly beside a router, and the skill count. */
export function planPayload(opts: RegisterOptions, dest: string, mode: SkillsMode, scratch: string): { files: Map<string, Buffer>; router: string | null; visible: string[]; direct: string[]; skills: number } {
const t = opts.target;
const skills = sourceSkills(t, opts.checkout, scratch);
const files = new Map<string, Buffer>();
@@ -346,23 +361,27 @@ export function planPayload(opts: RegisterOptions, dest: string, mode: SkillsMod
files.set(path.join(to, 'SKILL.md'), Buffer.from(flatFrontmatter(fs.readFileSync(path.join(s.dir, 'SKILL.md'), 'utf8'), path.basename(to))));
if (fs.existsSync(path.join(s.dir, 'sections'))) copyDir(path.join(s.dir, 'sections'), path.join(to, 'sections'));
};
const listed = (s: SkillEntry) => {
const to = path.join(dest, path.basename(s.dir));
if (t.render === 'host') copyDir(s.dir, to); else claudeFiles(s, to);
return t.render === 'host' ? s.name : path.basename(s.dir);
};
if (mode === 'all') {
for (const s of skills) {
const to = path.join(dest, path.basename(s.dir));
if (t.render === 'host') copyDir(s.dir, to); else claudeFiles(s, to);
}
return { files, router: null, names: skills.map(s => t.render === 'host' ? s.name : path.basename(s.dir)) };
const names = skills.map(listed);
return { files, router: null, visible: names, direct: [], skills: names.length };
}
const isDirect = (s: SkillEntry) => mode === 'hybrid' && HYBRID_SKILLS.includes(path.basename(s.dir).replace(/^gstack-/, ''));
const direct = skills.filter(isDirect).map(listed);
const routerDir = path.join(dest, 'gstack');
const entries = skills.map(s => {
const entries = skills.filter(s => !isDirect(s)).map(s => {
if (t.render !== 'host') return { name: s.name, use: s.use, path: path.join(s.dir, 'SKILL.md') };
const to = path.join(routerDir, 'skills', path.basename(s.dir));
copyDir(s.dir, to);
return { name: s.name, use: s.use, path: path.join(to, 'SKILL.md') };
});
const router = path.join(routerDir, 'SKILL.md');
files.set(router, Buffer.from(routerSkill(entries, t)));
return { files, router, names: ['gstack', ...entries.map(e => e.name)] };
files.set(router, Buffer.from(routerSkill(entries, t, direct)));
return { files, router, visible: ['gstack', ...direct], direct, skills: skills.length };
}
/** An edited file stays beside itself under a name no harness loads, so no uninstall step that removes gstack's folders can take it. */
@@ -389,25 +408,67 @@ function onDiskSha(file: string): string | null {
/** The ledger's hash of a context block: its lines, each ending in a newline, as the bash reader's awk prints them. */
export const blockSha = (block: string) => sha256(block + '\n');
/** The gstack block in a file: absent (no marker lines, or no file), owned (one marker pair hashing to sha) or other. */
export function blockState(file: string, sha: string): 'absent' | 'owned' | 'other' {
if (!fs.existsSync(file)) return 'absent';
const lines = fs.readFileSync(file, 'utf8').split('\n');
const at = (m: string) => lines.flatMap((l, i) => l === m ? [i] : []);
const [bs, es] = [at(BLOCK_BEGIN), at(BLOCK_END)];
if (!bs.length && !es.length) return 'absent';
return bs.length === 1 && es.length === 1 && es[0] > bs[0] && sha256(lines.slice(bs[0], es[0] + 1).join('\n') + '\n') === sha ? 'owned' : 'other';
}
/**
* The text of file with the block in it: replaces the one gstack block there (whole-line markers) when it is the block
* gstack wrote (ownedSha) or already current, else appends. A lone or repeated marker, or a block someone
* edited, is refused so nothing outside gstack's own lines is ever rewritten.
* The text of file with the block in it, and the pad gstack added before an appended block: replaces the one gstack
* block there (whole-line markers) when it is the block gstack wrote (ownedSha) or already current (pad ''), else
* appends. A lone or repeated marker, or a block someone edited, is refused so nothing outside gstack's own lines is
* ever rewritten.
*/
export function withBlock(file: string, block: string, ownedSha?: string): string {
const text = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
export function withBlock(file: string, block: string, ownedSha?: string): { text: string; pad: string } {
const exists = fs.existsSync(file);
const text = exists ? fs.readFileSync(file, 'utf8') : '';
const lines = text.split('\n');
const at = (m: string) => lines.flatMap((l, i) => l === m ? [i] : []);
const [bs, es] = [at(BLOCK_BEGIN), at(BLOCK_END)];
let next: string;
if (!bs.length && !es.length) next = text + (text && !text.endsWith('\n') ? '\n' : '') + (text ? '\n' : '') + block + '\n';
else if (bs.length === 1 && es.length === 1 && es[0] > bs[0]) {
if (!bs.length && !es.length) {
const pad = !exists ? 'new' : !text ? '0' : text.endsWith('\n') ? '1' : '2';
return { text: text + (pad === '2' ? '\n\n' : pad === '1' ? '\n' : '') + block + '\n', pad };
}
if (bs.length === 1 && es.length === 1 && es[0] > bs[0]) {
const cur = sha256(lines.slice(bs[0], es[0] + 1).join('\n') + '\n');
if (cur !== blockSha(block) && cur !== ownedSha) throw new HarnessError('HARNESS_UNOWNED_ENTRY', 'the gstack block in ' + file + ' was edited or gstack did not write it; delete the lines from ' + BLOCK_BEGIN + ' to ' + BLOCK_END);
lines.splice(bs[0], es[0] - bs[0] + 1, ...block.split('\n'));
next = lines.join('\n');
} else throw new HarnessError('HARNESS_UNOWNED_ENTRY', file + ' has a gstack harness-routing marker line without exactly one partner; fix or delete the marker lines');
return next;
return { text: lines.join('\n'), pad: '' };
}
throw new HarnessError('HARNESS_UNOWNED_ENTRY', file + ' has a gstack harness-routing marker line without exactly one partner; fix or delete the marker lines');
}
/** Whether a context file belongs to the harness's own home (profile: every session) or to a project (sessions started there). */
export function contextScope(t: Target, file: string, env: Env, home: string): 'profile' | 'project' {
const harnessHome = t.name === 'hermes' ? env.HERMES_HOME || path.join(home, '.hermes') : t.name === 'openclaw' ? env.OPENCLAW_STATE_DIR || path.join(home, '.openclaw') : null;
return harnessHome && path.resolve(file).startsWith(path.resolve(harnessHome) + path.sep) ? 'profile' : 'project';
}
/** Hermes loads one project context type, first match wins, walking to the git root (agent/prompt_builder.py build_context_files_prompt); within a group the first name in a folder wins, and the nearest .hermes.md/HERMES.md wins. */
const HERMES_CONTEXT_ORDER = [['.hermes.md', 'HERMES.md'], ['AGENTS.override.md', 'AGENTS.md', 'agents.md'], ['CLAUDE.md'], ['.cursorrules']];
/** Refuses SOUL.md (the harness's identity file), and for Hermes a new file that would shadow the rules it loads now. */
function assertContextFile(t: Target, file: string): void {
const refuse = (why: string) => { throw new HarnessError('HARNESS_CONTEXT_REFUSED', 'refusing to write the gstack block into ' + file + ': ' + why); };
if (path.basename(file).toLowerCase() === 'soul.md') refuse('SOUL.md is the harness\'s identity file');
if (t.name !== 'hermes' || fs.existsSync(file)) return;
const rank = HERMES_CONTEXT_ORDER.findIndex(g => g.includes(path.basename(file)));
if (rank < 0) return;
const group = HERMES_CONTEXT_ORDER[rank];
const later = HERMES_CONTEXT_ORDER.slice(rank + 1).flat();
const dirs = [path.dirname(file)];
for (let d = dirs[0]; !fs.existsSync(path.join(d, '.git')) && path.dirname(d) !== d; d = path.dirname(d)) dirs.push(path.dirname(d));
const chain = fs.existsSync(path.join(dirs.at(-1)!, '.git')) ? dirs : dirs.slice(0, 1);
for (const dir of chain) {
const own = dir === dirs[0] ? group.slice(group.indexOf(path.basename(file)) + 1) : rank === 0 ? group : [];
const shadowed = [...own, ...later].find(n => fs.existsSync(path.join(dir, n)));
if (shadowed) refuse('Hermes loads ' + path.basename(file) + ' instead of ' + path.join(dir, shadowed) + ', so creating it would hide those rules; name that file instead');
}
}
/** Runs fn from one of the checkout's sourced bash libraries, passing args through the environment. */
@@ -417,11 +478,6 @@ function sourcedBash(checkout: string, lib: string, fn: string, args: string[],
{ env: { ...process.env, ...env, ...argEnv, GSTACK_HARNESS_LIB: path.join(checkout, 'bin', lib), GSTACK_STATE_ROOT: stateRoot }, encoding: 'utf8', timeout: 60_000 });
}
/** Cuts a block this ledger recorded through the bash reader, so register and uninstall share one cutter. */
function cutBlock(opts: RegisterOptions, file: string, sha: string): void {
process.stdout.write(sourcedBash(opts.checkout, 'gstack-harness-ledger.sh', '_gstack_harness_cut_block', [file, sha], opts.stateRoot, opts.env).stdout || '');
}
function shellRegistry(opts: RegisterOptions, fn: string, args: string[]): boolean {
return sourcedBash(opts.checkout, 'gstack-install-registry.sh', fn, args, opts.stateRoot, opts.env).status === 0;
}
@@ -437,14 +493,13 @@ export function register(opts: RegisterOptions): RegisterResult {
const id = registrationId(t.name, provisional);
const dest = resolveDest(opts, id)!;
assertSafeDest(dest, opts);
if (opts.context) assertSafeDest(path.resolve(opts.context), opts);
const explicit = opts.context && !opts.inherit ? path.resolve(opts.context) : '';
if (explicit) { assertSafeDest(explicit, opts); assertContextFile(t, explicit); }
const lfile = ledgerPath(opts.stateRoot, id);
const prev = readLedger(lfile);
const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-harness-'));
try {
const { files, router, names } = planPayload(opts, dest, mode, scratch);
const skills = mode === 'router' ? names.length - 1 : names.length;
const visible = mode === 'router' ? ['gstack'] : names;
const { files, router, visible, direct, skills } = planPayload(opts, dest, mode, scratch);
const prevFiles = new Map((prev?.files ?? []).map(f => [f.path, f.sha]));
const topOf = (p: string) => path.join(dest, path.relative(dest, p).split(path.sep)[0]);
const owned = new Set([...prevFiles.keys()].map(topOf));
@@ -463,13 +518,28 @@ export function register(opts: RegisterOptions): RegisterResult {
}
for (const p of new Set([...files.keys(), ...prevFiles.keys()])) assertOwnedPath(dest, p);
const want = [...files].map(([p, b]) => ({ path: p, sha: sha256(b) }));
const ctx = opts.context ? path.resolve(opts.context) : '';
const block = opts.context ? contextBlock(router ?? '') : null;
if (block && block.length > CONTEXT_BLOCK_MAX) throw new HarnessError('HARNESS_BUDGET_EXCEEDED', 'context block is ' + block.length + ' bytes');
const blocks = block ? [{ sha: blockSha(block), path: ctx }] : [];
const ctxText = block ? withBlock(ctx, block, prev?.blocks.find(b => b.path === ctx)?.sha) : null;
const context = opts.context ? path.resolve(opts.context) : prev?.meta.context ?? '';
const block = contextBlock(router, direct);
if ((explicit || prev?.blocks.length) && block.length > CONTEXT_BLOCK_MAX) throw new HarnessError('HARNESS_BUDGET_EXCEEDED', 'context block is ' + block.length + ' bytes');
const blocks: LedgerBlock[] = [];
const blockWrites = new Map<string, string>();
for (const b of prev?.blocks ?? []) {
if (b.path === explicit) continue;
const state = blockState(b.path, b.sha);
if (state === 'absent') continue;
if (state === 'other') { blocks.push(b); continue; }
blockWrites.set(b.path, withBlock(b.path, block, b.sha).text);
blocks.push({ sha: blockSha(block), path: b.path, pad: b.pad });
}
if (explicit) {
const before = prev?.blocks.find(b => b.path === explicit);
const w = withBlock(explicit, block, before?.sha);
blockWrites.set(explicit, w.text);
blocks.push({ sha: blockSha(block), path: explicit, pad: w.pad || before?.pad || '' });
}
const same = prev && prev.meta.mode === mode && prev.meta.names === visible.join(',') && prev.files.length === want.length
&& (prev.meta.context ?? '') === ctx && prev.blocks.every(b => blocks.some(n => n.path === b.path && n.sha === b.sha))
&& (prev.meta.context ?? '') === context && prev.blocks.length === blocks.length
&& blocks.every(b => prev.blocks.some(p => p.path === b.path && p.sha === b.sha && p.pad === b.pad))
&& want.every(w => prevFiles.get(w.path) === w.sha && onDiskSha(w.path) === w.sha);
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
const kept: string[] = [];
@@ -478,16 +548,19 @@ export function register(opts: RegisterOptions): RegisterResult {
const dirs = new Set(prev?.dirs ?? []);
for (const p of files.keys()) for (let d = path.dirname(p); !fs.existsSync(d) && path.dirname(d) !== d; d = path.dirname(d)) dirs.add(d);
const record = (recorded: typeof want) => writeLedger(lfile, {
meta: { id, target: t.name, dest, mode, checkout: opts.checkout, version: opts.version, names: visible.join(','), ...(router ? { router } : {}), ...(ctx ? { context: ctx } : {}) },
meta: { id, target: t.name, dest, mode, checkout: opts.checkout, version: opts.version, names: visible.join(','), ...(router ? { router } : {}), ...(context ? { context } : {}) },
files: recorded, dirs: [...dirs].sort((a, b) => b.length - a.length), blocks,
});
record([...want, ...(prev?.files ?? []).filter(f => !files.has(f.path))]);
for (const b of prev?.blocks ?? []) if (b.path !== ctx) cutBlock(opts, b.path, b.sha);
for (const [p, sha] of prevFiles) {
if (files.has(p)) continue;
const disk = onDiskSha(p);
if (disk === sha) fs.rmSync(p, { force: true }); else if (disk) kept.push(keepEdit(p, stamp));
}
for (const dir of [...dirs].sort((a, b) => b.length - a.length)) {
if ([...files.keys()].some(p => p.startsWith(dir + path.sep))) continue;
try { fs.rmdirSync(dir); dirs.delete(dir); } catch {}
}
for (const [p, b] of files) {
const disk = onDiskSha(p);
if (disk === sha256(b)) continue;
@@ -499,9 +572,10 @@ export function register(opts: RegisterOptions): RegisterResult {
}
record(want);
}
if (ctxText !== null && ctxText !== (fs.existsSync(ctx) ? fs.readFileSync(ctx, 'utf8') : null)) {
fs.mkdirSync(path.dirname(ctx), { recursive: true });
fs.writeFileSync(ctx, ctxText);
for (const [file, text] of blockWrites) {
if (text === (fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : null)) continue;
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, text);
}
if (opts.registry && t.render === 'host') shellRegistry(opts, 'gstack_install_registry_upsert', [t.name, 'global', '-', dest, opts.checkout, opts.checkout, opts.version, '-', '-']);
return { id, target: t.name, dest, mode, status: !prev ? 'installed' : same ? 'unchanged' : 'updated', written, skills, router, ledger: lfile, kept };
@@ -536,7 +610,7 @@ export function refresh(base: Omit<RegisterOptions, 'target'>, skip: Set<string>
.map(({ ledger: l }) => register({
...base, target: getTarget(l.meta.target), mode: l.meta.mode as SkillsMode,
skillsDir: l.meta.context && l.meta.dest.startsWith(ledgerDir(base.stateRoot)) ? undefined : l.meta.dest,
context: l.meta.context || undefined,
context: l.meta.context || undefined, inherit: true,
}));
}
+85
View File
@@ -0,0 +1,85 @@
/**
* Trigger-first skill wording for harness listings (GSTA-135 skill use).
*
* Frozen rule, built only from each skill's own frontmatter, and the trigger
* part always comes first:
* - Router lines (lib/harness-register.ts, 160 chars): the description's own
* trigger sentence (its first sentence that starts "Use when", "Use to",
* "Use for", ...), followed by the description's first sentence when both
* fit. A description with no trigger sentence (the catalog-trimmed Claude
* render) uses the triggers list below instead.
* - Hermes descriptions (scripts/gen-skill-docs.ts, hosts/hermes.ts): a lead
* of at most 57 chars, the part Hermes's skills index shows: "Use for: "
* and the skill's `triggers:` list in frontmatter order, as many whole
* entries as fit; without triggers, the trigger sentence (or first
* sentence) cut at a word. The description's own trigger sentence, which
* the list repeats, is dropped, so a render does not grow.
*/
const TRIGGER_SENTENCE = /^Use (when|whenever|to|for|after|before|on|if)\b/;
export const normalizeDescription = (description: string) => description.replace(/\s*\(gstack\)\s*$/, '').replace(/\s+/g, ' ').trim();
export const sentences = (description: string): string[] => normalizeDescription(description).split(/(?<=[.!?])\s+/).filter(Boolean);
/** Cuts at the last word boundary that leaves room for "...". */
export function cutWords(text: string, max: number): string {
if (text.length <= max) return text;
const cut = text.slice(0, max - 3);
const space = cut.lastIndexOf(' ');
return (space > max / 3 ? cut.slice(0, space) : cut).replace(/[\s,;:]+$/, '') + '...';
}
/** The description's own trigger sentence, or ''. */
export const triggerSentence = (description: string) => sentences(description).find(s => TRIGGER_SENTENCE.test(s)) ?? '';
/** "Use for: a, b, c." from a skill's triggers list, as many whole entries as fit in max chars ('' without triggers). */
export function triggerList(triggers: string[], max: number): string {
const items = triggers.map(t => t.replace(/\s+/g, ' ').trim()).filter(Boolean);
if (!items.length) return '';
let lead = 'Use for: ' + items[0] + '.';
for (const t of items.slice(1)) {
const next = lead.slice(0, -1) + ', ' + t + '.';
if (next.length > max) break;
lead = next;
}
return cutWords(lead, max);
}
/** A trigger-first lead of at most max chars: the triggers list, else the trigger sentence or first sentence cut at a word. */
export function triggerLead(description: string, triggers: string[], max: number): string {
return triggerList(triggers, max) || cutWords(triggerSentence(description) || sentences(description)[0] || '', max);
}
/** A description led by triggerLead on its own first line; the description's trigger sentence is dropped when the lead comes from the triggers list, which that sentence repeats. */
export function withTriggerLead(description: string, triggers: string[], max: number): string {
const lead = triggerLead(description, triggers, max);
const sentence = triggerSentence(description);
if (!sentence || !triggerList(triggers, max)) return lead + '\n' + description;
const tag = /\(gstack\)\s*$/.test(description) ? ' (gstack)' : '';
return lead + '\n' + sentences(description).filter(s => s !== sentence).join(' ') + tag;
}
/** A router line of at most max chars: the trigger part first, then the description's first sentence when both fit. */
export function routerLine(description: string, triggers: string[], max = 160): string {
const first = sentences(description)[0] ?? '';
const trigger = triggerSentence(description) || triggerList(triggers, max);
if (!trigger) return cutWords(first, max);
const both = trigger + ' ' + first;
return first && first !== trigger && both.length <= max ? both : cutWords(trigger, max);
}
/** The values of a YAML block list field (`field:` then ` - value` lines) in a SKILL.md's frontmatter. */
export function frontmatterList(md: string, field: string): string[] {
const fm = md.startsWith('---\n') ? md.slice(4, md.indexOf('\n---', 4)) : '';
const lines = fm.split('\n');
const i = lines.findIndex(l => l.trimEnd() === field + ':');
if (i < 0) return [];
const out: string[] = [];
for (const l of lines.slice(i + 1)) {
const m = /^\s*-\s+(.*)$/.exec(l);
if (!m) break;
out.push(m[1].trim().replace(/^["']|["']$/g, ''));
}
return out;
}