Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(skillpack): trusting a new third-party pack asks through the consent primitive (C2)

garrytanc69fa349cde9
diff --git a/docs/architecture/key-files/skills.md b/docs/architecture/key-files/skills.md
index 3a248dad42..2af98a6bd4 100644
--- a/docs/architecture/key-files/skills.md
+++ b/docs/architecture/key-files/skills.md
@@ -25,7 +25,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/skillpack/{init-brain-pack,brain-pack-advisory,brain-resident-locate,nag-state}.ts` — brain-resident skillpacks. `manifest-v1.ts` gains optional `brain_resident` + `schema_pack` (additive). `runInitBrainPack` scaffolds a pack beside brain content (`brain_resident:true`, exact `gbrain_min_version`, 5-section machine-parseable README); `applyWritePlan` is factored out of `init-scaffold.ts` for the shared refuse-overwrite loop. Topology A: `src/commands/sources.ts` `runAdd` prints `brain-pack-advisory` to stderr after `opsAddSource`, fail-open; `nag-state.ts` (`~/.gbrain/skillpack-nag-state.json`) keys declines by `(source-repo brain_id, source_id, pack_name)` with pure `decideNagAction` (first/reminder/version-bump/ceiling) — declines count ONLY on CLI-interactive displays. Topology B: `brain-resident-locate.loadResidentPacksForServer` (source-scoped via `sourceScopeOpts`) backs the `list_brain_skillpack` op; `getResidentSkillDetail` backs `get_skill` `source_id`; `scaffold_spec` is the git source, never a server FS path. Tests: `test/skillpack-{init-brain-pack,nag-state,brain-resident-locate}.test.ts` + the brain-resident cases in `test/skillpack-manifest-v1.test.ts`.
-- `src/core/skillpack/{manifest-v1,tarball,state,remote-source,trust-prompt,bootstrap-display,scaffold-third-party,registry-schema,registry-client,rubric,doctor,init-scaffold,pack-publish,endorse,audit}.ts` + `examples/skillpack-reference/` + `docs/skillpack-anatomy.md` + `scripts/build-skillpack-anatomy.ts` — third-party skillpack ecosystem. `gbrain skillpack scaffold <owner/repo|https-url|./tgz|./local-dir>` resolves the spec via `classifySpec`, fetches through SSRF-hardened `git-remote.ts` (git) or extracts the tarball into `~/.gbrain/skillpack-cache/<host>/<owner>/<repo>/<sha>/`, validates `skillpack.json` (api_version `gbrain-skillpack-v1`), checks `gbrain_min_version`, surfaces a TOFU first-install identity-confirm prompt (author + source + pinned commit + tarball SHA + tier; non-TTY requires `--trust`), records the pin in machine-owned `~/.gbrain/skillpack-state.json` (schema `gbrain-skillpack-state-v1`, atomic `.tmp + rename`, `isAlreadyTrusted` skips re-prompt on author+pin match), runs through `enumerateScaffoldEntries` → `copyArtifacts` (one-time additive, refuses to overwrite), then DISPLAYS `runbooks/bootstrap.md` WITHOUT executing (deliberately does not auto-execute). Registry catalog at `garrytan/gbrain-skillpack-registry` split into `registry.json` (PR-able, `gbrain-registry-v1`) + `endorsements.json` (maintainer-only overlay, `gbrain-endorsements-v1`); `effectiveTier` merges. `registry-client.ts` fetches both via `If-None-Match` etag with 1h soft-TTL + stale-fallback (origins `fresh_fetch | cache_warm | cache_soft_stale | cache_hard_stale`); hard-fail only on no-cache + no-network. CLI: `gbrain skillpack {search,info,registry,doctor,init,pack,endorse}`. Doctor walks `SKILLPACK_RUBRIC_V1` (10 binary dimensions: 5 required CORE — manifest_valid, skills_have_skill_md, routing_evals_present ≥5 intents, skills_have_unique_triggers MECE, changelog_present_and_current — and 5 quality BADGES — unit_tests_present, e2e_tests_present, llm_eval_present ≥3 cases, bootstrap_runbook_present, license_present); tier eligibility: `endorsed` needs all 10, `community` needs core + ≥3 badges, `experimental` needs core only, `blocked` when any core fails. `--quick` ~5s structural sweep; `--fix --yes` auto-scaffolds `auto_fixable: true` dimensions and refuses to overwrite files whose mtime is newer than `skillpack.json`. `gbrain skillpack init <name>` lands 11 files (skillpack.json, SKILL.md, routing-eval.jsonl, test/example.test.ts, e2e/example.e2e.test.ts, evals/example.judge.json, runbooks/{bootstrap,uninstall,upgrade-template}.md, CHANGELOG, README, LICENSE); freshly-init'd scores 10/10; `--minimal` skips test/e2e/evals. `gbrain skillpack pack` packs a deterministic tarball via GNU tar (`--sort=name --mtime=@0 --owner=0 --group=0 --numeric-owner` + `GZIP=-n` + `TZ=UTC`); refuses on `tier_eligibility === 'blocked'`. Extract caps (5000 files / 100MB total / 1MB per file / 255-char paths / 100:1 compression ratio); rejects symlinks/hardlinks/devices/FIFOs. `gbrain skillpack endorse <name> [--tier ...] [--push] [--dry-run]` runs in a clone of the registry repo: validates the pack in `registry.json`, mutates `endorsements.json` via pure `applyEndorsement`, stable-key-orders the write, commits `endorse: <name> -> <tier>`, optionally pushes. JSONL audit at `~/.gbrain/audit/skillpack-YYYY-Www.jsonl` (ISO-week rotated, honors `GBRAIN_AUDIT_DIR`). `examples/skillpack-reference/` is a 10/10 reference pack pinned by `test/e2e/skillpack-third-party.test.ts`. `docs/skillpack-anatomy.md` auto-generated via `scripts/build-skillpack-anatomy.ts` (`--check` for CI drift). CLI dispatch in `src/commands/skillpack.ts` disambiguates third-party (contains `/`, `://`, `.tgz`) from bundled-skill kebab; kebab routes bundled-first, registry-fallback. Tests: `test/skillpack-{manifest-v1,tarball,state,remote-source,trust-prompt,registry-schema,registry-client,rubric,doctor,init-scaffold,pack-publish,endorse,audit,scaffold-third-party}.test.ts` + `test/e2e/skillpack-third-party.test.ts`. Spec at `docs/designs/SKILLPACK_REGISTRY_V1_SPEC.md`.
+- `src/core/skillpack/{manifest-v1,tarball,state,remote-source,trust-prompt,bootstrap-display,scaffold-third-party,registry-schema,registry-client,rubric,doctor,init-scaffold,pack-publish,endorse,audit}.ts` + `examples/skillpack-reference/` + `docs/skillpack-anatomy.md` + `scripts/build-skillpack-anatomy.ts` — third-party skillpack ecosystem. `gbrain skillpack scaffold <owner/repo|https-url|./tgz|./local-dir>` resolves the spec via `classifySpec`, fetches through SSRF-hardened `git-remote.ts` (git) or extracts the tarball into `~/.gbrain/skillpack-cache/<host>/<owner>/<repo>/<sha>/`, validates `skillpack.json` (api_version `gbrain-skillpack-v1`), checks `gbrain_min_version`, surfaces a TOFU first-install identity-confirm prompt (author + source + pinned commit + tarball SHA + tier; prompted through interaction.readLine; with no human at the terminal the CLI asks through `requireConsent` (effect `persistent_install`, preapprovals never apply): `--trust` or `--yes` is the user's approval, otherwise nothing is written and it exits 3 with the consent payload), records the pin in machine-owned `~/.gbrain/skillpack-state.json` (schema `gbrain-skillpack-state-v1`, atomic `.tmp + rename`, `isAlreadyTrusted` skips re-prompt on author+pin match), runs through `enumerateScaffoldEntries` → `copyArtifacts` (one-time additive, refuses to overwrite), then DISPLAYS `runbooks/bootstrap.md` WITHOUT executing (deliberately does not auto-execute). Registry catalog at `garrytan/gbrain-skillpack-registry` split into `registry.json` (PR-able, `gbrain-registry-v1`) + `endorsements.json` (maintainer-only overlay, `gbrain-endorsements-v1`); `effectiveTier` merges. `registry-client.ts` fetches both via `If-None-Match` etag with 1h soft-TTL + stale-fallback (origins `fresh_fetch | cache_warm | cache_soft_stale | cache_hard_stale`); hard-fail only on no-cache + no-network. CLI: `gbrain skillpack {search,info,registry,doctor,init,pack,endorse}`. Doctor walks `SKILLPACK_RUBRIC_V1` (10 binary dimensions: 5 required CORE — manifest_valid, skills_have_skill_md, routing_evals_present ≥5 intents, skills_have_unique_triggers MECE, changelog_present_and_current — and 5 quality BADGES — unit_tests_present, e2e_tests_present, llm_eval_present ≥3 cases, bootstrap_runbook_present, license_present); tier eligibility: `endorsed` needs all 10, `community` needs core + ≥3 badges, `experimental` needs core only, `blocked` when any core fails. `--quick` ~5s structural sweep; `--fix --yes` auto-scaffolds `auto_fixable: true` dimensions and refuses to overwrite files whose mtime is newer than `skillpack.json`. `gbrain skillpack init <name>` lands 11 files (skillpack.json, SKILL.md, routing-eval.jsonl, test/example.test.ts, e2e/example.e2e.test.ts, evals/example.judge.json, runbooks/{bootstrap,uninstall,upgrade-template}.md, CHANGELOG, README, LICENSE); freshly-init'd scores 10/10; `--minimal` skips test/e2e/evals. `gbrain skillpack pack` packs a deterministic tarball via GNU tar (`--sort=name --mtime=@0 --owner=0 --group=0 --numeric-owner` + `GZIP=-n` + `TZ=UTC`); refuses on `tier_eligibility === 'blocked'`. Extract caps (5000 files / 100MB total / 1MB per file / 255-char paths / 100:1 compression ratio); rejects symlinks/hardlinks/devices/FIFOs. `gbrain skillpack endorse <name> [--tier ...] [--push] [--dry-run]` runs in a clone of the registry repo: validates the pack in `registry.json`, mutates `endorsements.json` via pure `applyEndorsement`, stable-key-orders the write, commits `endorse: <name> -> <tier>`, optionally pushes. JSONL audit at `~/.gbrain/audit/skillpack-YYYY-Www.jsonl` (ISO-week rotated, honors `GBRAIN_AUDIT_DIR`). `examples/skillpack-reference/` is a 10/10 reference pack pinned by `test/e2e/skillpack-third-party.test.ts`. `docs/skillpack-anatomy.md` auto-generated via `scripts/build-skillpack-anatomy.ts` (`--check` for CI drift). CLI dispatch in `src/commands/skillpack.ts` disambiguates third-party (contains `/`, `://`, `.tgz`) from bundled-skill kebab; kebab routes bundled-first, registry-fallback. Tests: `test/skillpack-{manifest-v1,tarball,state,remote-source,trust-prompt,registry-schema,registry-client,rubric,doctor,init-scaffold,pack-publish,endorse,audit,scaffold-third-party}.test.ts` + `test/e2e/skillpack-third-party.test.ts`. Spec at `docs/designs/SKILLPACK_REGISTRY_V1_SPEC.md`.
- `src/core/skillpack/{personas,bridge-state,harness-bridge}.ts` + `src/commands/skillpack/{shared,scaffold,reference,harness}.ts` — the harness skill bridge. `src/commands/skillpack.ts` is a peeled FAÇADE (dispatch + HELP_TOP + the install/uninstall removal errors; module-size ratchet); per-subcommand handlers live in `src/commands/skillpack/` and the flag registry scans the dir via the façade's `facadeExpansion` entry — spell foreign CLI flags dash-less in these modules' comments/strings (prose-bleed class). `scaffold --harness <claude-code|openclaw|codex|opencode>` installs a persona-curated set into the harness's native skills dir: personas live in `skills/plugin-lanes.json#personas` (`personas.ts` is the SINGLE validation implementation — `scripts/generate-plugin-tree.ts` imports it; membership ⊆ the plugin lane set, so lane-excluded slugs are refused with their recorded reason); slugs path-resolve via `bundle.ts`'s `universe:'manifest'` (the 8 lane additions are all absent from openclaw.plugin.json#skills). Safety: frontmatter fail-loud gate pre-write (a frontmatterless SKILL.md bricks Codex sessions), target-side confinement in `assertTargetsConfined` (deepest-existing-ancestor realpath — copy.ts confines SOURCES only), refuse-overwrite, and written-only ownership in `bridge-state.ts` (`~/.gbrain/skillpack-bridge-state.json`, schema `gbrain-skillpack-bridge-v1`, fail-open load, install-time sha256 per written file — never touches `skillpack-state.json`, whose loader drops unknown keys). `--stub` renders cold-pull pointers (frontmatter verbatim + `<!-- gbrain-skill-stub v1 -->` marker; ships the shared-dep closure AND sibling aux files — `get_skill` serves only the SKILL.md body) behind a three-check preflight in `src/commands/skillpack/harness.ts` (publish gate dual-plane, per-slug servability via `verifySlugsServable`, best-effort local surface warn — the module deliberately does NOT import `src/mcp/surface.ts`, whose comments would bleed serve flags into the allowlist; `get_skill ∉ STARTER_OPS` is pinned by a contract test). `reference --harness` is a stub-aware three-way lens (`local_edit` vs `upstream_drift` vs `unknown` — no install-time hash, never auto-applied — via the hash ledger; marker fallback survives state loss both directions) + `--apply-clean-hunks` (refuses stub files); `remove --harness` deletes ledger-owned files only; `skillpack status` renders an installed-bridges section from `collectBridgesStatus`. openclaw delegates to `runScaffold({skillSlugs})`; codex/opencode require an explicit dest until observation runs. Claude-code dirs come from `host-specs.ts` (`claudeUserSkillsDir`/`claudeProjectSkillsDir`, HOME-env-first). Tests: `test/skillpack-{personas,bridge-state,harness-bridge,reference-harness,scaffold-harness}.test.ts`. Doc: the harness-bridge section of `docs/guides/skillpacks-as-scaffolding.md`.
diff --git a/scripts/agent-contract-baselines/interactive-io.tsv b/scripts/agent-contract-baselines/interactive-io.tsv
index 6c297e6e28..c56b87108e 100644
--- a/scripts/agent-contract-baselines/interactive-io.tsv
+++ b/scripts/agent-contract-baselines/interactive-io.tsv
@@ -9,5 +9,4 @@ src/commands/report.ts 1
src/commands/upgrade.ts 1
src/commands/watch.ts 1
src/core/post-upgrade-reembed.ts 1
-src/core/skillpack/trust-prompt.ts 1
src/mcp/server.ts 2
diff --git a/src/commands/skillpack/scaffold.ts b/src/commands/skillpack/scaffold.ts
index c885024173..4fdba5409d 100644
--- a/src/commands/skillpack/scaffold.ts
+++ b/src/commands/skillpack/scaffold.ts
@@ -28,6 +28,7 @@ import {
import { SkillpackManifestError } from '../../core/skillpack/manifest-v1.ts';
import { VERSION } from '../../version.ts';
import { findGbrainOrDie, resolveWorkspace } from './shared.ts';
+import { consentGate } from '../../core/consent-cli.ts';
export async function cmdScaffold(args: string[]): Promise<void> {
// Harness lane (cathedral-7): `--harness <h>` installs a persona-curated
@@ -50,7 +51,8 @@ export async function cmdScaffold(args: string[]): Promise<void> {
' --workspace PATH Target workspace (default: auto-detected)\n' +
' --all Scaffold every bundled skill (gbrain only)\n' +
' --dry-run Validate + report; no writes\n' +
- ' --trust Skip first-install confirm prompt (CI / unattended agents)\n' +
+ ' --trust The user\'s approval to trust a new third-party author + pin\n' +
+ ' (without it a non-interactive run writes nothing and exits 3)\n' +
' --no-cache Force fresh clone/extract for third-party sources\n' +
' --json Stable JSON envelope for agent consumption',
);
@@ -106,6 +108,7 @@ export async function cmdScaffold(args: string[]): Promise<void> {
trustFlag,
noCache,
json,
+ args,
});
return;
}
@@ -121,6 +124,7 @@ export async function cmdScaffold(args: string[]): Promise<void> {
trustFlag,
noCache,
json,
+ args,
});
return;
}
@@ -172,6 +176,8 @@ interface ThirdPartyScaffoldOptions {
trustFlag: boolean;
noCache: boolean;
json: boolean;
+ /** Raw argv, for the consent request (`--yes`, `--trust`). */
+ args: readonly string[];
}
async function runThirdPartyScaffold(opts: ThirdPartyScaffoldOptions): Promise<void> {
@@ -209,16 +215,38 @@ async function runThirdPartyScaffold(opts: ThirdPartyScaffoldOptions): Promise<v
// Step 2: orchestrator handles manifest validation, trust prompt, copy,
// state.json update, and bootstrap display.
try {
- const result = await runScaffoldThirdParty(
+ const scaffold = (trustFlag: boolean) => runScaffoldThirdParty(
{
resolved,
targetWorkspace: opts.targetWorkspace,
- trustFlag: opts.trustFlag,
+ trustFlag,
dryRun: opts.dryRun,
tier: registryTier,
},
VERSION,
);
+ let result = await scaffold(opts.trustFlag);
+ // A4: no human to answer the trust prompt. The user decides whether this
+ // author + pin is trusted: refuse with the consent payload (exit 3), or
+ // proceed when the caller already carries the approval (--yes). A generic
+ // persistent_install preapproval never trusts third-party code.
+ if (result.status === 'aborted_no_trust' && result.trustDecision.reason === 'non_tty_no_trust_flag') {
+ const m = result.manifest;
+ const pin = result.resolved.pinned_commit ? `commit ${result.resolved.pinned_commit.slice(0, 12)}`
+ : result.resolved.tarball_sha256 ? `tarball sha256:${result.resolved.tarball_sha256.slice(0, 12)}` : 'unpinned';
+ const auth = await consentGate({
+ command: 'skillpack scaffold', effects: ['persistent_install'], actor: 'agent',
+ what: `Install the third-party skillpack ${m.name}@${m.version} by ${m.author}`,
+ why: `Adds ${m.name}'s skills to this workspace (${m.description}).`,
+ risk: `Copies third-party skills from ${result.resolved.source} (${pin}) into ${opts.targetWorkspace}; your agent will follow them as instructions, including any scripts they reference. `
+ + 'Trust is recorded for this exact author and pin; a different author or pin asks again.',
+ user_message: `Install the skillpack ${m.name} by ${m.author} from ${result.resolved.source} (${pin})? Its skills become instructions your agent follows.`,
+ argv: ['gbrain', 'skillpack', 'scaffold', opts.spec, ...opts.args.filter(a => a !== opts.spec && a !== '--yes' && a !== '--trust')],
+ args: opts.args,
+ }, { json: opts.json, env: { preapprovals: {} } });
+ if (!auth) return;
+ result = await scaffold(true);
+ }
if (opts.json) {
console.log(
diff --git a/src/core/skillpack/trust-prompt.ts b/src/core/skillpack/trust-prompt.ts
index a3e6160005..9dd01c33e3 100644
--- a/src/core/skillpack/trust-prompt.ts
+++ b/src/core/skillpack/trust-prompt.ts
@@ -13,7 +13,7 @@
* inject a fake reader).
*/
-import { createInterface } from 'readline';
+import { isInteractive, readLine } from '../interaction.ts';
import type { ResolvedSource } from './remote-source.ts';
import type { SkillpackManifest } from './manifest-v1.ts';
@@ -67,19 +67,14 @@ export interface AskTrustOptions {
trustFlag?: boolean;
/** Inject a custom reader for testing. */
readLine?: (question: string) => Promise<string>;
- /** Default reader uses readline against stdin. */
+ /** Default: isInteractive() (a human can answer the prompt). */
isTTY?: boolean;
}
-/** Default TTY-aware reader. */
-function defaultReadLine(question: string): Promise<string> {
- const rl = createInterface({ input: process.stdin, output: process.stderr });
- return new Promise((resolveAns) => {
- rl.question(question, (answer) => {
- rl.close();
- resolveAns(answer);
- });
- });
+/** Default reader: interaction.readLine (stderr prompt; EOF/timeout read as a decline, never a hang). */
+async function defaultReadLine(question: string): Promise<string> {
+ const read = await readLine({ prompt: question });
+ return read.kind === 'line' ? read.text : '';
}
/**
@@ -116,10 +111,10 @@ export async function askTrust(
return { trusted: true, reason: 'trust_flag_bypassed' };
}
- const isTTY = opts.isTTY ?? Boolean(process.stdin.isTTY && process.stderr.isTTY);
+ const isTTY = opts.isTTY ?? isInteractive();
if (!isTTY) {
process.stderr.write(
- '[skillpack] non-TTY environment and no --trust flag; refusing to scaffold a new third-party source without explicit consent.\n',
+ '[skillpack] no human at this terminal and no --trust: the user decides whether to trust a new third-party source; nothing was written.\n',
);
return { trusted: false, reason: 'non_tty_no_trust_flag' };
}