@cohirer/harness-pack 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Starlinks
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,159 @@
1
- # Temporary Holding Version
1
+ # harness-pack
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ One agent bundle in, per-harness release artifacts out.
4
+
5
+ <img width="896" height="222" src="https://github.com/user-attachments/assets/de199dc5-1ff6-4f03-8820-16bd2d2a4900" />
6
+
7
+ **Status:** WorkBuddy is the only supported target today. The `claude-code` and
8
+ `codex` presets are experimental and not part of the supported surface.
9
+
10
+ A *bundle* is a source tree holding Agent Skills (`skills/<name>/SKILL.md` plus
11
+ whatever files they reference), agent persona files, and an MCP wiring
12
+ declaration. `harness-pack` runs the bundle's repo-owned build steps, copies
13
+ the resulting release views, stamps a version into a per-harness manifest
14
+ template, and emits one artifact directory per target plus `dist/release.json`
15
+ with a sha256 for every file.
16
+
17
+ **Content shape is repo-owned.** What ships, how sources become release
18
+ artifacts, and which doc references point at them are decided by the repo that
19
+ owns the content: each skill's build step produces a release view directory
20
+ (only ship files, packaged artifacts, rewritten references), and `skills`
21
+ points at those views. `harness-pack` never prunes or rewrites content — it
22
+ only performs the harness-specific mechanics (envelope layout, manifest
23
+ placement, MCP declaration, release hashing).
24
+
25
+ ```sh
26
+ npx @cohirer/harness-pack@0.2.0 build --config pack.yaml --version 1.2.3
27
+ npx @cohirer/harness-pack@0.2.0 install-dev --config pack.yaml --target workbuddy
28
+ npx @cohirer/harness-pack@0.2.0 lint --config pack.yaml
29
+ ```
30
+
31
+ Pin the exact version in build scripts (as above) so a release can be
32
+ reproduced; a floating tag would let the packer change under a fixed bundle.
33
+
34
+ Targets are selected by preset; each target in the config picks one and
35
+ supplies its own manifest template:
36
+
37
+ | preset | artifact layout | MCP declaration |
38
+ |---|---|---|
39
+ | `workbuddy` | `.codebuddy-plugin/plugin.json`, `skills/`, `agents/` | root `.mcp.json`, `{{root}}` = `.`; the manifest points at it via `dependencies.mcpServers: "./.mcp.json"` (the open-platform documented form; keep that line in the template) |
40
+ | `claude-code` | `.claude-plugin/plugin.json`, `skills/`, `agents/` | `.mcp.json`, `{{root}}` = `${CLAUDE_PLUGIN_ROOT}` |
41
+ | `codex` | `plugin.json` (Agent Plugins 1.0), `skills/`, `agents/` | `mcp.json` (`$schema`, `type: stdio`, `cwd: "./"`), `{{root}}` = `.` |
42
+
43
+ ## Config
44
+
45
+ ```yaml
46
+ name: my-bundle
47
+ version: 0.1.0 # or pass --version
48
+ skills: # release views, copied to <preset skills dir>/<basename>
49
+ - skills/my-skill/release/my-skill
50
+ lint: # optional: source dirs to validate instead of the views
51
+ - skills/my-skill
52
+ agents: # optional
53
+ - agents/my-agent.md
54
+ include: # optional root entries copied verbatim
55
+ - avatars
56
+ build: # optional commands, run in the bundle root first
57
+ - 'make -C skills/my-skill pack'
58
+ mcp: # stdio servers shipped with every target
59
+ myserver:
60
+ command: node
61
+ args: ['{{root}}/bin/mcp.mjs']
62
+ displayName: {en: My Tool, zh: 我的工具} # connector-card metadata:
63
+ description: {en: ..., zh: ...} # rendered into x-workbuddy by
64
+ icon: ./avatars/my-tool.svg # workbuddy, stripped elsewhere
65
+ display: # person layer, rendered via {{display.*}} tokens
66
+ displayName: {en: My Agent, zh: 我的助手}
67
+ profession: {en: Automation Specialist, zh: 自动化专家}
68
+ displayDescription: {en: ..., zh: ...} # zh: 40-50 hanzi (WorkBuddy rule)
69
+ avatar: avatars/expert.png
70
+ tags: [{en: ..., zh: ...}, {en: ..., zh: ...}, {en: ..., zh: ...}]
71
+ quickPrompts: [{en: ..., zh: ...}, {en: ..., zh: ...}, {en: ..., zh: ...}]
72
+ defaultInitPrompt: {en: ..., zh: ...} # must equal quickPrompts[0]
73
+ targets:
74
+ claude:
75
+ preset: claude-code
76
+ manifest: templates/claude-plugin.json # {{name}} / {{version}} tokens
77
+ mcp: # optional per-target servers, field-merged
78
+ extra: { command: extra-mcp }
79
+ workbuddy:
80
+ preset: workbuddy
81
+ manifest: templates/workbuddy-plugin.json
82
+ display: # optional whole-key overrides over the layer above
83
+ avatar: avatars/expert-wb.png # e.g. the market wants PNG
84
+ ```
85
+
86
+ - **build** — a plain command list run in the bundle root before assembly.
87
+ Packaging belongs to the repos that own the content (`make -C skills/x pack`,
88
+ `npm pack`, ...); harness-pack only runs the commands. A non-zero exit aborts
89
+ the build.
90
+ - **mcp** — stdio servers declared once for all targets. `{{root}}` in any
91
+ string of a server definition is rendered by the preset into that harness's plugin-root
92
+ reference (WorkBuddy's `.`, Claude Code's `${CLAUDE_PLUGIN_ROOT}`, Codex's
93
+ `.` with `cwd: "./"`), so the artifact carries no machine-specific path and
94
+ consumers copy it verbatim. WorkBuddy's expert service resolves `./` args
95
+ against the installed plugin dir; that is the channel the published expert
96
+ package uses.
97
+ `targets.<name>.mcp` merges field-by-field over the bundle-level server of
98
+ the same name: an override replaces only the fields it sets.
99
+ Per-server presentation keys (`displayName` / `description` / `icon` /
100
+ `auth`) are canonical: presets with a metadata envelope render them into it
101
+ (workbuddy → `x-workbuddy`, the connector-card copy; the app strips the
102
+ envelope before writing the user's connector config), presets without one
103
+ strip them from the artifact.
104
+ - **display** — the person layer above the canonical schema. Platforms that
105
+ present a bundle as a person (WorkBuddy experts: humanized avatar, name,
106
+ profession) render these keys via `{{display.*}}` tokens (dotted paths
107
+ work, e.g. `{{display.displayName.en}}`) — persona output comes from these
108
+ keys, never from `name`, which stays the tool id. A token that exactly
109
+ fills a JSON string splices any JSON value; embedded in longer text it must
110
+ resolve to a string; an unresolvable key fails the build.
111
+ `targets.<name>.display` overrides keys wholesale (platform media formats).
112
+ - **manifest lint** — per-preset platform rules run on every build against
113
+ the rendered manifests (`src/manifest-lint.ts`), so the official-market
114
+ requirements are encoded once instead of re-checked by each bundle:
115
+ structural problems fail the build (missing listing fields, `plugin != name`,
116
+ `defaultInitPrompt != quickPrompts[0]`, tags/quickPrompts count, agentName
117
+ not matching an `agents/` stem, avatar file missing); market-copy policy
118
+ warns on stderr (zh word count, avatar format/size, `author.email`). One
119
+ universal check runs for every preset: reference integrity of the shipped
120
+ tree — a `SKILL.md` or agent doc referencing a file the package does not
121
+ contain fails the build (the market's "missing file" rejection, caught
122
+ before submission).
123
+ - **install-dev** — build (same gates as a release), then deploy each target
124
+ to that harness's development location on this machine, for the
125
+ edit-summon-verify loop. What "deploy" means is preset mechanics:
126
+
127
+ | preset | behavior |
128
+ |---|---|
129
+ | `workbuddy` | install into the local `my-experts` marketplace (`WORKBUDDY_HOME` or `~/.workbuddy`): replace `plugins/my-experts/plugins/<name>/`, upsert the marketplace entry, drop the app's plugin cache, patch `avatarUrl` onto the installed manifest; summon it straight from the expert picker (the app rescans the marketplace on demand) |
130
+ | `claude-code` | load in place — print `claude --plugin-dir <dist dir>`; edits are picked up by `/reload-plugins`, nothing to install |
131
+ | `codex` | print the documented loop (cache-copy install via a local marketplace; skills iterate in place via `~/.agents/skills`) |
132
+
133
+ Build steps run with `HARNESS_PACK_DEV=1`, so repo-owned view scripts may
134
+ assemble from working trees (uncommitted edits included) instead of
135
+ committed archives — pruning and packaging stay exactly as a release.
136
+ Deployed dev copies are normal marketplace entries: the market copy of the
137
+ same-named expert stays installed, and per session the summoned one wins
138
+ (local resolution prefers `my-experts`); delete the dev copy to fall back.
139
+ - **lint** — checks `SKILL.md` against the portable subset of the
140
+ [Agent Skills spec](https://agentskills.io/specification): frontmatter
141
+ `name`/`description` present, `name` matches the directory and is
142
+ kebab-case, non-standard frontmatter fields warn. It validates `lint` paths
143
+ when given, else the `skills` release views; `make lint` therefore works
144
+ before any build toolchain is installed.
145
+
146
+ See [docs/design.md](docs/design.md) for the rationale, layering and the
147
+ release contract.
148
+
149
+ ## Development
150
+
151
+ ```sh
152
+ pnpm install
153
+ pnpm test
154
+ pnpm build # tsc -> dist/
155
+ ```
156
+
157
+ ## License
158
+
159
+ MIT
package/dist/cli.js ADDED
@@ -0,0 +1,93 @@
1
+ #!/usr/bin/env node
2
+ import path from 'node:path';
3
+ import { runBuild, runLint } from './pipeline.js';
4
+ import { devInstall } from './dev-install.js';
5
+ import { ConfigError } from './config.js';
6
+ const USAGE = `harness-pack — pack one agent bundle into per-harness artifacts
7
+
8
+ Usage:
9
+ harness-pack build [--config <pack.yaml>] [--target <name>]... [--version <v>]
10
+ [--out <dir>]
11
+ harness-pack install-dev [--config <pack.yaml>] [--target <name>]... [--version <v>]
12
+ harness-pack lint [--config <pack.yaml>]
13
+
14
+ Defaults: --config pack.yaml, --out <config-dir>/dist. --version overrides the
15
+ config's version. --target narrows the build (repeatable). install-dev builds
16
+ like a release, then deploys each target to that harness's development
17
+ location on this machine (see the README's install-dev section).`;
18
+ function parseArgs(argv) {
19
+ const args = { command: argv.shift(), configPath: 'pack.yaml', targets: [] };
20
+ const rest = [...argv];
21
+ while (rest.length > 0) {
22
+ const flag = rest.shift();
23
+ const value = () => {
24
+ const v = rest.shift();
25
+ if (v === undefined)
26
+ throw new ConfigError(`${flag} needs a value`);
27
+ return v;
28
+ };
29
+ switch (flag) {
30
+ case '--config':
31
+ args.configPath = value();
32
+ break;
33
+ case '--target':
34
+ args.targets.push(value());
35
+ break;
36
+ case '--version':
37
+ args.version = value();
38
+ break;
39
+ case '--out':
40
+ args.outDir = value();
41
+ break;
42
+ case '-h':
43
+ case '--help':
44
+ args.command = 'help';
45
+ break;
46
+ default: throw new ConfigError(`unknown argument '${flag}'`);
47
+ }
48
+ }
49
+ return args;
50
+ }
51
+ function main() {
52
+ const args = parseArgs(process.argv.slice(2));
53
+ if (!args.command || args.command === 'help') {
54
+ console.log(USAGE);
55
+ return args.command ? 0 : 1;
56
+ }
57
+ try {
58
+ if (args.command === 'build' || args.command === 'install-dev') {
59
+ const { command: _command, ...opts } = args;
60
+ const result = runBuild({
61
+ ...opts,
62
+ dev: args.command === 'install-dev',
63
+ configPath: path.resolve(args.configPath),
64
+ targets: args.targets.length ? args.targets : undefined,
65
+ });
66
+ if (args.command === 'install-dev') {
67
+ for (const t of result.targets)
68
+ console.log(devInstall(t));
69
+ }
70
+ else {
71
+ for (const t of result.targets) {
72
+ console.log(`built ${t.key}: ${path.relative(process.cwd(), t.outDir)} (${t.fileCount} files)`);
73
+ }
74
+ console.log(`release manifest: ${path.relative(process.cwd(), result.releasePath)}`);
75
+ }
76
+ return 0;
77
+ }
78
+ if (args.command === 'lint') {
79
+ const issues = runLint(path.resolve(args.configPath));
80
+ for (const i of issues)
81
+ console.log(`${i.severity}: ${i.skill}: ${i.message}`);
82
+ const errors = issues.filter((i) => i.severity === 'error').length;
83
+ console.log(issues.length === 0 ? 'lint clean' : `${issues.length} issue(s), ${errors} error(s)`);
84
+ return errors > 0 ? 1 : 0;
85
+ }
86
+ throw new ConfigError(`unknown command '${args.command}'`);
87
+ }
88
+ catch (e) {
89
+ console.error(`harness-pack: ${e instanceof Error ? e.message : e}`);
90
+ return e instanceof ConfigError ? 2 : 1;
91
+ }
92
+ }
93
+ process.exit(main());
package/dist/config.js ADDED
@@ -0,0 +1,134 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { parse } from 'yaml';
4
+ import { PRESETS } from './presets.js';
5
+ const PRESET_NAMES = Object.keys(PRESETS);
6
+ export class ConfigError extends Error {
7
+ }
8
+ function fail(message) {
9
+ throw new ConfigError(message);
10
+ }
11
+ export const isRecord = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
12
+ function assertStringArray(value, field) {
13
+ if (!Array.isArray(value) || value.some((v) => typeof v !== 'string')) {
14
+ fail(`${field} must be a list of strings`);
15
+ }
16
+ }
17
+ // Bundle-level servers are complete definitions; `partial` (target overrides)
18
+ // may set any subset, merged field-by-field over the bundle-level server.
19
+ function assertMcp(value, field, partial = false) {
20
+ if (!isRecord(value))
21
+ fail(`${field} must be a map of server name to stdio server definition`);
22
+ for (const [name, server] of Object.entries(value)) {
23
+ const where = `${field}.${name}`;
24
+ if (!isRecord(server))
25
+ fail(`${where} must be an object`);
26
+ const s = server;
27
+ if (!partial && (typeof s.command !== 'string' || !s.command))
28
+ fail(`${where}: command is required`);
29
+ if (partial && Object.keys(server).length === 0)
30
+ fail(`${where}: an override must set at least one field`);
31
+ if (s.args !== undefined)
32
+ assertStringArray(s.args, `${where}.args`);
33
+ if (s.cwd !== undefined && typeof s.cwd !== 'string')
34
+ fail(`${where}.cwd must be a string`);
35
+ if (s.env !== undefined && (!isRecord(s.env) || Object.values(s.env).some((v) => typeof v !== 'string'))) {
36
+ fail(`${where}.env must be a map of string values`);
37
+ }
38
+ if (s.displayName !== undefined)
39
+ assertLocalized(s.displayName, `${where}.displayName`);
40
+ if (s.description !== undefined)
41
+ assertLocalized(s.description, `${where}.description`);
42
+ if (s.icon !== undefined && (typeof s.icon !== 'string' || !s.icon))
43
+ fail(`${where}.icon must be a non-empty path or URL`);
44
+ if (s.auth !== undefined && !isRecord(s.auth))
45
+ fail(`${where}.auth must be an object`);
46
+ }
47
+ }
48
+ function assertLocalized(value, field) {
49
+ if (typeof value === 'string')
50
+ return;
51
+ if (isRecord(value) && Object.values(value).every((s) => s === undefined || typeof s === 'string'))
52
+ return;
53
+ fail(`${field} must be a string or an {en, zh} map of strings`);
54
+ }
55
+ function assertDisplay(value, field) {
56
+ if (!isRecord(value))
57
+ fail(`${field} must be a map of display keys`);
58
+ for (const key of ['displayName', 'profession', 'displayDescription', 'defaultInitPrompt']) {
59
+ if (value[key] !== undefined)
60
+ assertLocalized(value[key], `${field}.${key}`);
61
+ }
62
+ for (const key of ['tags', 'quickPrompts']) {
63
+ const list = value[key];
64
+ if (list === undefined)
65
+ continue;
66
+ if (!Array.isArray(list))
67
+ fail(`${field}.${key} must be a list of strings or {en, zh} maps`);
68
+ list.forEach((item, i) => assertLocalized(item, `${field}.${key}[${i}]`));
69
+ }
70
+ if (value.avatar !== undefined && (typeof value.avatar !== 'string' || !value.avatar)) {
71
+ fail(`${field}.avatar must be a non-empty bundle-root relative path`);
72
+ }
73
+ }
74
+ export function loadConfig(configPath) {
75
+ let raw;
76
+ try {
77
+ raw = parse(readFileSync(configPath, 'utf8'));
78
+ }
79
+ catch (e) {
80
+ fail(`cannot read ${configPath}: ${e instanceof Error ? e.message : e}`);
81
+ }
82
+ const cfg = raw;
83
+ if (typeof cfg.name !== 'string' || !cfg.name)
84
+ fail('name is required');
85
+ if (cfg.version !== undefined && typeof cfg.version !== 'string')
86
+ fail('version must be a string');
87
+ assertStringArray(cfg.skills, 'skills');
88
+ if (cfg.skills.length === 0)
89
+ fail('skills must list at least one directory');
90
+ for (const field of ['lint', 'agents', 'include', 'build']) {
91
+ if (cfg[field] !== undefined)
92
+ assertStringArray(cfg[field], field);
93
+ }
94
+ if (cfg.lint?.length === 0)
95
+ fail('lint must list at least one directory when set');
96
+ if (cfg.mcp !== undefined)
97
+ assertMcp(cfg.mcp, 'mcp');
98
+ if (cfg.display !== undefined)
99
+ assertDisplay(cfg.display, 'display');
100
+ if (!isRecord(cfg.targets) || Object.keys(cfg.targets).length === 0) {
101
+ fail('targets must declare at least one target');
102
+ }
103
+ for (const [key, target] of Object.entries(cfg.targets)) {
104
+ if (!PRESET_NAMES.includes(target.preset)) {
105
+ fail(`targets.${key}: unknown preset '${target.preset}' (known: ${PRESET_NAMES.join(', ')})`);
106
+ }
107
+ if (typeof target.manifest !== 'string' || !target.manifest) {
108
+ fail(`targets.${key}: manifest template path is required`);
109
+ }
110
+ if (target.mcp !== undefined)
111
+ assertMcp(target.mcp, `targets.${key}.mcp`, true);
112
+ if (target.display !== undefined)
113
+ assertDisplay(target.display, `targets.${key}.display`);
114
+ if (target.outDir !== undefined && path.isAbsolute(target.outDir)) {
115
+ fail(`targets.${key}: outDir must be relative`);
116
+ }
117
+ }
118
+ return cfg;
119
+ }
120
+ // CLI flags win over the config file: --version stamps the release, --target
121
+ // narrows the build, --out relocates the tree.
122
+ export function resolveConfig(cfg, opts) {
123
+ const version = opts.version ?? cfg.version;
124
+ if (!version)
125
+ fail('no version: pass --version or set version in the config');
126
+ const targets = opts.targets
127
+ ? Object.fromEntries(opts.targets.map((key) => {
128
+ if (!cfg.targets[key])
129
+ fail(`unknown target '${key}' (declared: ${Object.keys(cfg.targets).join(', ')})`);
130
+ return [key, cfg.targets[key]];
131
+ }))
132
+ : cfg.targets;
133
+ return { ...cfg, version, targets };
134
+ }
@@ -0,0 +1,69 @@
1
+ // Per-harness development deployment: how a freshly built artifact runs on
2
+ // this machine, keyed by preset (mechanics per preset: see the README's
3
+ // install-dev section).
4
+ import { cpSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
5
+ import { homedir } from 'node:os';
6
+ import path from 'node:path';
7
+ import { pathToFileURL } from 'node:url';
8
+ import { PRESETS } from './presets.js';
9
+ // WorkBuddy: my-experts is a real marketplace directory the app scans on
10
+ // every listing (re-reading each plugin dir and reconciling the manifest
11
+ // itself), so deploying is rm+copy, one marketplace entry, and dropping the
12
+ // app's plugin cache - the app copies plugins out of that cache only when the
13
+ // entry is missing, so dropping it is what makes the next summon pick up the
14
+ // new content. Same flow as teamai's updater, minus the pin machinery.
15
+ function devInstallWorkbuddy(target) {
16
+ const cfg = process.env.WORKBUDDY_HOME ?? path.join(homedir(), '.workbuddy');
17
+ const myExperts = path.join(cfg, 'plugins', 'marketplaces', 'my-experts');
18
+ const manifest = JSON.parse(readFileSync(path.join(target.outDir, PRESETS.workbuddy.manifestDest), 'utf8'));
19
+ const name = typeof manifest.name === 'string' && manifest.name ? manifest.name : target.key;
20
+ const pluginDir = path.join(myExperts, 'plugins', name);
21
+ rmSync(pluginDir, { recursive: true, force: true });
22
+ cpSync(target.outDir, pluginDir, { recursive: true });
23
+ // The expert card reads `avatar` (the app resolves it to a data URL), but
24
+ // the selection/assistant badge reads only `avatarUrl` and accepts file://
25
+ // URLs; the app never maps one to the other for custom experts.
26
+ if (typeof manifest.avatar === 'string' && manifest.avatar
27
+ && !/^(https?|data|file):/.test(manifest.avatar) && !manifest.avatarUrl) {
28
+ const patched = { ...manifest, avatarUrl: pathToFileURL(path.join(pluginDir, manifest.avatar)).href };
29
+ writeFileSync(path.join(pluginDir, PRESETS.workbuddy.manifestDest), `${JSON.stringify(patched, null, 2)}\n`);
30
+ }
31
+ const entry = {
32
+ name,
33
+ source: `./plugins/${name}`,
34
+ ...(typeof manifest.description === 'string' ? { description: manifest.description } : {}),
35
+ ...(typeof manifest.version === 'string' && manifest.version ? { version: manifest.version } : {}),
36
+ };
37
+ const marketplaceFile = path.join(myExperts, '.codebuddy-plugin', 'marketplace.json');
38
+ const marketplace = {};
39
+ try {
40
+ Object.assign(marketplace, JSON.parse(readFileSync(marketplaceFile, 'utf8')));
41
+ }
42
+ catch { /* fresh marketplace */ }
43
+ // Dedupe by name and source, the app's own manifest reconcile keys.
44
+ const plugins = (marketplace.plugins ?? []).filter((e) => e.name !== entry.name && e.source !== entry.source);
45
+ plugins.push(entry);
46
+ mkdirSync(path.dirname(marketplaceFile), { recursive: true });
47
+ writeFileSync(marketplaceFile, `${JSON.stringify({
48
+ name: marketplace.name ?? 'my-experts',
49
+ description: marketplace.description ?? 'my-experts marketplace (auto-generated)',
50
+ plugins,
51
+ }, null, 2)}\n`);
52
+ rmSync(path.join(cfg, 'plugins', 'cache', 'my-experts', name), { recursive: true, force: true });
53
+ return `dev-installed ${name} (${entry.version ?? 'unversioned'}) into ${myExperts} (cache invalidated) - summon it straight from the expert picker`;
54
+ }
55
+ const DEV_INSTALLERS = {
56
+ workbuddy: devInstallWorkbuddy,
57
+ // Claude Code loads a plugin directory in place for one session; nothing to
58
+ // install and no refresh step beyond /reload-plugins.
59
+ 'claude-code': ({ outDir }) => `load in place: claude --plugin-dir ${outDir}`
60
+ + ' (session-scoped <name>@inline, shadows the installed same-name plugin; /reload-plugins picks up edits)',
61
+ // Codex has no in-place plugin loading: local-marketplace installs load a
62
+ // cache copy, so the documented loop is reinstall + restart. Its skills are
63
+ // the exception - they load in place from ~/.agents/skills.
64
+ codex: ({ outDir }) => `codex loads installed plugins from a cache copy - reinstall from your local marketplace and restart Codex`
65
+ + ` (artifact: ${outDir}; for in-place iteration symlink skills/ entries into ~/.agents/skills)`,
66
+ };
67
+ export function devInstall(target) {
68
+ return DEV_INSTALLERS[target.preset](target);
69
+ }
package/dist/lint.js ADDED
@@ -0,0 +1,68 @@
1
+ import { existsSync, readFileSync, statSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { parse } from 'yaml';
4
+ // Checks the portable subset of the Agent Skills spec (agentskills.io):
5
+ // anything that passes here loads in every harness that claims the standard.
6
+ // Harness-specific frontmatter extensions are intentionally not validated.
7
+ const NAME_RE = /^[a-z0-9]+(-[a-z0-9]+)*$/;
8
+ export function lintSkill(skillDir) {
9
+ const label = path.basename(skillDir);
10
+ const issues = [];
11
+ const add = (severity, message) => issues.push({ skill: label, severity, message });
12
+ const skillFile = path.join(skillDir, 'SKILL.md');
13
+ if (!existsSync(skillFile)) {
14
+ add('error', 'SKILL.md is missing');
15
+ return issues;
16
+ }
17
+ const text = readFileSync(skillFile, 'utf8');
18
+ const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(text);
19
+ if (!match) {
20
+ add('error', 'SKILL.md has no YAML frontmatter');
21
+ return issues;
22
+ }
23
+ let front;
24
+ try {
25
+ front = (parse(match[1]) ?? {});
26
+ }
27
+ catch (e) {
28
+ add('error', `frontmatter is not valid YAML: ${e instanceof Error ? e.message : e}`);
29
+ return issues;
30
+ }
31
+ const name = front.name;
32
+ if (typeof name !== 'string' || !name) {
33
+ add('error', 'frontmatter.name is required');
34
+ }
35
+ else {
36
+ if (name !== label)
37
+ add('error', `frontmatter.name '${name}' must match the directory name '${label}'`);
38
+ if (name.length > 64)
39
+ add('error', 'frontmatter.name exceeds 64 characters');
40
+ if (!NAME_RE.test(name))
41
+ add('error', `frontmatter.name '${name}' must be lowercase kebab-case`);
42
+ }
43
+ const description = front.description;
44
+ if (typeof description !== 'string' || !description) {
45
+ add('error', 'frontmatter.description is required');
46
+ }
47
+ else if (description.length > 1024) {
48
+ add('error', 'frontmatter.description exceeds 1024 characters');
49
+ }
50
+ for (const key of Object.keys(front)) {
51
+ if (!['name', 'description', 'license', 'compatibility', 'metadata', 'allowed-tools'].includes(key)) {
52
+ add('warning', `non-standard frontmatter field '${key}' (ignored by strict harnesses)`);
53
+ }
54
+ }
55
+ const body = text.slice(match[0].length);
56
+ if (body.split('\n').length > 500) {
57
+ add('warning', 'SKILL.md body exceeds 500 lines; move detail into references/');
58
+ }
59
+ return issues;
60
+ }
61
+ export function lintSkills(skillDirs) {
62
+ return skillDirs.flatMap((dir) => {
63
+ if (!existsSync(dir) || !statSync(dir).isDirectory()) {
64
+ return [{ skill: path.basename(dir), severity: 'error', message: `skill directory not found: ${dir}` }];
65
+ }
66
+ return lintSkill(dir);
67
+ });
68
+ }
@@ -0,0 +1,164 @@
1
+ // Per-preset manifest requirements, checked on the RENDERED manifest of every
2
+ // build. A preset whose platform presents the bundle as a person encodes its
3
+ // market's listing rules here, so a bundle cannot silently ship a package the
4
+ // platform would reject: structural problems are errors, market-copy policy
5
+ // (word counts, image specs) is warnings. The reference-integrity check at the
6
+ // bottom is universal - it runs for every preset on the shipped tree.
7
+ import { existsSync, readFileSync, readdirSync } from 'node:fs';
8
+ import path from 'node:path';
9
+ import { isRecord } from './config.js';
10
+ // Listing fields are declared as {en, zh} pairs; a plain string renders, but
11
+ // the market listing wants both languages.
12
+ function localized(value, field, out) {
13
+ if (typeof value === 'string') {
14
+ if (value)
15
+ out.push({ severity: 'warning', message: `${field} should be an {en, zh} pair for the market listing` });
16
+ else
17
+ out.push({ severity: 'error', message: `${field} is empty` });
18
+ return;
19
+ }
20
+ const ok = isRecord(value)
21
+ && typeof value.en === 'string' && value.en
22
+ && typeof value.zh === 'string' && value.zh;
23
+ if (!ok)
24
+ out.push({ severity: 'error', message: `${field} must be an {en, zh} pair of non-empty strings` });
25
+ }
26
+ const hanzi = (s) => (s.match(/[一-鿿]/g) ?? []).length;
27
+ function pngSize(buf) {
28
+ if (buf.length < 24 || !buf.subarray(1, 4).equals(Buffer.from('PNG')))
29
+ return undefined;
30
+ return [buf.readUInt32BE(16), buf.readUInt32BE(20)];
31
+ }
32
+ function lintWorkbuddy(m, outDir, mcpRef) {
33
+ const out = [];
34
+ for (const field of ['displayName', 'profession', 'displayDescription']) {
35
+ localized(m[field], field, out);
36
+ }
37
+ const desc = m.displayDescription;
38
+ const zh = isRecord(desc) && typeof desc.zh === 'string' ? desc.zh : undefined;
39
+ if (zh) {
40
+ const n = hanzi(zh);
41
+ if (n < 40 || n > 50)
42
+ out.push({ severity: 'warning', message: `displayDescription.zh is ${n} hanzi - the market wants 40-50` });
43
+ }
44
+ if (typeof m.avatar !== 'string' || !m.avatar) {
45
+ out.push({ severity: 'error', message: 'avatar is required' });
46
+ }
47
+ else {
48
+ if (!/\.(png|jpe?g)$/i.test(m.avatar))
49
+ out.push({ severity: 'warning', message: `avatar ${m.avatar}: the market wants PNG or JPG` });
50
+ const file = path.join(outDir, m.avatar);
51
+ if (!existsSync(file))
52
+ out.push({ severity: 'error', message: `avatar file missing from the package: ${m.avatar}` });
53
+ else {
54
+ const bytes = readFileSync(file);
55
+ if (bytes.length > 500 * 1024)
56
+ out.push({ severity: 'warning', message: 'avatar exceeds the 500KB market limit' });
57
+ const dims = pngSize(bytes);
58
+ if (dims && (dims[0] !== 512 || dims[1] !== 512))
59
+ out.push({ severity: 'warning', message: `avatar is ${dims[0]}x${dims[1]} - the market wants 512x512` });
60
+ }
61
+ }
62
+ if (typeof m.categoryId !== 'string' || !m.categoryId)
63
+ out.push({ severity: 'error', message: 'categoryId is required' });
64
+ const listingOf3 = (value, field) => {
65
+ if (!Array.isArray(value) || value.length !== 3) {
66
+ out.push({ severity: 'error', message: `${field} must list exactly 3` });
67
+ return undefined;
68
+ }
69
+ value.forEach((item, i) => localized(item, `${field}[${i}]`, out));
70
+ return value;
71
+ };
72
+ const prompts = listingOf3(m.quickPrompts, 'quickPrompts');
73
+ listingOf3(m.tags, 'tags');
74
+ if (m.defaultInitPrompt === undefined)
75
+ out.push({ severity: 'error', message: 'defaultInitPrompt is required' });
76
+ else if (JSON.stringify(m.defaultInitPrompt) !== JSON.stringify(prompts?.[0])) {
77
+ out.push({ severity: 'error', message: 'defaultInitPrompt must equal quickPrompts[0]' });
78
+ }
79
+ const deps = m.dependencies;
80
+ if (m.plugin !== m.name)
81
+ out.push({ severity: 'error', message: 'plugin must equal name' });
82
+ if (isRecord(m.mcpServers)) {
83
+ out.push({ severity: 'warning', message: 'top-level mcpServers is undocumented for the market - declare MCP via dependencies.mcpServers pointing at ./.mcp.json' });
84
+ }
85
+ else if (mcpRef && (!isRecord(deps) || deps.mcpServers !== mcpRef)) {
86
+ out.push({ severity: 'error', message: `dependencies.mcpServers must be "${mcpRef}" - without the pointer the shipped MCP file is never loaded` });
87
+ }
88
+ if (m.expertType !== 'agent' && m.expertType !== 'team') {
89
+ out.push({ severity: 'error', message: 'expertType must be "agent" or "team"' });
90
+ }
91
+ else if (m.expertType === 'team' && !isRecord(m.teamInfo)) {
92
+ out.push({ severity: 'error', message: 'expertType team requires teamInfo' });
93
+ }
94
+ const stems = (Array.isArray(m.agents) ? m.agents : [])
95
+ .filter((a) => typeof a === 'string')
96
+ .map((a) => path.basename(a).replace(/\.md$/, ''));
97
+ if (typeof m.agentName !== 'string' || !stems.includes(m.agentName)) {
98
+ out.push({ severity: 'error', message: `agentName must match an agents/ file stem (${stems.join(', ') || 'none declared'})` });
99
+ }
100
+ const author = m.author;
101
+ if (!isRecord(author) || typeof author.email !== 'string' || !author.email) {
102
+ out.push({ severity: 'warning', message: 'author.email is missing - the market requires {name, email}' });
103
+ }
104
+ return out;
105
+ }
106
+ export function lintManifest(manifest, preset, outDir, mcpRef) {
107
+ if (preset === 'workbuddy')
108
+ return lintWorkbuddy(manifest, outDir, mcpRef);
109
+ return [];
110
+ }
111
+ // ─── package-tree lint: reference integrity ──────────────────────────────────
112
+ // A relative path with an extension, preceded by a non-path character so
113
+ // absolute (~/.x, /usr/bin/tar) and bare-filename mentions do not match.
114
+ const ASSET_REF = /(?:^|[\s`"'<>=(:;*[\],、。;:()【「】」])([A-Za-z0-9_][\w.@-]*(?:\/[\w.@-]+)+\.[A-Za-z0-9]{2,8})/g;
115
+ function* shippedDocs(outDir, preset) {
116
+ const agents = path.join(outDir, preset.agentsDir);
117
+ if (existsSync(agents)) {
118
+ for (const e of readdirSync(agents)) {
119
+ if (e.endsWith('.md'))
120
+ yield { file: path.join(agents, e), base: outDir };
121
+ }
122
+ }
123
+ const skills = path.join(outDir, preset.skillsDir);
124
+ if (!existsSync(skills))
125
+ return;
126
+ for (const skill of readdirSync(skills)) {
127
+ const md = path.join(skills, skill, 'SKILL.md');
128
+ if (existsSync(md))
129
+ yield { file: md, base: path.join(skills, skill) };
130
+ }
131
+ }
132
+ // The market rejects packages whose docs reference files they do not contain;
133
+ // check the shipped trees the same way on every build, for every preset.
134
+ // Directory-tree diagrams state the parent dir on its own line (`plugins/`)
135
+ // with `├──`-prefixed children after it; those children resolve against the
136
+ // last bare-dir line so tree entries are checked too, not skipped.
137
+ export function lintPackageTree(outDir, preset) {
138
+ const out = [];
139
+ for (const { file, base } of shippedDocs(outDir, preset)) {
140
+ const rel = path.relative(outDir, file);
141
+ const lines = readFileSync(file, 'utf8').split('\n');
142
+ let dirPrefix = '';
143
+ for (let i = 0; i < lines.length; i++) {
144
+ const trimmed = lines[i].trim();
145
+ if (/^[A-Za-z0-9_][\w.@-]*\/$/.test(trimmed)) {
146
+ dirPrefix = trimmed;
147
+ continue;
148
+ }
149
+ const inTree = /^[├└│─]/.test(trimmed);
150
+ if (!inTree)
151
+ dirPrefix = '';
152
+ const line = lines[i]
153
+ .replace(/https?:\/\/\S+/g, '') // URLs are not file references
154
+ .replace(/<[^<>]*>\//g, ''); // <skill-abs-path>/-style placeholders
155
+ for (const m of line.matchAll(ASSET_REF)) {
156
+ const target = path.resolve(base, inTree ? dirPrefix + m[1] : m[1]);
157
+ if (!existsSync(target)) {
158
+ out.push({ severity: 'error', message: `${rel}:${i + 1} references missing file: ${dirPrefix}${m[1]}` });
159
+ }
160
+ }
161
+ }
162
+ }
163
+ return out;
164
+ }
@@ -0,0 +1,224 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
4
+ import path from 'node:path';
5
+ import { loadConfig, resolveConfig, isRecord } from './config.js';
6
+ import { lintManifest, lintPackageTree } from './manifest-lint.js';
7
+ import { PRESETS } from './presets.js';
8
+ import { lintSkills } from './lint.js';
9
+ const PKG_VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
10
+ // ─── fs helpers ──────────────────────────────────────────────────────────────
11
+ function walk(dir, rel = '') {
12
+ const out = [];
13
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
14
+ const childRel = rel === '' ? e.name : `${rel}/${e.name}`;
15
+ const childAbs = path.join(dir, e.name);
16
+ if (e.isDirectory())
17
+ out.push(...walk(childAbs, childRel));
18
+ else if (e.isFile())
19
+ out.push({ rel: childRel, abs: childAbs });
20
+ }
21
+ return out;
22
+ }
23
+ const sha256 = (buf) => createHash('sha256').update(buf).digest('hex');
24
+ // Resolve every configured entry once; targets copy straight from these
25
+ // sources (release views are already the ship-only tree).
26
+ function resolveEntries(root, cfg) {
27
+ const entry = (category) => (rel) => {
28
+ const src = path.join(root, rel);
29
+ if (!existsSync(src))
30
+ throw new Error(`missing bundle entry: ${rel}`);
31
+ return { src, name: path.basename(rel), category };
32
+ };
33
+ return [
34
+ ...cfg.skills.map(entry('skills')),
35
+ ...(cfg.agents ?? []).map(entry('agents')),
36
+ ...(cfg.include ?? []).map(entry('include')),
37
+ ];
38
+ }
39
+ const lintDirs = (root, cfg) => (cfg.lint ?? cfg.skills).map((s) => path.join(root, s));
40
+ // Build steps belong to the repos that own the content; run them in the
41
+ // bundle root so relative paths in the commands (make -C skills/x ...) work.
42
+ // install-dev sets HARNESS_PACK_DEV=1: view scripts may then assemble from
43
+ // working trees instead of committed archives (what ships for a release
44
+ // never changes).
45
+ function runBuildSteps(root, steps, dev = false) {
46
+ const env = dev ? { ...process.env, HARNESS_PACK_DEV: '1' } : undefined;
47
+ for (const step of steps) {
48
+ // Inherit both streams: build output (including per-source warnings such
49
+ // as a skipped broken plugin) belongs in the caller's log as it happens.
50
+ const res = spawnSync(step, { shell: true, cwd: root, stdio: ['ignore', 'inherit', 'inherit'], env });
51
+ if (res.status !== 0) {
52
+ throw new Error(`build step failed (exit ${res.status ?? '?'}): ${step}`);
53
+ }
54
+ }
55
+ }
56
+ // ─── emit: per-target artifacts ──────────────────────────────────────────────
57
+ // {{root}} is the only token rendered inside MCP declarations: the bundle owns
58
+ // what to launch, the preset owns how this harness spells "the plugin root".
59
+ // Presentation keys move into the preset's metadata envelope when it has one,
60
+ // and are stripped otherwise - they are canonical, not protocol.
61
+ function renderMcpServers(servers, preset) {
62
+ const render = (value) => {
63
+ if (typeof value === 'string')
64
+ return value.replaceAll('{{root}}', preset.mcp.root);
65
+ if (Array.isArray(value))
66
+ return value.map(render);
67
+ if (value && typeof value === 'object') {
68
+ return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, render(child)]));
69
+ }
70
+ return value;
71
+ };
72
+ return Object.fromEntries(Object.entries(servers).map(([name, server]) => {
73
+ const { displayName, description, icon, auth, ...stdio } = server;
74
+ const def = { ...preset.mcp.serverDefaults, ...render(stdio) };
75
+ const meta = Object.fromEntries(Object.entries({ displayName, description, icon, auth }).filter(([, v]) => v !== undefined));
76
+ if (preset.mcp.metaKey && Object.keys(meta).length > 0)
77
+ def[preset.mcp.metaKey] = render(meta);
78
+ return [name, def];
79
+ }));
80
+ }
81
+ // Manifest tokens: {{name}}, {{version}} and dotted {{display.*}} paths into
82
+ // the resolved display layer, always wrapped in template quotes. A token that
83
+ // exactly fills a JSON string splices any JSON value (the quotes are
84
+ // consumed); a token embedded in longer text splices its raw contents and
85
+ // must resolve to a string. Unresolvable keys fail the build - persona output
86
+ // comes from declared keys only, never a silent fallback to `name`.
87
+ function renderManifest(root, templateRel, cfg, preset, display, mcp) {
88
+ const templatePath = path.join(root, templateRel);
89
+ if (!existsSync(templatePath))
90
+ throw new Error(`manifest template not found: ${templateRel}`);
91
+ const lookup = { name: cfg.name, version: cfg.version, display };
92
+ const token = (key) => {
93
+ let node = lookup;
94
+ for (const part of key.split('.')) {
95
+ if (!isRecord(node) || !(part in node)) {
96
+ throw new Error(`manifest template ${templateRel}: {{${key}}} does not resolve (declare it under display)`);
97
+ }
98
+ node = node[part];
99
+ }
100
+ return node;
101
+ };
102
+ const text = readFileSync(templatePath, 'utf8').replace(/"(?:[^"\\]|\\.)*"/g, (lit) => {
103
+ const sole = lit.match(/^"\{\{([\w.]+)\}\}"$/);
104
+ if (sole)
105
+ return JSON.stringify(token(sole[1]));
106
+ return lit.replace(/\{\{([\w.]+)\}\}/g, (_raw, key) => {
107
+ const value = token(key);
108
+ if (typeof value !== 'string') {
109
+ throw new Error(`manifest template ${templateRel}: {{${key}}} must resolve to a string when embedded in text`);
110
+ }
111
+ return JSON.stringify(value).slice(1, -1);
112
+ });
113
+ });
114
+ let manifest;
115
+ try {
116
+ manifest = JSON.parse(text);
117
+ }
118
+ catch (e) {
119
+ throw new Error(`manifest template ${templateRel} is not valid JSON after substitution: ${e instanceof Error ? e.message : e}`);
120
+ }
121
+ if (preset.mcp.mode === 'embed' && mcp)
122
+ manifest[preset.mcp.dest] = mcp;
123
+ return manifest;
124
+ }
125
+ function emitTarget(root, entries, key, target, distRoot, cfg) {
126
+ const preset = PRESETS[target.preset];
127
+ // Whole-key override, not a deep merge: platform media divergence (a PNG
128
+ // avatar where the market bans SVG) swaps the key wholesale.
129
+ const display = { ...cfg.display, ...target.display };
130
+ if (typeof display.avatar === 'string' && !existsSync(path.join(root, display.avatar))) {
131
+ throw new Error(`targets.${key}: display avatar not found in the bundle: ${display.avatar}`);
132
+ }
133
+ const outDir = path.resolve(distRoot, target.outDir ?? key);
134
+ if (!outDir.startsWith(path.resolve(distRoot) + path.sep))
135
+ throw new Error(`targets.${key}: outDir escapes dist`);
136
+ rmSync(outDir, { recursive: true, force: true });
137
+ mkdirSync(outDir, { recursive: true });
138
+ for (const entry of entries) {
139
+ const sub = entry.category === 'skills' ? preset.skillsDir : entry.category === 'agents' ? preset.agentsDir : '';
140
+ mkdirSync(path.join(outDir, sub), { recursive: true });
141
+ cpSync(entry.src, path.join(outDir, sub, entry.name), { recursive: true });
142
+ }
143
+ // Field merge: an override replaces only the fields it sets.
144
+ const servers = { ...cfg.mcp };
145
+ for (const [name, override] of Object.entries(target.mcp ?? {})) {
146
+ servers[name] = { ...servers[name], ...override };
147
+ }
148
+ const mcp = Object.keys(servers).length > 0 ? renderMcpServers(servers, preset) : undefined;
149
+ const manifest = renderManifest(root, target.manifest, cfg, preset, display, mcp);
150
+ const manifestDest = path.join(outDir, preset.manifestDest);
151
+ mkdirSync(path.dirname(manifestDest), { recursive: true });
152
+ writeFileSync(manifestDest, `${JSON.stringify(manifest, null, 2)}\n`);
153
+ if (mcp && preset.mcp.mode === 'file') {
154
+ const file = { ...(preset.mcp.schema ? { $schema: preset.mcp.schema } : {}), mcpServers: mcp };
155
+ writeFileSync(path.join(outDir, preset.mcp.dest), `${JSON.stringify(file, null, 2)}\n`);
156
+ }
157
+ const mcpRef = mcp && preset.mcp.mode === 'file' ? `./${preset.mcp.dest}` : undefined;
158
+ const issues = [...lintManifest(manifest, target.preset, outDir, mcpRef), ...lintPackageTree(outDir, preset)]
159
+ .map((i) => ({ skill: `targets.${key}`, ...i }));
160
+ return { outDir, issues };
161
+ }
162
+ // ─── release manifest + build orchestration ──────────────────────────────────
163
+ function hashTree(dir) {
164
+ const files = {};
165
+ for (const file of walk(dir)) {
166
+ const buf = readFileSync(file.abs);
167
+ files[file.rel] = { sha256: sha256(buf), bytes: buf.byteLength };
168
+ }
169
+ return files;
170
+ }
171
+ export function runBuild(opts) {
172
+ const root = path.resolve(path.dirname(opts.configPath));
173
+ const cfg = resolveConfig(loadConfig(opts.configPath), opts);
174
+ // Build first: what ships is the release views, so the spec check runs on
175
+ // the tree that will actually be assembled (or on `lint` sources when the
176
+ // config points there).
177
+ if (cfg.build)
178
+ runBuildSteps(root, cfg.build, opts.dev ?? false);
179
+ const errors = lintSkills(lintDirs(root, cfg)).filter((i) => i.severity === 'error');
180
+ if (errors.length > 0) {
181
+ throw new Error(`lint errors - fix them before building:\n${errors.map((i) => ` ${i.skill}: ${i.message}`).join('\n')}`);
182
+ }
183
+ const entries = resolveEntries(root, cfg);
184
+ const distRoot = path.resolve(root, opts.outDir ?? 'dist');
185
+ const manifestIssues = [];
186
+ const targets = Object.entries(cfg.targets).map(([key, target]) => {
187
+ const { outDir, issues } = emitTarget(root, entries, key, target, distRoot, cfg);
188
+ manifestIssues.push(...issues);
189
+ // Dev skips release hashing and the release manifest: install-dev never
190
+ // reads either and reruns on every edit-summon-verify cycle. The gates
191
+ // (skill lint + manifest lint) above are unaffected.
192
+ const files = opts.dev ? undefined : hashTree(outDir);
193
+ return { key, outDir, fileCount: files ? Object.keys(files).length : walk(outDir).length, preset: target.preset, files };
194
+ });
195
+ // Platform listing rules run on the rendered manifests; warnings surface on
196
+ // stderr, errors abort before release.json is written.
197
+ for (const issue of manifestIssues.filter((i) => i.severity === 'warning')) {
198
+ console.error(`[warn] ${issue.skill}: ${issue.message}`);
199
+ }
200
+ const manifestErrors = manifestIssues.filter((i) => i.severity === 'error');
201
+ if (manifestErrors.length > 0) {
202
+ throw new Error(`manifest errors - fix them before building:\n${manifestErrors.map((i) => ` ${i.skill}: ${i.message}`).join('\n')}`);
203
+ }
204
+ const releasePath = path.join(distRoot, 'release.json');
205
+ if (!opts.dev) {
206
+ const release = {
207
+ generator: `harness-pack/${PKG_VERSION}`,
208
+ name: cfg.name,
209
+ version: cfg.version,
210
+ generatedAt: new Date().toISOString(),
211
+ targets: Object.fromEntries(targets.map((t) => [t.key, { files: t.files }])),
212
+ };
213
+ writeFileSync(releasePath, `${JSON.stringify(release, null, 2)}\n`);
214
+ }
215
+ return {
216
+ version: cfg.version,
217
+ releasePath,
218
+ targets: targets.map(({ key, outDir, fileCount, preset }) => ({ key, outDir, fileCount, preset })),
219
+ };
220
+ }
221
+ export function runLint(configPath) {
222
+ const root = path.resolve(path.dirname(configPath));
223
+ return lintSkills(lintDirs(root, loadConfig(configPath)));
224
+ }
@@ -0,0 +1,48 @@
1
+ // Per-harness layout conventions. A preset answers four questions: where the
2
+ // manifest lands, where skills and agents go, how the MCP declaration is
3
+ // placed, and how a built artifact runs on this machine for development (the
4
+ // installers live in src/dev-install.ts, keyed by preset). Everything else
5
+ // about a target's content comes from the bundle's own templates and config.
6
+ export const PRESETS = {
7
+ // Claude Code plugin: manifest at .claude-plugin/plugin.json, MCP servers
8
+ // declared in a sibling-rooted .mcp.json (the plugin default location).
9
+ 'claude-code': {
10
+ manifestDest: '.claude-plugin/plugin.json',
11
+ skillsDir: 'skills',
12
+ agentsDir: 'agents',
13
+ mcp: { mode: 'file', dest: '.mcp.json', root: '${CLAUDE_PLUGIN_ROOT}' },
14
+ },
15
+ // Codex plugin (Agent Plugins 1.0 portable core): manifest at the root,
16
+ // MCP servers in mcp.json. Codex also reads Claude-format marketplaces, so
17
+ // this artifact doubles as a portable core for cross-posting.
18
+ //
19
+ // Codex does not expand ${PLUGIN_ROOT} in MCP configs; it resolves a
20
+ // relative cwd from the plugin root and defaults it to the plugin root.
21
+ // Relative args therefore resolve, and the spec's closed stdio variant
22
+ // needs an explicit type.
23
+ codex: {
24
+ manifestDest: 'plugin.json',
25
+ skillsDir: 'skills',
26
+ agentsDir: 'agents',
27
+ mcp: {
28
+ mode: 'file',
29
+ dest: 'mcp.json',
30
+ root: '.',
31
+ schema: 'https://agent-plugins.org/schemas/1.0.0/mcp.schema.json',
32
+ serverDefaults: { type: 'stdio', cwd: './' },
33
+ },
34
+ },
35
+ // CodeBuddy-family expert package (WorkBuddy): manifest inside
36
+ // .codebuddy-plugin/, MCP servers in a root .mcp.json referenced by the
37
+ // manifest's dependencies pointer - the open-platform documented form.
38
+ //
39
+ // Expert packages: the open-platform documented MCP form (manifest
40
+ // dependencies pointer + root .mcp.json) and x-workbuddy connector-card
41
+ // metadata. Mechanism notes: docs/design.md preset section.
42
+ workbuddy: {
43
+ manifestDest: '.codebuddy-plugin/plugin.json',
44
+ skillsDir: 'skills',
45
+ agentsDir: 'agents',
46
+ mcp: { mode: 'file', dest: '.mcp.json', root: '.', metaKey: 'x-workbuddy' },
47
+ },
48
+ };
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/docs/design.md ADDED
@@ -0,0 +1,212 @@
1
+ # harness-pack design
2
+
3
+ ## 1. Scope and non-goals
4
+
5
+ A builder with **no business logic**: it takes the skill release views, persona
6
+ files, and MCP wiring declared by a bundle repo, compiles them into per-harness
7
+ release artifacts, and records a sha256 for every artifact file.
8
+
9
+ What it does:
10
+
11
+ - run the content repo's own build commands (`build`);
12
+ - collect release views and lay them out per preset (envelope location,
13
+ `skills/` and `agents/` directories, MCP placement);
14
+ - stamp the version into each harness's manifest template;
15
+ - write the `dist/release.json` release manifest that downstream pins by
16
+ sha256.
17
+
18
+ What it does not do (boundaries):
19
+
20
+ - **Content shape**: which files ship, how sources become release artifacts,
21
+ and how doc references are rewritten — all owned by the content repo; this
22
+ tool offers no prune/rewrite primitives;
23
+ - **Install and distribution**: each harness's own mechanism (Claude
24
+ marketplace, Codex marketplace, custom updaters);
25
+ - **Business formats**: `build` only runs commands defined by the content repo;
26
+ this tool does not understand artifact formats;
27
+ - **Product field structure**: how fields are spelled and where they land come
28
+ entirely from the target manifest template and preset. Persona display
29
+ **values** are the exception: platforms present a bundle as a person
30
+ (humanized avatar, name, title), so those values are canonicalized in the
31
+ `display` layer (§4) — values belong to content, fields belong to the
32
+ harness.
33
+
34
+ ## 2. Layers and ownership
35
+
36
+ | Layer | Owner | Content |
37
+ |---|---|---|
38
+ | Content shape | Skill repo | `make pack` produces `release/<name>/`: pruning, packaging, reference rewriting |
39
+ | Composition and metadata | Bundle repo | Which skills to ship, target list, manifest templates, persona values (`display`), version |
40
+ | Harness mechanics | harness-pack | Preset layout, manifest placement, MCP wiring, `release.json`, dev deployment |
41
+
42
+ The test is "who owns this knowledge": a new plugin variant should only touch
43
+ that skill repo; a new target harness should only touch the packer's preset
44
+ data; changing the release composition should only touch the bundle's
45
+ `pack.yaml`.
46
+
47
+ Pushing envelope layout down into every bundle repo makes each repo copy three
48
+ layouts and let them drift — exactly why the industry has no reusable
49
+ multi-harness tool. Pulling content pruning up into the packer makes a skill
50
+ repo's release shape depend on external configuration, so adding a variant
51
+ means editing someone else's file. Neither is acceptable.
52
+
53
+ ## 3. Release view convention
54
+
55
+ A skill repo's `make pack` produces `release/<skill-name>/`:
56
+
57
+ - the directory name must equal the `name` in `SKILL.md` frontmatter (`lint`
58
+ checks this);
59
+ - only shipping files belong here — the typical approach is `git archive HEAD`
60
+ plus `.gitattributes` `export-ignore` pruning, with the build script doing
61
+ the packaging and reference rewriting;
62
+ - packaged artifacts (such as a signed and encrypted `.goblin`) are generated
63
+ inside the view; source files do not enter it;
64
+ - the view directory is gitignored by the skill repo and never versioned.
65
+
66
+ A bundle repo's `skills` points at these views; `build` generates them before
67
+ collection. `git archive` reads committed content, so a release view
68
+ corresponds to a commit/tag and is reproducible by construction.
69
+
70
+ ## 4. Configuration reference (pack.yaml)
71
+
72
+ | Key | Meaning |
73
+ |---|---|
74
+ | `name` / `version` | Package name; the version can be overridden with `--version` (CI injects a tag) |
75
+ | `skills[]` | Skill release views, copied to `<preset skills dir>/<basename>` |
76
+ | `lint[]` | Optional: source skill directories to validate; defaults to the `skills` views |
77
+ | `agents[]` | Persona files or directories, copied to `<preset agents dir>/<basename>` |
78
+ | `include[]` | Other root entries (files or directories) copied verbatim into every target root |
79
+ | `build[]` | Commands run in order in the bundle root; any non-zero exit fails the build. `install-dev` sets `HARNESS_PACK_DEV=1` so view scripts may assemble from working trees; releases never do |
80
+ | `mcp{}` | stdio servers shared by all targets; `{{root}}` in any server string is rendered by the preset into that harness's plugin-root reference; `displayName`/`description`/`icon`/`auth` are canonical connector-card metadata, rendered into the envelope if the preset has one (workbuddy → `x-workbuddy`) and stripped otherwise |
81
+ | `display{}` | Persona layer: persona platforms (which present the bundle as a person) render these keys via `{{display.*}}`; `name` is always the tool id (install directory, pin name, plugin/agentName) and is never a display fallback |
82
+ | `targets{}` | Target name → `{preset, manifest, mcp?, display?, outDir?}`; `mcp` merges field-by-field over the bundle-level server of the same name; `display` overrides the persona layer **whole-key** (platform media differences, such as a market that only accepts PNG avatars: the key swaps files, it is not a deep merge) |
83
+
84
+ **Manifest templates**: `{{name}}`/`{{version}}`/`{{display.*}}` (dotted
85
+ paths) are substituted first, then the result is parsed as JSON; a parse
86
+ failure fails the build. Tokens always sit inside template quotes: when a
87
+ token fills an entire string it splices any JSON value (the quotes are
88
+ consumed); embedded in longer text it must resolve to a string; an undeclared
89
+ key fails the build — persona output comes only from display keys and never
90
+ silently falls back to `name`. Harness structural fields (categoryId,
91
+ expertType, `$schema`, etc.) still live entirely in the template.
92
+
93
+ **Manifest lint**: preset platform-listing rules are encoded in
94
+ `src/manifest-lint.ts` and run against the **rendered** manifest on every
95
+ build, so listing requirements are written once and content repos do not copy
96
+ platform docs: structural problems (missing display fields, `plugin != name`,
97
+ `defaultInitPrompt` not equal to `quickPrompts[0]`, tags/quickPrompts counts,
98
+ agentName not matching an `agents/` filename, missing avatar file) are errors
99
+ that block the build and prevent `release.json` from being written; market-copy
100
+ policy (Chinese copy 40-50 characters, avatar PNG/JPG 512×512 ≤500KB,
101
+ `author.email`) is a warning printed to stderr. **Reference integrity**
102
+ (`lintPackageTree`) is the one universal rule: for every preset's shipped tree
103
+ it checks relative path references in `SKILL.md` and agent docs (including
104
+ parent-directory resolution in directory-tree diagrams); a missing reference is
105
+ an error that blocks the build — a build-time equivalent of the market review's
106
+ "missing bundled file" category.
107
+
108
+ **Build order**: build → lint (validate `lint` sources or release views) →
109
+ collect → apply envelope → release.json. Build runs first because the shipping
110
+ target is the release view, and spec validation should target the tree that
111
+ actually ships; `make lint` (which only runs the lint command) needs no build
112
+ toolchain when `lint` points at source directories.
113
+
114
+ **Dev deployment** (`install-dev`): a preset answers a fourth harness
115
+ question — how a freshly built artifact runs on this machine. Copy-based
116
+ harnesses (WorkBuddy's `my-experts` marketplace: replace the plugin dir, upsert
117
+ the marketplace entry, drop the app's plugin cache) get a real deploy; in-place
118
+ loaders (Claude Code `--plugin-dir`) get the load command; cache-copy loaders
119
+ without in-place loading (Codex) get their documented loop. The dev package is
120
+ built through the same pipeline and gates as a release — the only difference
121
+ is `HARNESS_PACK_DEV=1` on the build steps, which lets content repos switch
122
+ their view sourcing to working trees. Dev copies coexist with an installed
123
+ market package of the same name (separate marketplaces, per-session summon
124
+ decides); deleting the dev copy falls back to the market.
125
+
126
+ ## 5. Presets
127
+
128
+ | preset | manifest | skills | agents | MCP |
129
+ |---|---|---|---|---|
130
+ | `workbuddy` | `.codebuddy-plugin/plugin.json` | `skills/` | `agents/` | root `.mcp.json` (`{{root}}` = `.`), with the manifest pointing at it via `dependencies.mcpServers: "./.mcp.json"` — the open-platform documented form; the expert dependency service reads services in the order dependencies → top-level `mcpServers` → root file, and resolves `./` args against the declaring file's directory (the plugin root) |
131
+ | `claude-code` | `.claude-plugin/plugin.json` | `skills/` | `agents/` | `.mcp.json` (`{mcpServers: ...}`, `{{root}}` = `${CLAUDE_PLUGIN_ROOT}`) |
132
+ | `codex` | `plugin.json` (root, Agent Plugins 1.0 portable core) | `skills/` | `agents/` | `mcp.json` (`$schema` + `{mcpServers: ...}`, `{{root}}` = `.`) |
133
+
134
+ - The `codex` artifact can also serve as a cross-harness portable core: Codex
135
+ also reads Claude-format marketplaces. Codex does not expand
136
+ `${PLUGIN_ROOT}` in MCP configs, so the preset adds `type: stdio` to every
137
+ server and defaults `cwd` to `"./"` — Codex resolves a relative `cwd`
138
+ against the plugin root, so relative launch scripts work.
139
+ - **MCP `{{root}}`**: the bundle writes the launch command once; the preset
140
+ renders it into each harness's plugin-root syntax. Claude Code expands
141
+ `${CLAUDE_PLUGIN_ROOT}`; WorkBuddy's **expert** dependency service resolves
142
+ `./`-prefixed args against the install directory; Codex uses a relative
143
+ `cwd`. `${CODEBUDDY_PLUGIN_ROOT}` belongs to the app's built-in plugin
144
+ loader, not the expert publishing channel.
145
+ - Target names are decoupled from presets: the same preset can be declared
146
+ multiple times (for example two variants with different manifest templates
147
+ and `outDir`s).
148
+
149
+ ## 6. Release manifest contract
150
+
151
+ `dist/release.json`:
152
+
153
+ ```json
154
+ {
155
+ "generator": "harness-pack/0.2.0",
156
+ "name": "my-bundle",
157
+ "version": "1.2.3",
158
+ "generatedAt": "2026-11-23T00:00:00.000Z",
159
+ "targets": {
160
+ "workbuddy": { "files": { "skills/x/SKILL.md": { "sha256": "...", "bytes": 1234 } } }
161
+ }
162
+ }
163
+ ```
164
+
165
+ Consumers (updaters, CI, distribution scripts) pin by "version + per-file
166
+ sha256" as the sole authority; the artifact directory itself can be reproduced
167
+ from a build of the same version at any time.
168
+
169
+ ## 7. Typical wiring
170
+
171
+ A business repo (such as `goblin-helper`) in a tag pipeline:
172
+
173
+ ```
174
+ git submodule update --init
175
+ npx @cohirer/harness-pack@0.2.0 build --config pack.yaml --version "$CI_COMMIT_TAG"
176
+ # collects the release views produced by the bundle's build steps → applies envelopes
177
+ # → dist/workbuddy/, dist/claude-code/, dist/codex/, dist/release.json
178
+ ```
179
+
180
+ The distribution repo stores only a small pin file (version plus the sha256 of
181
+ the distribution artifact itself — on the WorkBuddy side, the market-upload
182
+ zip; `release.json`'s per-file hashes verify artifact contents). On each
183
+ session sync it downloads, verifies, and unpacks the artifact, then hands it to
184
+ the existing assembly steps. Assembly steps only know the artifact directory
185
+ layout and are decoupled from the packer.
186
+
187
+ ## 8. Compatibility and evolution
188
+
189
+ - Node >= 20, ESM, TypeScript; the only runtime dependency is `yaml`.
190
+ - Presets are **data** (`src/presets.ts`): adding a harness means one preset
191
+ entry plus a template plus a dev installer in `src/dev-install.ts`, with no
192
+ pipeline changes.
193
+ - Not built yet, add on demand: zip/tar artifact packaging (currently emits
194
+ directories; compression is left to CI), `marketplace.json` generation,
195
+ official schema validation and `claude plugin validate` integration, and
196
+ resolving sources directly from a git remote (currently reads the local tree
197
+ only).
198
+
199
+ ## 9. Decision record
200
+
201
+ | Decision | Rationale |
202
+ |---|---|
203
+ | Node/TypeScript over Python | Target repos and the consumption chain (Node updaters, npm distribution, CI) are all in the Node ecosystem |
204
+ | MIT | Open source; no commercial licensing goal |
205
+ | No prune/rewrite; content shape belongs to the content repo | Pruning and reference rewriting are content-repo knowledge; pulling them into a generic tool would make a skill repo's release shape depend on external configuration |
206
+ | Keep envelope/manifest placement/release.json | Harness layout is cross-repo shared mechanics that no single bundle repo can reimplement without degrading into per-repo adapters |
207
+ | Manifests from templates, not code generation | Harness fields differ widely and evolve quickly; templates make new fields zero-code |
208
+ | Canonicalize persona values in the `display` layer, keep field structure in templates | Platforms like WorkBuddy present experts as people rather than tools; values belong to the content repo and are declared once for reuse across harnesses; platform differences (PNG vs SVG avatars) use whole-key target overrides, and output never comes from the tool id |
209
+ | Per-preset manifest lint in the build | Platform listing rules should be written once and apply to the actually rendered manifest; the warning/error split separates "broken package" from "market will not accept it" |
210
+ | Canonicalize MCP connector-card metadata; presets render it into their envelopes | Connector-card copy (name, description, icon, auth) is content, while `x-workbuddy` is platform-specific; bundles do not write harness-private keys, the same division as `{{root}}` |
211
+ | Build is a command list | Packaging knowledge (variants, naming, keys, formats) belongs to the content repo; the generic tool only runs commands |
212
+ | Build before lint | The shipping target is the release view; when `lint` points at source directories there is a fast path that needs no build toolchain |
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "@cohirer/harness-pack",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Pack one agent bundle (skills + agents + MCP wiring) into per-harness release artifacts: Claude Code plugin, Codex plugin, CodeBuddy-family expert package, and friends.",
5
+ "homepage": "https://github.com/cohirer/harness-pack#readme",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/cohirer/harness-pack.git"
9
+ },
10
+ "type": "module",
11
+ "license": "MIT",
12
+ "publishConfig": {
13
+ "registry": "https://registry.npmjs.org/"
14
+ },
15
+ "packageManager": "pnpm@11.17.0",
16
+ "bin": {
17
+ "harness-pack": "dist/cli.js"
18
+ },
19
+ "main": "dist/pipeline.js",
20
+ "files": [
21
+ "dist",
22
+ "docs",
23
+ "README.md",
24
+ "LICENSE"
25
+ ],
26
+ "engines": {
27
+ "node": ">=20"
28
+ },
29
+ "scripts": {
30
+ "build": "tsc -p tsconfig.json",
31
+ "test": "vitest run",
32
+ "typecheck": "tsc --noEmit",
33
+ "prepack": "npm run build",
34
+ "prepublishOnly": "npm run typecheck && npm test"
35
+ },
36
+ "keywords": [
37
+ "agent-skills",
38
+ "claude-code",
39
+ "codex",
40
+ "mcp",
41
+ "plugin",
42
+ "packer"
43
+ ],
44
+ "dependencies": {
45
+ "yaml": "^2.6.0"
46
+ },
47
+ "devDependencies": {
48
+ "@types/node": "^26.6.6",
49
+ "typescript": "^5.6.0",
50
+ "vitest": "^3.0.0"
51
+ }
52
+ }