@harnesspm/cli 0.0.0-snapshot.412a718

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.
Files changed (80) hide show
  1. package/CHANGELOG.md +259 -0
  2. package/LICENSE +21 -0
  3. package/README.md +70 -0
  4. package/dist/added.d.ts +51 -0
  5. package/dist/added.js +192 -0
  6. package/dist/check.d.ts +14 -0
  7. package/dist/check.js +263 -0
  8. package/dist/cli.d.ts +2 -0
  9. package/dist/cli.js +218 -0
  10. package/dist/commands.d.ts +58 -0
  11. package/dist/commands.js +1299 -0
  12. package/dist/config.d.ts +15 -0
  13. package/dist/config.js +45 -0
  14. package/dist/deliver.d.ts +1 -0
  15. package/dist/deliver.js +31 -0
  16. package/dist/doctor.d.ts +18 -0
  17. package/dist/doctor.js +99 -0
  18. package/dist/exec-outputs.d.ts +75 -0
  19. package/dist/exec-outputs.js +425 -0
  20. package/dist/exec-units.d.ts +68 -0
  21. package/dist/exec-units.js +151 -0
  22. package/dist/fetch.d.ts +16 -0
  23. package/dist/fetch.js +145 -0
  24. package/dist/frontmatter.d.ts +16 -0
  25. package/dist/frontmatter.js +49 -0
  26. package/dist/homes.d.ts +7 -0
  27. package/dist/homes.js +21 -0
  28. package/dist/lock.d.ts +47 -0
  29. package/dist/lock.js +245 -0
  30. package/dist/manifest.d.ts +78 -0
  31. package/dist/manifest.js +169 -0
  32. package/dist/new.d.ts +33 -0
  33. package/dist/new.js +228 -0
  34. package/dist/outputs.d.ts +124 -0
  35. package/dist/outputs.js +875 -0
  36. package/dist/parent.d.ts +41 -0
  37. package/dist/parent.js +182 -0
  38. package/dist/render.d.ts +91 -0
  39. package/dist/render.js +221 -0
  40. package/dist/resolve.d.ts +132 -0
  41. package/dist/resolve.js +522 -0
  42. package/dist/reviewed.d.ts +15 -0
  43. package/dist/reviewed.js +41 -0
  44. package/dist/run.d.ts +18 -0
  45. package/dist/run.js +133 -0
  46. package/dist/sections.d.ts +32 -0
  47. package/dist/sections.js +121 -0
  48. package/dist/telemetry-api.d.ts +26 -0
  49. package/dist/telemetry-api.js +60 -0
  50. package/dist/telemetry.d.ts +119 -0
  51. package/dist/telemetry.js +401 -0
  52. package/dist/user-outputs.d.ts +30 -0
  53. package/dist/user-outputs.js +239 -0
  54. package/dist/util.d.ts +137 -0
  55. package/dist/util.js +370 -0
  56. package/dist/workspaces.d.ts +2 -0
  57. package/dist/workspaces.js +62 -0
  58. package/docs/spec/01-overview.md +149 -0
  59. package/docs/spec/02-package-format.md +252 -0
  60. package/docs/spec/03-resolution.md +108 -0
  61. package/docs/spec/04-outputs.md +194 -0
  62. package/docs/spec/05-executables.md +170 -0
  63. package/docs/spec/06-trust.md +88 -0
  64. package/docs/spec/07-added.md +109 -0
  65. package/docs/spec/08-improving.md +79 -0
  66. package/docs/spec/09-cloud.md +68 -0
  67. package/docs/spec/10-cli.md +181 -0
  68. package/docs/spec/11-standards.md +52 -0
  69. package/docs/spec/12-dogfooding.md +51 -0
  70. package/docs/spec/13-open-questions.md +97 -0
  71. package/docs/spec/14-telemetry.md +199 -0
  72. package/docs/spec/README.md +33 -0
  73. package/harness/dev.harnesspm/rules/generated-files.md +9 -0
  74. package/harness/dev.harnesspm/rules/harnesspm-config.md +12 -0
  75. package/harness/plugin.json +13 -0
  76. package/harness/skills/harnesspm-export/SKILL.md +43 -0
  77. package/harness/skills/harnesspm-import/SKILL.md +40 -0
  78. package/harness/skills/harnesspm-improve/SKILL.md +38 -0
  79. package/package.json +73 -0
  80. package/schema/harnesspm.schema.json +58 -0
