@harnesspm/cli 0.0.1 → 0.18.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.
Files changed (83) hide show
  1. package/CHANGELOG.md +275 -0
  2. package/LICENSE +1 -1
  3. package/README.md +71 -3
  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 +230 -0
  10. package/dist/commands.d.ts +68 -0
  11. package/dist/commands.js +1441 -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 +77 -0
  19. package/dist/exec-outputs.js +426 -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/start.d.ts +18 -0
  49. package/dist/start.js +136 -0
  50. package/dist/telemetry-api.d.ts +26 -0
  51. package/dist/telemetry-api.js +60 -0
  52. package/dist/telemetry.d.ts +119 -0
  53. package/dist/telemetry.js +401 -0
  54. package/dist/user-outputs.d.ts +30 -0
  55. package/dist/user-outputs.js +239 -0
  56. package/dist/util.d.ts +137 -0
  57. package/dist/util.js +370 -0
  58. package/dist/workspaces.d.ts +2 -0
  59. package/dist/workspaces.js +62 -0
  60. package/docs/spec/01-overview.md +156 -0
  61. package/docs/spec/02-package-format.md +252 -0
  62. package/docs/spec/03-resolution.md +108 -0
  63. package/docs/spec/04-outputs.md +194 -0
  64. package/docs/spec/05-executables.md +170 -0
  65. package/docs/spec/06-trust.md +88 -0
  66. package/docs/spec/07-added.md +109 -0
  67. package/docs/spec/08-improving.md +79 -0
  68. package/docs/spec/09-cloud.md +68 -0
  69. package/docs/spec/10-cli.md +215 -0
  70. package/docs/spec/11-standards.md +52 -0
  71. package/docs/spec/12-dogfooding.md +51 -0
  72. package/docs/spec/13-open-questions.md +97 -0
  73. package/docs/spec/14-telemetry.md +199 -0
  74. package/docs/spec/README.md +33 -0
  75. package/harness/dev.harnesspm/rules/generated-files.md +9 -0
  76. package/harness/dev.harnesspm/rules/harnesspm-config.md +12 -0
  77. package/harness/plugin.json +13 -0
  78. package/harness/skills/harnesspm-export/SKILL.md +43 -0
  79. package/harness/skills/harnesspm-import/SKILL.md +32 -0
  80. package/harness/skills/harnesspm-improve/SKILL.md +38 -0
  81. package/package.json +66 -11
  82. package/schema/harnesspm.schema.json +58 -0
  83. package/index.js +0 -4
@@ -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,230 @@
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: npx -y @harnesspm/cli [-C <dir>] [<command>]
23
+ harnesspm where to start: the tasks for this folder, or this project's report
24
+ -C <dir> act on the project in <dir>, such as a repository you cloned. \`run\` keeps
25
+ the current folder for the script, so file arguments stay valid
26
+ harnesspm help the project's packages, one line each; outside a project, these commands
27
+ harnesspm help <package | rule ID | tool>
28
+ a package's rules, docs, tools, MCP servers, skills and hooks in full,
29
+ one rule, or a tool's usage and run command. Needs no install
30
+
31
+ Projects
32
+ harnesspm init set up harnesspm in this project: install it, write its files and sync
33
+ harnesspm sync [--check | --write]
34
+ write the agent files (--check: compare only, for CI;
35
+ --write: committed files too when CI=true)
36
+ harnesspm status the project's report: packages, checks, and what waits for a person
37
+ harnesspm doctor the same report, which exits 1 when a check fails
38
+ harnesspm why <ID> where a unit comes from and how to change it
39
+ harnesspm run <plugin>:<script> [-- args]
40
+ run a script of a trusted package
41
+ harnesspm approve [<package>] a person's step: write what an agent could not grant, and approve
42
+ a "pin" package's new version
43
+ harnesspm fetch download the harness packages in the lock, for jobs without an install
44
+
45
+ Harnesses on top of the repository's (your team's, your own)
46
+ harnesspm add <source> [--local] [--no-hook]
47
+ add a harness: github:<owner>/<repo>, git:<url>, npm:<name> or a folder
48
+ harnesspm remove <source> [--local]
49
+ harnesspm update fetch new versions of added harnesses
50
+
51
+ Authors
52
+ harnesspm check [<folder>] validate a harness before publishing
53
+ harnesspm new <kind> <name> [--to <plugin>] [--entry]
54
+ a rule, skill, agent, script, hook or mcp from a template
55
+ harnesspm new patch <rule ID> [--to <plugin>] [--entry]
56
+ a patch that changes some sections of a rule
57
+ `;
58
+ /** Details for a command whose usage line is not enough. */
59
+ const DETAILS = {
60
+ new: `Kinds: rule, skill, agent, script, hook, mcp. \`new patch\` takes a rule ID, such as acme-ui:rules/usage.
61
+ --to <plugin> write into a harness you added (\`npx -y @harnesspm/cli status\` lists them), not the project's own harness/
62
+ --entry with --to: write into that harness's entry for this repository`,
63
+ };
64
+ /** Help for one command: its lines in HELP and its details. Undefined for a word that is not a command. */
65
+ function commandHelp(command) {
66
+ const picked = [];
67
+ let inside = false;
68
+ for (const line of HELP.split('\n')) {
69
+ if (line === ` harnesspm ${command}` || line.startsWith(` harnesspm ${command} `)) {
70
+ inside = true;
71
+ picked.push(line);
72
+ }
73
+ else if (inside && /^ {3,}\S/.test(line))
74
+ picked.push(line);
75
+ else
76
+ inside = false;
77
+ }
78
+ if (picked.length === 0)
79
+ return undefined;
80
+ const details = DETAILS[command];
81
+ return [...picked, ...(details !== undefined ? ['', details] : []), '', 'Every command: npx -y @harnesspm/cli --help. Every option: https://harnesspm.tenphi.me/reference/cli/'].join('\n');
82
+ }
83
+ const out = {
84
+ log: (line) => console.log(line),
85
+ warn: (line) => console.error(line),
86
+ };
87
+ /**
88
+ * `-C <dir>` before the command: harnesspm acts as if it started in <dir>, as `git -C` does (spec 10.1). Returns the
89
+ * folder and the arguments after it.
90
+ */
91
+ function projectFolder(argv) {
92
+ if (argv[0] !== '-C')
93
+ return { cwd: process.cwd(), named: false, argv };
94
+ const dir = argv[1];
95
+ if (dir === undefined || dir === '')
96
+ throw new HarnessError('Usage: harnesspm -C <dir> <command>');
97
+ const cwd = path.resolve(dir);
98
+ if (!isDir(cwd))
99
+ throw new HarnessError(`-C ${dir}: no such folder`);
100
+ return { cwd, named: true, argv: argv.slice(2) };
101
+ }
102
+ function dispatch(argvIn, { add, approve, check, doctor, fetch, init, mcp, newUnit, notAProject, projectHelp, remove, run, start, status, sync, targetHelp, update, why }) {
103
+ const { cwd, named, argv } = projectFolder(argvIn);
104
+ const [command, ...rest] = argv;
105
+ const isHelp = (arg) => arg === '--help' || arg === '-h';
106
+ // After `run <plugin>:<script>`, every argument goes to the script, `--help` too. Only a first `--help` is harnesspm's.
107
+ if (command !== undefined && (command === 'run' || command === 'mcp' ? isHelp(rest[0]) : rest.some(isHelp))) {
108
+ console.log(commandHelp(command) ?? HELP);
109
+ return 0;
110
+ }
111
+ if (command === 'run' || command === 'mcp') {
112
+ // Everything after the script name goes to the script, untouched.
113
+ let agent;
114
+ let i = 0;
115
+ if (rest[0] === '--agent') {
116
+ agent = rest[1];
117
+ i = 2;
118
+ }
119
+ const ref = rest[i];
120
+ if (ref === undefined)
121
+ throw new HarnessError(`Usage: harnesspm ${command} [--agent <claude|codex>] <plugin>:<name>${command === 'run' ? ' [-- args]' : ''}`);
122
+ const args = rest.slice(i + 1);
123
+ if (args[0] === '--')
124
+ args.shift();
125
+ return command === 'run' ? run(cwd, ref, args, agent) : mcp(cwd, ref, agent);
126
+ }
127
+ const flags = new Set(rest.filter((a) => a.startsWith('--')));
128
+ const args = rest.filter((a) => !a.startsWith('--'));
129
+ const unknown = (allowed) => {
130
+ for (const flag of flags)
131
+ if (!allowed.includes(flag))
132
+ throw new HarnessError(`Unknown option ${flag} for ${command}`);
133
+ };
134
+ switch (command) {
135
+ case 'init':
136
+ unknown([]);
137
+ return init(cwd, out);
138
+ case 'sync':
139
+ unknown(['--check', '--write']);
140
+ return sync(cwd, out, { check: flags.has('--check'), write: flags.has('--write') });
141
+ case 'status':
142
+ unknown([]);
143
+ return status(cwd, out);
144
+ case 'doctor':
145
+ unknown([]);
146
+ return doctor(cwd, out);
147
+ case 'why':
148
+ unknown([]);
149
+ if (args[0] === undefined)
150
+ throw new HarnessError('Usage: harnesspm why <ID>');
151
+ return why(cwd, args[0], out);
152
+ case 'add':
153
+ case 'remove': {
154
+ unknown(command === 'add' ? ['--local', '--no-hook'] : ['--local']);
155
+ if (args[0] === undefined)
156
+ throw new HarnessError(`Usage: harnesspm ${command} <source>${command === 'add' ? ' [--local] [--no-hook]' : ' [--local]'}`);
157
+ if (command === 'add')
158
+ return add(cwd, args[0], out, { local: flags.has('--local'), hook: !flags.has('--no-hook') });
159
+ return remove(cwd, args[0], out, { local: flags.has('--local') });
160
+ }
161
+ case 'update':
162
+ unknown([]);
163
+ return update(cwd, out);
164
+ case 'new': {
165
+ const flagArgs = rest.filter((a, i) => a === '--to' || rest[i - 1] === '--to' || a === '--entry');
166
+ const positional = rest.filter((a) => !flagArgs.includes(a) && !a.startsWith('--'));
167
+ const toIndex = rest.indexOf('--to');
168
+ const to = toIndex >= 0 ? rest[toIndex + 1] : undefined;
169
+ for (const a of rest)
170
+ if (a.startsWith('--') && a !== '--to' && a !== '--entry')
171
+ throw new HarnessError(`Unknown option ${a} for new`);
172
+ if (positional.length !== 2)
173
+ throw new HarnessError('Usage: harnesspm new <kind> <name> [--to <plugin>] [--entry], or harnesspm new patch <rule ID>');
174
+ return newUnit(cwd, positional[0], positional[1], { ...(to !== undefined ? { to } : {}), entry: rest.includes('--entry') }, out);
175
+ }
176
+ case 'fetch':
177
+ unknown([]);
178
+ return fetch(cwd, out);
179
+ case 'approve':
180
+ unknown([]);
181
+ return approve(cwd, args[0], out);
182
+ case 'check':
183
+ unknown([]);
184
+ return check(args[0] ?? cwd, out);
185
+ case '--version':
186
+ case '-v': {
187
+ const pkg = readJson(new URL('../package.json', import.meta.url).pathname);
188
+ console.log(pkg.version);
189
+ return 0;
190
+ }
191
+ case undefined:
192
+ // Every task starts here: the project's report, or the tasks for this folder (spec 10.1).
193
+ return start(cwd, out);
194
+ case '--help':
195
+ case '-h':
196
+ console.log(HELP.trimEnd());
197
+ return 0;
198
+ case 'help': {
199
+ if (args[0] !== undefined) {
200
+ // A command first, then a package, rule or tool of the project (spec 10.1).
201
+ const text = commandHelp(args[0]);
202
+ if (text !== undefined) {
203
+ console.log(text);
204
+ return 0;
205
+ }
206
+ return targetHelp(cwd, args[0], out);
207
+ }
208
+ // Inside a project, or with -C, the project's packages lead. Elsewhere, the commands.
209
+ const code = projectHelp(cwd, out);
210
+ if (code !== undefined)
211
+ return code;
212
+ console.log(HELP.trimEnd());
213
+ if (named)
214
+ console.log(`\n${notAProject(cwd)}`);
215
+ return 0;
216
+ }
217
+ default:
218
+ throw new HarnessError(`Unknown command "${command}". Every command: \`npx -y @harnesspm/cli --help\`.`);
219
+ }
220
+ }
221
+ // Agent hooks call `harnesspm track` on every matching tool call, so it loads only what it needs (spec 14.4). A hook in a
222
+ // folder above the project names the project with `-C <dir>` (spec 4.10).
223
+ const tracked = process.argv[2] === 'track' ? 3 : process.argv[2] === '-C' && process.argv[4] === 'track' ? 5 : 0;
224
+ if (tracked > 0) {
225
+ const { track } = await import('./telemetry.js');
226
+ process.exitCode = track(process.argv.slice(tracked), tracked === 5 ? path.resolve(process.argv[3]) : undefined);
227
+ }
228
+ else {
229
+ await main();
230
+ }
@@ -0,0 +1,68 @@
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
+ /**
17
+ * `harnesspm init` (spec 10.1): installs harnesspm when the project does not list it, writes the configuration, the
18
+ * install hook, the import in CLAUDE.md and the `.gitignore` line, syncs, and reports what waits for a person and what
19
+ * to commit.
20
+ */
21
+ export declare function init(projectDir: string, out: Output): number;
22
+ export declare function add(cwd: string, spec: string, out: Output, options?: {
23
+ local?: boolean;
24
+ hook?: boolean;
25
+ }): number;
26
+ export declare function remove(cwd: string, spec: string, out: Output, options?: {
27
+ local?: boolean;
28
+ }): number;
29
+ /**
30
+ * Fetches the added harnesses, then syncs. The `SessionStart` hook runs it (spec 7.5), so a source that cannot be
31
+ * fetched never fails it: harnesspm warns and syncs what is on this machine. Without a person at a terminal, git never
32
+ * prompts and a slow fetch is stopped.
33
+ */
34
+ export declare function update(cwd: string, out: Output): number;
35
+ /** `harnesspm status`: the project's report (spec 10.5). It always exits 0. */
36
+ export declare function status(cwd: string, out: Output): number;
37
+ /** `harnesspm doctor`: the same report, which exits 1 when a check fails; what waits for a person does not fail. */
38
+ export declare function doctor(cwd: string, out: Output): number;
39
+ /**
40
+ * The bare command (spec 10.1): in a project that uses harnesspm, its report; elsewhere, what the folder is and the
41
+ * tasks for it, each with the one command that starts it.
42
+ */
43
+ export declare function start(cwd: string, out: Output): number;
44
+ export declare function why(cwd: string, id: string, out: Output): number;
45
+ /** The command that runs the project's tools from where harnesspm started: with `-C` from outside it (spec 10.1). */
46
+ export declare function toolCommand(projectDir: string): string;
47
+ export declare function run(cwd: string, ref: string, args: string[], agent: string | undefined): Promise<number>;
48
+ export declare function mcp(cwd: string, ref: string, agent: string | undefined): number;
49
+ /**
50
+ * `help` in a project (spec 10.1): one line per package, across workspaces, with what it covers and the
51
+ * `help <package>` command that prints the rest. Undefined outside a project that uses harnesspm.
52
+ */
53
+ export declare function projectHelp(cwd: string, out: Output): number | undefined;
54
+ /** Where `help` says that a folder named with `-C` does not use harnesspm. */
55
+ export declare function notAProject(cwd: string): string;
56
+ /**
57
+ * `help <target>`: a package or plugin, a rule ID, or a tool by `<plugin>:<script>` or its ID (spec 10.1). It works
58
+ * without an install, like `help`, and sends a `help` event (spec 14.2).
59
+ */
60
+ export declare function targetHelp(cwd: string, target: string, out: Output): number;
61
+ /** Approves new versions of "pin" packages and writes what a model run left pending (spec 6.2). */
62
+ export declare function approve(cwd: string, name: string | undefined, out: Output): number;
63
+ export declare function newUnit(cwd: string, kind: string, name: string, options: {
64
+ to?: string;
65
+ entry?: boolean;
66
+ }, out: Output): number;
67
+ export declare function fetch(cwd: string, out: Output): number;
68
+ export declare function check(target: string, out: Output): number;