@@ -0,0 +1,14 @@
1
+ export interface CheckResult {
2
+ errors: string[];
3
+ warnings: string[];
4
+ alwaysOnBytes: number;
5
+ plugin: string;
6
+ /** Each project entry folder once, with the remotes that map to it and its always-on size (spec 2.10). */
7
+ entries: {
8
+ dir: string;
9
+ remotes: string[];
10
+ alwaysOnBytes: number;
11
+ }[];
12
+ }
13
+ /** `target` is a package root, or a harness/ folder, or an added harness folder. */
14
+ export declare function checkHarness(target: string): CheckResult;
package/dist/check.js ADDED
@@ -0,0 +1,263 @@
1
+ // harnesspm check: validate a harness before it is published (spec 2.10).
2
+ import * as fs from 'node:fs';
3
+ import * as path from 'node:path';
4
+ import { parseFrontmatter, stringList } from './frontmatter.js';
5
+ import { entryFolders, entryPackage } from './added.js';
6
+ import { discoverExecUnits } from './exec-units.js';
7
+ import { discoverUnits, loadHarnessPackage, NS, ruleMeta } from './manifest.js';
8
+ import { gitKeeps, HarnessError, isDir, isFile, isInside, isRecord, readJsonIfExists, readText, relativeLinks, relPosix } from './util.js';
9
+ const SECRET_PATTERNS = [
10
+ // A key has a body: a header alone is an example or a placeholder. Encrypted PEM puts `Name: value` lines first.
11
+ [/-----BEGIN [A-Z ]*PRIVATE KEY-----\s*(?:[\w-]+: [^\n]*\n\s*)*[A-Za-z0-9+/=]{40,}/, 'a private key'],
12
+ [/\bgh[pousr]_[A-Za-z0-9]{30,}\b/, 'a GitHub token'],
13
+ [/\bsk-[A-Za-z0-9_-]{20,}\b/, 'an API key'],
14
+ [/\bAKIA[0-9A-Z]{16}\b/, 'an AWS access key'],
15
+ [/\bxox[abprs]-[A-Za-z0-9-]{10,}\b/, 'a Slack token'],
16
+ ];
17
+ function walkFiles(dir) {
18
+ const files = [];
19
+ const walk = (current) => {
20
+ for (const entry of fs.readdirSync(current, { withFileTypes: true })) {
21
+ const full = path.join(current, entry.name);
22
+ if (entry.isDirectory())
23
+ walk(full);
24
+ else if (entry.isFile())
25
+ files.push(full);
26
+ }
27
+ };
28
+ if (isDir(dir))
29
+ walk(dir);
30
+ return files.sort();
31
+ }
32
+ /** A docs folder's files without the ones git ignores, as the lock and the index count them (spec 2.7). */
33
+ function docsFiles(dir) {
34
+ const keeps = gitKeeps(dir);
35
+ return walkFiles(dir).filter((file) => keeps(relPosix(dir, file)));
36
+ }
37
+ /** A `files` pattern as a test of a path relative to the package root: the path itself, or a folder above it. */
38
+ function filesPattern(pattern) {
39
+ const clean = pattern.replace(/^\.?\//, '').replace(/\/+$/, '');
40
+ if (clean === '' || /[[\]{}()+@]/.test(clean))
41
+ return undefined;
42
+ const source = clean
43
+ .split('**')
44
+ .map((part) => part.replace(/[.^$|\\]/g, '\\$&').replace(/\*/g, '[^/]*').replace(/\?/g, '[^/]'))
45
+ .join('.*')
46
+ .replace(/\.\*\//g, '(?:.*/)?');
47
+ const re = new RegExp(`^${source}(?:/.*)?$`);
48
+ return (rel) => re.test(rel);
49
+ }
50
+ /**
51
+ * Whether npm packs a path, read from `files` in package.json as npm reads it (spec 2.10): a listed path, a folder
52
+ * and what is in it, or a glob, less `!` entries, plus the files npm always packs. npm packs by `files`, not by
53
+ * `.gitignore`, so docs built at `prepack` ship. `undefined` without `files`, or with a pattern this doesn't read,
54
+ * such as braces: then `check` asks git, as the index does. It never runs npm, whose `pack --dry-run` runs the
55
+ * package's `prepare` even with `--ignore-scripts`.
56
+ */
57
+ function packs(root) {
58
+ const pkg = readJsonIfExists(path.join(root, 'package.json'));
59
+ if (!isRecord(pkg) || !Array.isArray(pkg['files']))
60
+ return undefined;
61
+ const include = [];
62
+ const exclude = [];
63
+ for (const entry of pkg['files']) {
64
+ if (typeof entry !== 'string')
65
+ return undefined;
66
+ const test = filesPattern(entry.replace(/^!/, ''));
67
+ if (!test)
68
+ return undefined;
69
+ (entry.startsWith('!') ? exclude : include).push(test);
70
+ }
71
+ const named = [pkg['main'], ...(typeof pkg['bin'] === 'string' ? [pkg['bin']] : isRecord(pkg['bin']) ? Object.values(pkg['bin']) : [])]
72
+ .filter((file) => typeof file === 'string')
73
+ .map((file) => file.replace(/^\.\//, ''));
74
+ const always = (rel) => /^(package\.json|(readme|licen[cs]e)(\..*)?)$/i.test(rel) || named.includes(rel);
75
+ return (rel) => always(rel) || (include.some((test) => test(rel)) && !exclude.some((test) => test(rel)));
76
+ }
77
+ /** A skill's `name` is its folder's name. A replacement takes the name of the skill it replaces, as agents see it there. */
78
+ function checkSkill(dir, name, why, errors, show) {
79
+ const file = path.join(dir, 'SKILL.md');
80
+ try {
81
+ const { data, hasFrontmatter } = parseFrontmatter(readText(file), file);
82
+ if (!hasFrontmatter)
83
+ errors.push(`${show(file)}: needs frontmatter with "name" and "description"`);
84
+ if (data['name'] !== name)
85
+ errors.push(`${show(file)}: "name" must be "${name}", ${why}`);
86
+ if (typeof data['description'] !== 'string' || data['description'].trim() === '')
87
+ errors.push(`${show(file)}: needs a "description"`);
88
+ }
89
+ catch (error) {
90
+ errors.push(error.message);
91
+ }
92
+ }
93
+ /** Checks the rules and skills of a harness or of one of its project entries. Returns them and the always-on size. */
94
+ function checkUnits(pkg, errors, warnings, show) {
95
+ const overrideFiles = new Set([...Object.values(pkg.ext.replace), ...Object.values(pkg.ext.patch)].map((f) => path.resolve(pkg.harnessDir, f)));
96
+ const units = discoverUnits(pkg, overrideFiles);
97
+ let alwaysOnBytes = 0;
98
+ for (const rule of units.rules) {
99
+ try {
100
+ const text = readText(rule.file);
101
+ const meta = ruleMeta(text, rule.name, rule.file);
102
+ const { data } = parseFrontmatter(text, rule.file);
103
+ if (data['paths'] !== undefined && !stringList(data['paths']))
104
+ errors.push(`${show(rule.file)}: "paths" must be a string or a list of strings`);
105
+ if (data['description'] !== undefined && typeof data['description'] !== 'string')
106
+ errors.push(`${show(rule.file)}: "description" must be a string`);
107
+ if (meta.activation === 'always')
108
+ alwaysOnBytes += Buffer.byteLength(meta.body);
109
+ }
110
+ catch (error) {
111
+ errors.push(error.message);
112
+ }
113
+ }
114
+ for (const skill of units.skills) {
115
+ checkSkill(skill.dir, skill.name, 'the folder name', errors, show);
116
+ if (!skill.name.startsWith(`${pkg.plugin}-`) && skill.name !== pkg.plugin) {
117
+ warnings.push(`skill "${skill.name}" should start with the plugin name, such as "${pkg.plugin}-${skill.name}"`);
118
+ }
119
+ }
120
+ return { units, alwaysOnBytes };
121
+ }
122
+ /** `target` is a package root, or a harness/ folder, or an added harness folder. */
123
+ export function checkHarness(target) {
124
+ let root = path.resolve(target);
125
+ if (path.basename(root) === 'harness' && isFile(path.join(root, 'plugin.json')))
126
+ root = path.dirname(root);
127
+ const pkg = loadHarnessPackage(root, 'project');
128
+ if (!pkg)
129
+ throw new HarnessError(`No harness found: ${relPosix(process.cwd(), path.join(root, 'harness', 'plugin.json'))} does not exist`);
130
+ const errors = [...pkg.problems];
131
+ const warnings = [];
132
+ const show = (file) => relPosix(root, file);
133
+ const pkgJson = readJsonIfExists(path.join(root, 'package.json'));
134
+ if (isRecord(pkgJson) && Array.isArray(pkgJson['files'])) {
135
+ const files = pkgJson['files'].filter((f) => typeof f === 'string').map((f) => f.replace(/^\.\//, '').replace(/\/$/, ''));
136
+ if (!files.includes('harness'))
137
+ errors.push('package.json: "files" must include "harness"');
138
+ if (pkg.ext.docs !== undefined) {
139
+ const docsRel = relPosix(root, path.resolve(pkg.harnessDir, pkg.ext.docs));
140
+ // The folder itself, a parent of it, or entries inside it, such as `docs/components` or `docs/*.md`.
141
+ const covers = (f) => docsRel === f || docsRel.startsWith(`${f}/`) || f.startsWith(`${docsRel}/`);
142
+ if (!files.some(covers))
143
+ errors.push(`package.json: "files" must include the docs folder "${docsRel}", or entries inside it`);
144
+ }
145
+ }
146
+ const checkPath = (label, rel, mustExist) => {
147
+ const full = path.resolve(pkg.harnessDir, rel);
148
+ if (!isInside(root, full))
149
+ errors.push(`${label}: ${rel} points outside the package`);
150
+ else if (mustExist === 'file' ? !isFile(full) : !isDir(full))
151
+ errors.push(`${label}: ${rel} does not exist`);
152
+ };
153
+ // A replacement has the shape of the unit it replaces: a rule's file, or a skill's folder (spec 3.4).
154
+ const replacedSkills = [];
155
+ for (const [id, file] of Object.entries(pkg.ext.replace)) {
156
+ const skill = /:skills\/(.+)$/.exec(id)?.[1];
157
+ if (skill !== undefined) {
158
+ checkPath(`replace ${id}`, file, 'dir');
159
+ const dir = path.resolve(pkg.harnessDir, file);
160
+ if (isDir(dir) && isInside(root, dir))
161
+ replacedSkills.push({ dir, name: skill });
162
+ }
163
+ else {
164
+ checkPath(`replace ${id}`, file, 'file');
165
+ if (!id.includes(':rules/'))
166
+ errors.push(`replace ${id}: replace works on rules and skills only. Exclude the unit and add one of your own instead.`);
167
+ }
168
+ }
169
+ for (const [id, file] of Object.entries(pkg.ext.patch)) {
170
+ checkPath(`patch ${id}`, file, 'file');
171
+ if (!id.includes(':rules/'))
172
+ errors.push(`patch ${id}: patches work on rules only`);
173
+ }
174
+ if (pkg.ext.docs !== undefined)
175
+ checkPath('docs', pkg.ext.docs, 'dir');
176
+ for (const [name, def] of Object.entries(pkg.ext.scripts)) {
177
+ if (!def.file.startsWith('./'))
178
+ errors.push(`script ${name}: "file" must start with "./"`);
179
+ checkPath(`script ${name}`, def.file, 'file');
180
+ }
181
+ for (const [remote, dir] of Object.entries(pkg.ext.projects))
182
+ checkPath(`project entry ${remote}`, dir, 'dir');
183
+ const { units, alwaysOnBytes } = checkUnits(pkg, errors, warnings, show);
184
+ for (const skill of replacedSkills) {
185
+ if (isFile(path.join(skill.dir, 'SKILL.md')))
186
+ checkSkill(skill.dir, skill.name, 'the name of the skill it replaces', errors, show);
187
+ else
188
+ errors.push(`replace: ${show(skill.dir)} needs a SKILL.md`);
189
+ }
190
+ // Project entries, each folder once, though several remotes may map to it. `sync` loads an entry as this does.
191
+ const entries = [];
192
+ for (const { dir, remotes } of entryFolders(pkg)) {
193
+ if (!isInside(root, dir) || !isDir(dir))
194
+ continue;
195
+ try {
196
+ const entry = entryPackage(pkg, dir, remotes[0]);
197
+ for (const problem of entry.problems)
198
+ errors.push(`${show(path.join(dir, 'plugin.json'))}: ${problem}`);
199
+ entries.push({ dir: show(dir), remotes, alwaysOnBytes: checkUnits(entry, errors, warnings, show).alwaysOnBytes });
200
+ }
201
+ catch (error) {
202
+ errors.push(error.message);
203
+ }
204
+ }
205
+ // Judge the docs and links by what ships (spec 2.10). Without `files` to read, by the files git keeps.
206
+ const packed = packs(root);
207
+ const ships = (file) => (packed === undefined ? fs.existsSync(file) : packed(relPosix(root, file)));
208
+ // Docs pages in a generated index (spec 2.7): the index takes their title and description from the frontmatter.
209
+ const docs = units.docs ? (packed === undefined ? docsFiles(units.docs.dir) : walkFiles(units.docs.dir).filter(ships)) : [];
210
+ if (units.docs && !(isFile(path.join(units.docs.dir, 'llms.txt')) && ships(path.join(units.docs.dir, 'llms.txt')))) {
211
+ for (const file of docs) {
212
+ if (!/\.mdx?$/.test(file))
213
+ continue;
214
+ try {
215
+ parseFrontmatter(readText(file), show(file));
216
+ }
217
+ catch (error) {
218
+ errors.push(error.message);
219
+ }
220
+ }
221
+ }
222
+ let jsonOk = true;
223
+ for (const json of ['mcp.json', path.join(NS, 'hooks.json'), path.join(NS, 'permissions.json')]) {
224
+ const file = path.join(pkg.harnessDir, json);
225
+ if (isFile(file)) {
226
+ try {
227
+ JSON.parse(readText(file));
228
+ }
229
+ catch (error) {
230
+ jsonOk = false;
231
+ errors.push(`${show(file)}: ${error.message}`);
232
+ }
233
+ }
234
+ }
235
+ if (jsonOk) {
236
+ try {
237
+ discoverExecUnits(pkg, errors);
238
+ }
239
+ catch (error) {
240
+ errors.push(error.message);
241
+ }
242
+ }
243
+ // Links in Markdown and secrets in any file.
244
+ const scanned = [...walkFiles(pkg.harnessDir), ...docs];
245
+ for (const file of [...new Set(scanned)]) {
246
+ const text = fs.readFileSync(file, 'utf8');
247
+ for (const [pattern, what] of SECRET_PATTERNS)
248
+ if (pattern.test(text))
249
+ warnings.push(`${show(file)} looks like it contains ${what}`);
250
+ if (!/\.mdx?$/.test(file))
251
+ continue;
252
+ for (const { link } of relativeLinks(text)) {
253
+ const target = path.resolve(path.dirname(file), decodeURI(link));
254
+ if (!isInside(root, target))
255
+ errors.push(`${show(file)}: the link ${link} points outside the package`);
256
+ else if (!fs.existsSync(target))
257
+ errors.push(`${show(file)}: the link ${link} points at a missing file`);
258
+ else if (isFile(target) && !ships(target))
259
+ errors.push(`${show(file)}: the link ${link} points at a file the package does not ship`);
260
+ }
261
+ }
262
+ return { errors, warnings, alwaysOnBytes, plugin: pkg.plugin, entries };
263
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,218 @@
1
+ #!/usr/bin/env node
2
+ import * as path from 'node:path';
3
+ import { HarnessError, isDir, readJson } from './util.js';
4
+ async function main() {
5
+ const commands = await import('./commands.js');
6
+ const { Refused } = await import('./run.js');
7
+ try {
8
+ process.exitCode = await dispatch(process.argv.slice(2), commands);
9
+ }
10
+ catch (error) {
11
+ if (error instanceof HarnessError) {
12
+ console.error(`harnesspm: ${error.message}`);
13
+ process.exitCode = error instanceof Refused ? 2 : 1;
14
+ }
15
+ else {
16
+ throw error;
17
+ }
18
+ }
19
+ }
20
+ const HELP = `harnesspm — the harness package manager
21
+
22
+ Usage: harnesspm [-C <dir>] <command>
23
+ -C <dir> act on the project in <dir>, such as a repository you cloned. \`run\` keeps
24
+ the current folder for the script, so file arguments stay valid
25
+ harnesspm help these commands, and the project's packages, one line each
26
+ harnesspm help <package | rule ID | tool>
27
+ a package's rules, docs, tools, MCP servers, skills and hooks in full,
28
+ one rule, or a tool's usage and run command. Needs no install
29
+
30
+ Projects
31
+ harnesspm init set up harnesspm in this project
32
+ harnesspm sync [--check | --write]
33
+ write the agent files (--check: compare only, for CI;
34
+ --write: committed files too when CI=true)
35
+ harnesspm status layers, packages and always-on size
36
+ harnesspm doctor check that local files stay out of git and the outputs are in place
37
+ harnesspm why <ID> where a unit comes from and how to change it
38
+ harnesspm run <plugin>:<script> [-- args]
39
+ run a script of a trusted package
40
+ harnesspm approve [<package>] approve a "pin" package's new version, and write what an agent could not
41
+ harnesspm fetch download the harness packages in the lock, for jobs without an install
42
+
43
+ Harnesses on top of the repository's (your team's, your own)
44
+ harnesspm add <source> [--local] [--no-hook]
45
+ add a harness: github:<owner>/<repo>, git:<url>, npm:<name> or a folder
46
+ harnesspm remove <source> [--local]
47
+ harnesspm update fetch new versions of added harnesses
48
+
49
+ Authors
50
+ harnesspm check [<folder>] validate a harness before publishing
51
+ harnesspm new <kind> <name> [--to <plugin>] [--entry]
52
+ a rule, skill, agent, script, hook or mcp from a template
53
+ harnesspm new patch <rule ID> [--to <plugin>] [--entry]
54
+ a patch that changes some sections of a rule
55
+ `;
56
+ /** Details for a command whose usage line is not enough. */
57
+ const DETAILS = {
58
+ new: `Kinds: rule, skill, agent, script, hook, mcp. \`new patch\` takes a rule ID, such as acme-ui:rules/usage.
59
+ --to <plugin> write into a harness you added (\`harnesspm status\` lists them), not the project's own harness/
60
+ --entry with --to: write into that harness's entry for this repository`,
61
+ };
62
+ /** Help for one command: its lines in HELP and its details. Undefined for a word that is not a command. */
63
+ function commandHelp(command) {
64
+ const picked = [];
65
+ let inside = false;
66
+ for (const line of HELP.split('\n')) {
67
+ if (line === ` harnesspm ${command}` || line.startsWith(` harnesspm ${command} `)) {
68
+ inside = true;
69
+ picked.push(line);
70
+ }
71
+ else if (inside && /^ {3,}\S/.test(line))
72
+ picked.push(line);
73
+ else
74
+ inside = false;
75
+ }
76
+ if (picked.length === 0)
77
+ return undefined;
78
+ const details = DETAILS[command];
79
+ return [...picked, ...(details !== undefined ? ['', details] : []), '', 'Every command: harnesspm help. Every option: https://harnesspm.tenphi.me/reference/cli/'].join('\n');
80
+ }
81
+ const out = {
82
+ log: (line) => console.log(line),
83
+ warn: (line) => console.error(line),
84
+ };
85
+ /**
86
+ * `-C <dir>` before the command: harnesspm acts as if it started in <dir>, as `git -C` does (spec 10.1). Returns the
87
+ * folder and the arguments after it.
88
+ */
89
+ function projectFolder(argv) {
90
+ if (argv[0] !== '-C')
91
+ return { cwd: process.cwd(), named: false, argv };
92
+ const dir = argv[1];
93
+ if (dir === undefined || dir === '')
94
+ throw new HarnessError('Usage: harnesspm -C <dir> <command>');
95
+ const cwd = path.resolve(dir);
96
+ if (!isDir(cwd))
97
+ throw new HarnessError(`-C ${dir}: no such folder`);
98
+ return { cwd, named: true, argv: argv.slice(2) };
99
+ }
100
+ function dispatch(argvIn, { add, approve, check, doctor, fetch, init, mcp, newUnit, projectHelp, remove, run, status, sync, targetHelp, update, why }) {
101
+ const { cwd, named, argv } = projectFolder(argvIn);
102
+ const [command, ...rest] = argv;
103
+ const isHelp = (arg) => arg === '--help' || arg === '-h';
104
+ // After `run <plugin>:<script>`, every argument goes to the script, `--help` too. Only a first `--help` is harnesspm's.
105
+ if (command !== undefined && (command === 'run' || command === 'mcp' ? isHelp(rest[0]) : rest.some(isHelp))) {
106
+ console.log(commandHelp(command) ?? HELP);
107
+ return 0;
108
+ }
109
+ if (command === 'run' || command === 'mcp') {
110
+ // Everything after the script name goes to the script, untouched.
111
+ let agent;
112
+ let i = 0;
113
+ if (rest[0] === '--agent') {
114
+ agent = rest[1];
115
+ i = 2;
116
+ }
117
+ const ref = rest[i];
118
+ if (ref === undefined)
119
+ throw new HarnessError(`Usage: harnesspm ${command} [--agent <claude|codex>] <plugin>:<name>${command === 'run' ? ' [-- args]' : ''}`);
120
+ const args = rest.slice(i + 1);
121
+ if (args[0] === '--')
122
+ args.shift();
123
+ return command === 'run' ? run(cwd, ref, args, agent) : mcp(cwd, ref, agent);
124
+ }
125
+ const flags = new Set(rest.filter((a) => a.startsWith('--')));
126
+ const args = rest.filter((a) => !a.startsWith('--'));
127
+ const unknown = (allowed) => {
128
+ for (const flag of flags)
129
+ if (!allowed.includes(flag))
130
+ throw new HarnessError(`Unknown option ${flag} for ${command}`);
131
+ };
132
+ switch (command) {
133
+ case 'init':
134
+ unknown([]);
135
+ return init(cwd, out);
136
+ case 'sync':
137
+ unknown(['--check', '--write']);
138
+ return sync(cwd, out, { check: flags.has('--check'), write: flags.has('--write') });
139
+ case 'status':
140
+ unknown([]);
141
+ return status(cwd, out);
142
+ case 'doctor':
143
+ unknown([]);
144
+ return doctor(cwd, out);
145
+ case 'why':
146
+ unknown([]);
147
+ if (args[0] === undefined)
148
+ throw new HarnessError('Usage: harnesspm why <ID>');
149
+ return why(cwd, args[0], out);
150
+ case 'add':
151
+ case 'remove': {
152
+ unknown(command === 'add' ? ['--local', '--no-hook'] : ['--local']);
153
+ if (args[0] === undefined)
154
+ throw new HarnessError(`Usage: harnesspm ${command} <source>${command === 'add' ? ' [--local] [--no-hook]' : ' [--local]'}`);
155
+ if (command === 'add')
156
+ return add(cwd, args[0], out, { local: flags.has('--local'), hook: !flags.has('--no-hook') });
157
+ return remove(cwd, args[0], out, { local: flags.has('--local') });
158
+ }
159
+ case 'update':
160
+ unknown([]);
161
+ return update(cwd, out);
162
+ case 'new': {
163
+ const flagArgs = rest.filter((a, i) => a === '--to' || rest[i - 1] === '--to' || a === '--entry');
164
+ const positional = rest.filter((a) => !flagArgs.includes(a) && !a.startsWith('--'));
165
+ const toIndex = rest.indexOf('--to');
166
+ const to = toIndex >= 0 ? rest[toIndex + 1] : undefined;
167
+ for (const a of rest)
168
+ if (a.startsWith('--') && a !== '--to' && a !== '--entry')
169
+ throw new HarnessError(`Unknown option ${a} for new`);
170
+ if (positional.length !== 2)
171
+ throw new HarnessError('Usage: harnesspm new <kind> <name> [--to <plugin>] [--entry], or harnesspm new patch <rule ID>');
172
+ return newUnit(cwd, positional[0], positional[1], { ...(to !== undefined ? { to } : {}), entry: rest.includes('--entry') }, out);
173
+ }
174
+ case 'fetch':
175
+ unknown([]);
176
+ return fetch(cwd, out);
177
+ case 'approve':
178
+ unknown([]);
179
+ return approve(cwd, args[0], out);
180
+ case 'check':
181
+ unknown([]);
182
+ return check(args[0] ?? cwd, out);
183
+ case '--version':
184
+ case '-v': {
185
+ const pkg = readJson(new URL('../package.json', import.meta.url).pathname);
186
+ console.log(pkg.version);
187
+ return 0;
188
+ }
189
+ case 'help':
190
+ case undefined:
191
+ case '--help':
192
+ case '-h':
193
+ if (command === 'help' && args[0] !== undefined) {
194
+ // A command first, then a package, rule or tool of the project (spec 10.1).
195
+ const text = commandHelp(args[0]);
196
+ if (text !== undefined) {
197
+ console.log(text);
198
+ return 0;
199
+ }
200
+ return targetHelp(cwd, args[0], out);
201
+ }
202
+ console.log(HELP.trimEnd());
203
+ // Inside a project, or with -C, the project's own harness follows.
204
+ return projectHelp(cwd, out, named);
205
+ default:
206
+ throw new HarnessError(`Unknown command "${command}". Run \`harnesspm help\`.`);
207
+ }
208
+ }
209
+ // Agent hooks call `harnesspm track` on every matching tool call, so it loads only what it needs (spec 14.4). A hook in a
210
+ // folder above the project names the project with `-C <dir>` (spec 4.10).
211
+ const tracked = process.argv[2] === 'track' ? 3 : process.argv[2] === '-C' && process.argv[4] === 'track' ? 5 : 0;
212
+ if (tracked > 0) {
213
+ const { track } = await import('./telemetry.js');
214
+ process.exitCode = track(process.argv.slice(tracked), tracked === 5 ? path.resolve(process.argv[3]) : undefined);
215
+ }
216
+ else {
217
+ await main();
218
+ }
@@ -0,0 +1,58 @@
1
+ export interface Output {
2
+ log(line: string): void;
3
+ warn(line: string): void;
4
+ }
5
+ /** The repository to work on: the nearest folder with harnesspm.json, else the git root, else `cwd`. */
6
+ export declare function findProjectDir(cwd: string): string;
7
+ /**
8
+ * `check` compares and writes nothing. With `CI=true`, the committed outputs stay as they are unless `write` is set,
9
+ * so that an install's sync cannot hide a missed sync from a later `sync --check` (spec 6.4, 10.1).
10
+ */
11
+ export declare function sync(cwd: string, out: Output, options?: {
12
+ check?: boolean;
13
+ write?: boolean;
14
+ quiet?: boolean;
15
+ }): number;
16
+ export declare function init(projectDir: string, out: Output): number;
17
+ export declare function add(cwd: string, spec: string, out: Output, options?: {
18
+ local?: boolean;
19
+ hook?: boolean;
20
+ }): number;
21
+ export declare function remove(cwd: string, spec: string, out: Output, options?: {
22
+ local?: boolean;
23
+ }): number;
24
+ /**
25
+ * Fetches the added harnesses, then syncs. The `SessionStart` hook runs it (spec 7.5), so a source that cannot be
26
+ * fetched never fails it: harnesspm warns and syncs what is on this machine. Without a person at a terminal, git never
27
+ * prompts and a slow fetch is stopped.
28
+ */
29
+ export declare function update(cwd: string, out: Output): number;
30
+ export declare function status(cwd: string, out: Output): number;
31
+ /**
32
+ * `harnesspm doctor`: whether this repository is ready for harnesses, its own and a person's (spec 10.1).
33
+ * It changes nothing. Exits 1 when a check fails; warnings do not fail.
34
+ */
35
+ export declare function doctor(cwd: string, out: Output): number;
36
+ export declare function why(cwd: string, id: string, out: Output): number;
37
+ /** The command that runs the project's tools from where harnesspm started: with `-C` from outside it (spec 10.1). */
38
+ export declare function toolCommand(projectDir: string): string;
39
+ export declare function run(cwd: string, ref: string, args: string[], agent: string | undefined): Promise<number>;
40
+ export declare function mcp(cwd: string, ref: string, agent: string | undefined): number;
41
+ /**
42
+ * The project's part of `help` (spec 10.1): one line per package, across workspaces, with what it covers and the
43
+ * `help <package>` command that prints the rest.
44
+ */
45
+ export declare function projectHelp(cwd: string, out: Output, named: boolean): number;
46
+ /**
47
+ * `help <target>`: a package or plugin, a rule ID, or a tool by `<plugin>:<script>` or its ID (spec 10.1). It works
48
+ * without an install, like `help`, and sends a `help` event (spec 14.2).
49
+ */
50
+ export declare function targetHelp(cwd: string, target: string, out: Output): number;
51
+ /** Approves new versions of "pin" packages and writes what a model run left pending (spec 6.2). */
52
+ export declare function approve(cwd: string, name: string | undefined, out: Output): number;
53
+ export declare function newUnit(cwd: string, kind: string, name: string, options: {
54
+ to?: string;
55
+ entry?: boolean;
56
+ }, out: Output): number;
57
+ export declare function fetch(cwd: string, out: Output): number;
58
+ export declare function check(target: string, out: Output): number;