@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
package/dist/run.js ADDED
@@ -0,0 +1,133 @@
1
+ // harnesspm run and harnesspm mcp (spec 5.1, 5.3).
2
+ import { spawn, spawnSync } from 'node:child_process';
3
+ import * as path from 'node:path';
4
+ import { harnesspmHome } from './added.js';
5
+ import { trustOf } from './exec-outputs.js';
6
+ import { readLock } from './lock.js';
7
+ import { commandCaller, outsideField, readIndex, readTelemetryState, runOutcome, sendEvent } from './telemetry.js';
8
+ import { HarnessError, NPX_ANY, agentOf, ensureDir, isFile } from './util.js';
9
+ /** Thrown when the runner refuses a script. The CLI exits with code 2 (spec 10.4). */
10
+ export class Refused extends HarnessError {
11
+ }
12
+ function parseRef(ref) {
13
+ const index = ref.indexOf(':');
14
+ if (index <= 0 || index === ref.length - 1)
15
+ throw new HarnessError(`Use <plugin>:<name>, not "${ref}"`);
16
+ return { plugin: ref.slice(0, index), name: ref.slice(index + 1) };
17
+ }
18
+ /** Checks trust and the installed version (spec 5.1, step 2). */
19
+ function checkPackage(pkg, res, what) {
20
+ const lock = readLock(res.projectDir);
21
+ const trust = trustOf(pkg, res, lock);
22
+ if (!trust.trusted)
23
+ throw new Refused(`${what} of ${pkg.name} is refused: ${trust.reason}. ${trust.action}`);
24
+ if (pkg.layer === 'dependencies') {
25
+ const locked = lock?.packages[pkg.name]?.version;
26
+ // Either side can be stale. A cached environment's install can be older than the lock, and a sync there would
27
+ // write the lock down to it, so the refusal names both remedies (spec 5.1).
28
+ if (locked !== pkg.version) {
29
+ throw new Refused(`${what} is refused: ${pkg.name} ${pkg.version} is installed, but the lock has ${locked ?? 'no entry'}: reinstall the project's dependencies when the install is out of date, or run \`${NPX_ANY} sync\` when the lock is.`);
30
+ }
31
+ }
32
+ }
33
+ function environment(pkg, res, agent) {
34
+ const data = path.join(harnesspmHome(), 'data', pkg.plugin);
35
+ ensureDir(data);
36
+ return {
37
+ ...process.env,
38
+ PLUGIN_ROOT: pkg.harnessDir,
39
+ PLUGIN_DATA: data,
40
+ HARNESSPM_PROJECT_DIR: res.projectDir,
41
+ HARNESSPM_AGENT: agent ?? agentOf() ?? '',
42
+ };
43
+ }
44
+ /** A `run` or `mcp` event for a unit of the dependency or project layer (spec 14.2). Units of added harnesses stay private. */
45
+ function unitEvent(res, type, unit, agent, extra = {}) {
46
+ if (unit.pkg.layer === 'added')
47
+ return;
48
+ // The index that `sync` writes has the remote, so the event does not ask git.
49
+ const repository = readIndex(res.projectDir)?.repository;
50
+ const ctx = { projectDir: res.projectDir, project: res.projectName, ...(repository !== undefined ? { repository } : {}), workspaces: res.workspaces.map((ws) => ws.key) };
51
+ sendEvent(readTelemetryState(res.projectDir), ctx, { type, ...commandCaller(agent), unit: unit.id, package: unit.pkg.name, version: unit.pkg.version, ...outsideField(res.projectDir), ...extra });
52
+ }
53
+ function interpreter(file) {
54
+ if (/\.(m|c)?js$/.test(file))
55
+ return [process.execPath, [file]];
56
+ if (file.endsWith('.sh'))
57
+ return ['sh', [file]];
58
+ return [file, []];
59
+ }
60
+ /** Node.js's error codes for an import or require that finds no module. */
61
+ const MISSING_MODULE = /\b(?:ERR_MODULE_NOT_FOUND|MODULE_NOT_FOUND)\b/;
62
+ export function runScript(res, ref, args, agent, context = {}) {
63
+ const { plugin, name } = parseRef(ref);
64
+ const script = res.scripts.find((s) => s.pkg.plugin === plugin && s.name === name);
65
+ if (!script) {
66
+ const known = res.scripts.filter((s) => s.pkg.plugin === plugin).map((s) => `${plugin}:${s.name}`);
67
+ throw new HarnessError(`No script ${ref}.${known.length > 0 ? ` Scripts of ${plugin}: ${known.join(', ')}` : ''}`);
68
+ }
69
+ checkPackage(script.pkg, res, `Script ${ref}`);
70
+ if (!isFile(script.file))
71
+ throw new HarnessError(`Script ${ref}: ${script.file} does not exist`);
72
+ const [command, prefix] = interpreter(script.file);
73
+ const started = Date.now();
74
+ // The script runs in the caller's folder, so file arguments stay valid, also with -C (spec 10.1); a hook from a parent
75
+ // folder runs in its project (spec 4.10). stdout streams as it is. stderr passes through too, and its tail shows
76
+ // whether a dependency was missing.
77
+ const child = spawn(command, [...prefix, ...args], {
78
+ stdio: [context.input !== undefined ? 'pipe' : 'inherit', 'inherit', 'pipe'],
79
+ cwd: context.cwd ?? process.cwd(),
80
+ env: environment(script.pkg, res, agent),
81
+ });
82
+ if (context.input !== undefined) {
83
+ // A script that exits without reading its stdin closes the pipe: that is not an error.
84
+ child.stdin?.on('error', () => { });
85
+ child.stdin?.end(context.input);
86
+ }
87
+ let tail = '';
88
+ child.stderr?.on('data', (chunk) => {
89
+ process.stderr.write(chunk);
90
+ tail = (tail + chunk.toString('utf8')).slice(-4096);
91
+ });
92
+ return new Promise((done, fail) => {
93
+ let failed = false;
94
+ child.on('error', (error) => {
95
+ failed = true;
96
+ fail(new HarnessError(`Script ${ref} could not start: ${error.message}`));
97
+ });
98
+ child.on('close', (code, signal) => {
99
+ if (failed)
100
+ return;
101
+ const status = code ?? (signal !== null ? 1 : 0);
102
+ if (status !== 0 && context.install !== undefined && MISSING_MODULE.test(tail)) {
103
+ process.stderr.write(`harnesspm: ${ref} needs a package that the project installs, and this project has no install. Install it with \`${context.install}\`, then run the script again.\n`);
104
+ }
105
+ // Never the arguments: they can hold anything (spec 14.2). A signal gives exit 1, as before, but never an answer.
106
+ const outcome = runOutcome(status, script.answers, code === null && signal !== null);
107
+ unitEvent(res, 'run', script, agent, { exit: status, outcome, duration: Date.now() - started });
108
+ done(status);
109
+ });
110
+ });
111
+ }
112
+ export function runMcp(res, ref, agent) {
113
+ const { plugin, name } = parseRef(ref);
114
+ const server = res.mcp.find((s) => s.pkg.plugin === plugin && s.name === name);
115
+ if (!server)
116
+ throw new HarnessError(`No MCP server ${ref}`);
117
+ checkPackage(server.pkg, res, `MCP server ${ref}`);
118
+ if (server.config['type'] !== 'stdio')
119
+ throw new HarnessError(`MCP server ${ref} is remote; agents connect to its URL directly`);
120
+ const env = environment(server.pkg, res, agent);
121
+ const expand = (value) => value.replaceAll('${PLUGIN_ROOT}', env['PLUGIN_ROOT']).replaceAll('${PLUGIN_DATA}', env['PLUGIN_DATA']);
122
+ const command = expand(String(server.config['command']));
123
+ const args = Array.isArray(server.config['args']) ? server.config['args'].map((a) => expand(String(a))) : [];
124
+ const extra = server.config['env'];
125
+ if (extra !== null && typeof extra === 'object')
126
+ for (const [k, v] of Object.entries(extra))
127
+ env[k] = expand(String(v));
128
+ unitEvent(res, 'mcp', server, agent);
129
+ const result = spawnSync(command, args, { stdio: 'inherit', env });
130
+ if (result.error)
131
+ throw new HarnessError(`MCP server ${ref} could not start: ${result.error.message}`);
132
+ return result.status ?? 1;
133
+ }
@@ -0,0 +1,32 @@
1
+ export interface Heading {
2
+ line: number;
3
+ level: number;
4
+ text: string;
5
+ }
6
+ /** ATX headings outside fenced code blocks. */
7
+ export declare function headings(lines: string[]): Heading[];
8
+ export interface PatchSection {
9
+ level: number;
10
+ text: string;
11
+ lines: string[];
12
+ }
13
+ export interface PatchSpec {
14
+ remove: string[];
15
+ preamble: string[];
16
+ sections: PatchSection[];
17
+ }
18
+ export declare function parsePatch(text: string, file?: string): PatchSpec;
19
+ export interface TouchedSection {
20
+ heading: string;
21
+ hash: string;
22
+ }
23
+ export interface PatchResult {
24
+ text: string;
25
+ /** Hashes of the rule's sections that the patch replaced or removed, before the patch. */
26
+ touched: TouchedSection[];
27
+ warnings: string[];
28
+ }
29
+ /** Applies a patch to a rule. The rule's frontmatter is kept. */
30
+ export declare function applyPatch(ruleText: string, patchText: string, patchFile?: string): PatchResult;
31
+ /** Raises every heading level by `by`, outside code blocks, so a rule fits under a block heading. */
32
+ export declare function demoteHeadings(text: string, by: number): string;
@@ -0,0 +1,121 @@
1
+ // Markdown sections and patches (spec 2.5).
2
+ import { parseFrontmatter, stringList, withFrontmatter } from './frontmatter.js';
3
+ import { hash } from './util.js';
4
+ /** ATX headings outside fenced code blocks. */
5
+ export function headings(lines) {
6
+ const result = [];
7
+ let fence;
8
+ lines.forEach((line, index) => {
9
+ const fenceMatch = /^\s*(```+|~~~+)/.exec(line);
10
+ if (fenceMatch) {
11
+ const marker = fenceMatch[1];
12
+ if (fence === undefined)
13
+ fence = marker[0];
14
+ else if (marker[0] === fence)
15
+ fence = undefined;
16
+ return;
17
+ }
18
+ if (fence !== undefined)
19
+ return;
20
+ const match = /^(#{1,6})[ \t]+(.*?)[ \t]*#*[ \t]*$/.exec(line);
21
+ if (match)
22
+ result.push({ line: index, level: match[1].length, text: match[2].trim() });
23
+ });
24
+ return result;
25
+ }
26
+ /** A section is a heading and everything up to the next heading of the same or a higher level. */
27
+ function sectionEnd(lines, hs, index) {
28
+ const own = hs[index];
29
+ for (let i = index + 1; i < hs.length; i++) {
30
+ if (hs[i].level <= own.level)
31
+ return hs[i].line;
32
+ }
33
+ return lines.length;
34
+ }
35
+ export function parsePatch(text, file = 'patch') {
36
+ const { data, body } = parseFrontmatter(text, file);
37
+ const lines = body.split('\n');
38
+ const hs = headings(lines);
39
+ const first = hs[0]?.line ?? lines.length;
40
+ const sections = [];
41
+ let i = 0;
42
+ while (i < hs.length) {
43
+ const end = sectionEnd(lines, hs, i);
44
+ sections.push({ level: hs[i].level, text: hs[i].text, lines: trimBlank(lines.slice(hs[i].line, end)) });
45
+ // Skip headings nested in this section: they are part of it.
46
+ i++;
47
+ while (i < hs.length && hs[i].line < end)
48
+ i++;
49
+ }
50
+ return { remove: stringList(data['remove']) ?? [], preamble: trimBlank(lines.slice(0, first)), sections };
51
+ }
52
+ function trimBlank(lines) {
53
+ let start = 0;
54
+ let end = lines.length;
55
+ while (start < end && lines[start].trim() === '')
56
+ start++;
57
+ while (end > start && lines[end - 1].trim() === '')
58
+ end--;
59
+ return lines.slice(start, end);
60
+ }
61
+ /** Applies a patch to a rule. The rule's frontmatter is kept. */
62
+ export function applyPatch(ruleText, patchText, patchFile = 'patch') {
63
+ const patch = parsePatch(patchText, patchFile);
64
+ const rule = parseFrontmatter(ruleText);
65
+ const lines = rule.body.split('\n');
66
+ const hs = headings(lines);
67
+ const warnings = [];
68
+ const touched = [];
69
+ const ops = [];
70
+ const additions = [];
71
+ const find = (predicate) => {
72
+ const index = hs.findIndex(predicate);
73
+ if (index < 0)
74
+ return undefined;
75
+ return { start: hs[index].line, end: sectionEnd(lines, hs, index) };
76
+ };
77
+ for (const section of patch.sections) {
78
+ const target = find((h) => h.level === section.level && h.text === section.text);
79
+ if (target)
80
+ ops.push({ ...target, replacement: [...section.lines, ''], heading: section.text });
81
+ else
82
+ additions.push(section.lines);
83
+ }
84
+ for (const heading of patch.remove) {
85
+ const target = find((h) => h.text === heading);
86
+ if (target)
87
+ ops.push({ ...target, replacement: [], heading });
88
+ else
89
+ warnings.push(`${patchFile}: the rule has no section "${heading}" to remove`);
90
+ }
91
+ ops.sort((a, b) => b.start - a.start);
92
+ let limit = Number.POSITIVE_INFINITY;
93
+ for (const op of ops) {
94
+ if (op.end > limit) {
95
+ warnings.push(`${patchFile}: section "${op.heading}" overlaps another change and was skipped`);
96
+ continue;
97
+ }
98
+ touched.push({ heading: op.heading, hash: hash(lines.slice(op.start, op.end).join('\n')) });
99
+ lines.splice(op.start, op.end - op.start, ...op.replacement);
100
+ limit = op.start;
101
+ }
102
+ const tail = [...additions, ...(patch.preamble.length > 0 ? [patch.preamble] : [])];
103
+ let body = trimBlank(lines).join('\n');
104
+ for (const block of tail)
105
+ body += `\n\n${block.join('\n')}`;
106
+ body += '\n';
107
+ return {
108
+ text: rule.hasFrontmatter ? withFrontmatter(rule.data, body) : body,
109
+ touched: touched.sort((a, b) => a.heading.localeCompare(b.heading)),
110
+ warnings,
111
+ };
112
+ }
113
+ /** Raises every heading level by `by`, outside code blocks, so a rule fits under a block heading. */
114
+ export function demoteHeadings(text, by) {
115
+ const lines = text.split('\n');
116
+ for (const h of headings(lines)) {
117
+ const level = Math.min(6, h.level + by);
118
+ lines[h.line] = `${'#'.repeat(level)} ${h.text}`;
119
+ }
120
+ return lines.join('\n');
121
+ }
@@ -0,0 +1,18 @@
1
+ export declare const DOCS_URL = "https://harnesspm.tenphi.me";
2
+ /** The version of the running harnesspm. */
3
+ export declare function version(): string;
4
+ /** Who decides, said once under every list of tasks. */
5
+ export declare const PERSON_DECIDES = "A person decides what runs: they add a harness and trust a package. An agent asks first.";
6
+ export declare const EVERY_COMMAND = "Every command: `npx -y @harnesspm/cli --help`";
7
+ /**
8
+ * What the bare command prints in a folder that does not use harnesspm: what the folder is, and the tasks for it, the
9
+ * likeliest first. Each task names the one command that starts it, and that command prints the next step.
10
+ */
11
+ export declare function startText(dir: string): string[];
12
+ /** The steps after `init` wrote and synced: what to commit, the check for CI, and what the agent does now. */
13
+ export declare function afterInit(toCommit: string[], waiting: boolean): string[];
14
+ /**
15
+ * What to do after `new`, by the folder (spec 10.2): an added harness saves the owner's way, a project that uses
16
+ * harnesspm syncs, a package publishes the harness, and a harness of one's own is added by a person.
17
+ */
18
+ export declare function nextAfterNew(projectDir: string, added: boolean): string[];
package/dist/start.js ADDED
@@ -0,0 +1,136 @@
1
+ // Where every task starts (spec 10.1): the bare command's tasks for a folder, and the next steps that `init`, `new` and
2
+ // errors print. One source, so the site only shows the command and the CLI, versioned with the package, holds the steps.
3
+ import * as path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { CONFIG_FILE } from './config.js';
6
+ import { childProjects, isParentFolder } from './parent.js';
7
+ import { resolve } from './resolve.js';
8
+ import { HarnessError, NPX_ANY, PACKAGE_NAME, PACKAGE_NAMES, isDir, isFile, isRecord, readJson, readJsonIfExists, relPosix, shellWord } from './util.js';
9
+ export const DOCS_URL = 'https://harnesspm.tenphi.me';
10
+ /** The version of the running harnesspm. */
11
+ export function version() {
12
+ const pkg = readJson(fileURLToPath(new URL('../package.json', import.meta.url)));
13
+ return isRecord(pkg) && typeof pkg['version'] === 'string' ? pkg['version'] : 'unknown';
14
+ }
15
+ const ADD = { what: "Add your own or your team's harness, on every repo", command: `${NPX_ANY} add <github:owner/repo | folder>` };
16
+ const OWN = { what: 'Start a harness of your own, in an empty folder', command: `${NPX_ANY} new rule workflow` };
17
+ /** Who decides, said once under every list of tasks. */
18
+ export const PERSON_DECIDES = 'A person decides what runs: they add a harness and trust a package. An agent asks first.';
19
+ export const EVERY_COMMAND = `Every command: \`${NPX_ANY} --help\``;
20
+ /** The dependencies of a package folder that ship a harness, harnesspm's own left out. */
21
+ function shipping(dir) {
22
+ try {
23
+ const packages = resolve(dir, { team: true }).packages.filter((p) => p.layer === 'dependencies' && !PACKAGE_NAMES.includes(p.name));
24
+ // The ones the project lists first, then those they pass on.
25
+ const names = [...packages.filter((p) => p.direct), ...packages.filter((p) => !p.direct)].map((p) => p.name);
26
+ if (names.length === 0)
27
+ return isDir(path.join(dir, 'node_modules')) ? 'No installed dependency ships a harness yet.' : 'Its dependencies are not installed yet.';
28
+ return `${names.length === 1 ? '1 dependency ships' : `${names.length} dependencies ship`} a harness: ${names.join(', ')}.`;
29
+ }
30
+ catch (error) {
31
+ if (error instanceof HarnessError)
32
+ return '';
33
+ throw error;
34
+ }
35
+ }
36
+ /**
37
+ * What the bare command prints in a folder that does not use harnesspm: what the folder is, and the tasks for it, the
38
+ * likeliest first. Each task names the one command that starts it, and that command prints the next step.
39
+ */
40
+ export function startText(dir) {
41
+ const name = path.basename(dir);
42
+ const isPackage = isRecord(readJsonIfExists(path.join(dir, 'package.json')));
43
+ const hasHarness = isFile(path.join(dir, 'harness', 'plugin.json'));
44
+ let about;
45
+ let tasks;
46
+ if (isPackage && hasHarness) {
47
+ about = `This package (${name}) shares a harness and does not use harnesspm itself.`;
48
+ tasks = [
49
+ { what: 'Check the harness this package shares', command: `${NPX_ANY} check` },
50
+ { what: "See it as its users' agents will, in AGENTS.md", command: `${NPX_ANY} init` },
51
+ { what: 'Add a rule, skill or tool to it', command: `${NPX_ANY} new <kind> <name>` },
52
+ ADD,
53
+ ];
54
+ }
55
+ else if (isPackage) {
56
+ about = `This folder (${name}) does not use harnesspm. ${shipping(dir)}`.trimEnd();
57
+ tasks = [
58
+ { what: "Give this project's agents its dependencies' harness", command: `${NPX_ANY} init` },
59
+ { what: 'Share a harness from this package', command: `${NPX_ANY} new rule usage` },
60
+ ADD,
61
+ OWN,
62
+ ];
63
+ }
64
+ else if (isParentFolder(dir)) {
65
+ const projects = childProjects(dir).map((p) => path.basename(p));
66
+ about = `This folder is above ${projects.length === 1 ? '1 project' : `${projects.length} projects`} that use harnesspm: ${projects.join(', ')}.`;
67
+ tasks = [
68
+ { what: 'Give sessions that start here their hooks', command: `${NPX_ANY} sync` },
69
+ { what: "List a project's packages from here", command: `${NPX_ANY} -C ${shellWord(projects[0])} help` },
70
+ ADD,
71
+ ];
72
+ }
73
+ else if (hasHarness) {
74
+ about = `This folder (${name}) is a harness, not a project: it has no package.json.`;
75
+ tasks = [
76
+ { what: 'Check it', command: `${NPX_ANY} check` },
77
+ { what: 'Add a rule, skill or tool to it', command: `${NPX_ANY} new <kind> <name>` },
78
+ { what: 'Add it on this machine (a person does this)', command: `${NPX_ANY} add ${shellWord(dir)}` },
79
+ ];
80
+ }
81
+ else {
82
+ about = `This folder (${name}) is not a project: it has no package.json.`;
83
+ tasks = [
84
+ { ...OWN, what: 'Start a harness of your own, in this folder' },
85
+ ADD,
86
+ { what: "Give a project's agents its dependencies' harness, in it", command: `${NPX_ANY} init` },
87
+ { what: 'Share a harness from a package, in it', command: `${NPX_ANY} new rule usage` },
88
+ ];
89
+ }
90
+ const width = Math.max(...tasks.map((t) => t.what.length)) + 3;
91
+ return [
92
+ `harnesspm ${version()}: rules, docs, skills and tools from npm packages, for Claude Code and Codex.`,
93
+ about,
94
+ '',
95
+ 'Pick the task, run its command, and follow what it prints:',
96
+ ...tasks.map((t) => ` ${t.what.padEnd(width)}${t.command}`),
97
+ '',
98
+ PERSON_DECIDES,
99
+ `Every command: ${NPX_ANY} --help · Docs: ${DOCS_URL}`,
100
+ ];
101
+ }
102
+ /** The steps after `init` wrote and synced: what to commit, the check for CI, and what the agent does now. */
103
+ export function afterInit(toCommit, waiting) {
104
+ return [
105
+ ...(toCommit.length > 0 ? [`To commit: ${toCommit.join(', ')}`] : []),
106
+ `In CI, after the install: ${NPX_ANY} sync --check`,
107
+ waiting ? 'Agent: report this to the person and wait for their trust decision.' : 'Agent: report this to the person.',
108
+ ];
109
+ }
110
+ /** The harnesspm-export skill: the copy the project installed, else the one that ships with this harnesspm. */
111
+ function exportSkill(projectDir) {
112
+ const rel = path.join('harness', 'skills', 'harnesspm-export', 'SKILL.md');
113
+ const installed = path.join(projectDir, 'node_modules', PACKAGE_NAME, rel);
114
+ return isFile(installed) ? relPosix(projectDir, installed) : fileURLToPath(new URL(`../${rel.split(path.sep).join('/')}`, import.meta.url));
115
+ }
116
+ /**
117
+ * What to do after `new`, by the folder (spec 10.2): an added harness saves the owner's way, a project that uses
118
+ * harnesspm syncs, a package publishes the harness, and a harness of one's own is added by a person.
119
+ */
120
+ export function nextAfterNew(projectDir, added) {
121
+ if (added)
122
+ return [`Next: edit it, run \`${NPX_ANY} sync\`, then save the change the way that harness's own AGENTS.md or CONTRIBUTING.md says.`];
123
+ if (isFile(path.join(projectDir, CONFIG_FILE)))
124
+ return [`Next: edit it, then run \`${NPX_ANY} sync\` and \`${NPX_ANY} check\`.`];
125
+ if (!isFile(path.join(projectDir, 'package.json'))) {
126
+ return [
127
+ `Next: edit it, run \`${NPX_ANY} check\`, and commit.`,
128
+ `A person adds it on their machine, in their own terminal: \`${NPX_ANY} add ${shellWord(projectDir)}\`, or \`add github:<owner>/<repo>\` once it is pushed.`,
129
+ ];
130
+ }
131
+ return [
132
+ `Next: edit it, then run \`${NPX_ANY} check\`.`,
133
+ `To publish it, add "harness" to "files" in package.json, and "prepack": "harnesspm check" with ${PACKAGE_NAME} as a dev dependency.`,
134
+ `Every step, and what goes into a harness: the harnesspm-export skill, ${exportSkill(projectDir)}`,
135
+ ];
136
+ }
@@ -0,0 +1,26 @@
1
+ export interface RunReport {
2
+ /** The tool's unit ID, such as `app:scripts/probe`: `<plugin name>:<path>`. */
3
+ unit: string;
4
+ /**
5
+ * Fields of the tool's own, such as `{ mode: 'fast' }`. Rule 1 of spec 14.2 applies: no arguments, file contents,
6
+ * prompts, tool output or absolute paths. A field with the name of a common field is left out.
7
+ */
8
+ fields?: Record<string, unknown>;
9
+ /** Where the tool runs. The project is the nearest folder with `harnesspm.json` above it. Default: the current folder. */
10
+ cwd?: string;
11
+ /** How long the tool ran, in milliseconds. */
12
+ duration?: number;
13
+ /** The tool's exit code. */
14
+ exit?: number;
15
+ /**
16
+ * Exit codes that are answers, not failures, such as `[1]` for a lint that found problems. They set the event's
17
+ * `outcome`: `ok` for 0, `answer` for a code in this list, `failed` for any other code (spec 14.2).
18
+ */
19
+ answers?: number[];
20
+ }
21
+ /**
22
+ * Sends a `run` event for a tool of the project, as `harnesspm run` does for a script (spec 14.2). It applies every
23
+ * opt-out and sends nothing while the handler is held (spec 14.5, 14.6). It never throws, never prints and never
24
+ * waits: a command handler gets the event in a detached process, so a tool can call it right before `process.exit()`.
25
+ */
26
+ export declare function reportRun(report: RunReport): void;
@@ -0,0 +1,60 @@
1
+ // The public telemetry entry, `@harnesspm/cli/telemetry` (spec 14.9): a project's own tools report their runs
2
+ // through the same handler, switch, opt-outs and trust rule as `harnesspm run`. Like `harnesspm track`, it loads
3
+ // only Node.js built-ins and light modules, so a tool can call it on every run.
4
+ import * as path from 'node:path';
5
+ import { commandCaller, configDir, note, outsideField, readIndex, readTelemetryState, runOutcome, sendEvent } from './telemetry.js';
6
+ import { findWorkspaces } from './workspaces.js';
7
+ import { isRecord, readJsonIfExists, relPosix } from './util.js';
8
+ /** Fields that harnesspm sets on every `run` event. A tool's own fields never replace them. */
9
+ const RESERVED = new Set(['schema', 'type', 'time', 'project', 'repository', 'workspace', 'harnesspm', 'caller', 'agent', 'session', 'unit', 'package', 'version', 'exit', 'outcome', 'duration', 'outside']);
10
+ const UNIT_ID = /^[^\s:]+:\S+$/;
11
+ function contextOf(projectDir, index) {
12
+ // `sync` writes the index when agent events are on. Without it, read the same facts from the project.
13
+ if (index)
14
+ return { projectDir, project: index.project, ...(index.repository !== undefined ? { repository: index.repository } : {}), workspaces: index.workspaces };
15
+ const pkg = readJsonIfExists(path.join(projectDir, 'package.json'));
16
+ const project = isRecord(pkg) && typeof pkg['name'] === 'string' ? pkg['name'] : path.basename(projectDir);
17
+ return { projectDir, project, workspaces: findWorkspaces(projectDir).map((dir) => relPosix(projectDir, dir)) };
18
+ }
19
+ /**
20
+ * Sends a `run` event for a tool of the project, as `harnesspm run` does for a script (spec 14.2). It applies every
21
+ * opt-out and sends nothing while the handler is held (spec 14.5, 14.6). It never throws, never prints and never
22
+ * waits: a command handler gets the event in a detached process, so a tool can call it right before `process.exit()`.
23
+ */
24
+ export function reportRun(report) {
25
+ let projectDir;
26
+ try {
27
+ projectDir = configDir(report.cwd ?? process.cwd());
28
+ if (projectDir === undefined)
29
+ return;
30
+ const state = readTelemetryState(projectDir);
31
+ if (state.send === undefined || !state.events.has('run'))
32
+ return;
33
+ if (typeof report.unit !== 'string' || !UNIT_ID.test(report.unit)) {
34
+ note(projectDir, `reportRun: "${String(report.unit)}" is not a unit ID such as app:scripts/probe`);
35
+ return;
36
+ }
37
+ const index = readIndex(projectDir);
38
+ const own = Object.fromEntries(Object.entries(report.fields ?? {}).filter(([key]) => !RESERVED.has(key)));
39
+ const pkg = index?.packages[report.unit.slice(0, report.unit.indexOf(':'))];
40
+ const exit = typeof report.exit === 'number' ? report.exit : undefined;
41
+ const answers = Array.isArray(report.answers) ? report.answers.filter((code) => Number.isInteger(code) && code >= 1 && code <= 255) : [];
42
+ sendEvent(state, contextOf(projectDir, index), {
43
+ type: 'run',
44
+ ...commandCaller(),
45
+ unit: report.unit,
46
+ package: pkg?.package,
47
+ version: pkg?.version,
48
+ ...own,
49
+ exit,
50
+ outcome: runOutcome(exit, answers),
51
+ duration: typeof report.duration === 'number' ? Math.round(report.duration) : undefined,
52
+ // The caller's folder, not `cwd`: a tool that an agent starts from another repository runs outside the project.
53
+ ...outsideField(projectDir),
54
+ }, report.cwd ?? process.cwd());
55
+ }
56
+ catch (error) {
57
+ if (projectDir !== undefined)
58
+ note(projectDir, `reportRun: ${error.message}`);
59
+ }
60
+ }
@@ -0,0 +1,119 @@
1
+ export declare const EVENT_TYPES: readonly ['run', 'mcp', 'sync', 'why', 'help', 'read', 'skill', 'session'];
2
+ export type EventType = (typeof EVENT_TYPES)[number];
3
+ /** Events that harnesspm's own agent hooks send (spec 14.4). */
4
+ export declare const AGENT_EVENTS: readonly EventType[];
5
+ export declare const EVENT_SCHEMA = "harnesspm.event/1";
6
+ /** Per-machine files, next to the stable package paths (spec 4.2). */
7
+ export declare const INDEX_FILE: string;
8
+ /** A command that gets each event as JSON on stdin, or a file that gets one JSON line per event. */
9
+ export type Send = string | {
10
+ file: string;
11
+ };
12
+ export interface TelemetryConfig {
13
+ events: EventType[];
14
+ send: Send;
15
+ }
16
+ /** Validates the `telemetry` field of harnesspm.json (spec 14.1). */
17
+ export declare function parseTelemetry(value: unknown): TelemetryConfig | undefined;
18
+ export declare const sameSend: (a: unknown, b: unknown) => boolean;
19
+ export declare const describeSend: (send: Send) => string;
20
+ export interface TelemetryState {
21
+ config?: TelemetryConfig;
22
+ /** Where events go: the configured handler, when a person's sync recorded it and this machine did not opt out. */
23
+ send?: Send;
24
+ events: Set<EventType>;
25
+ /** Why nothing is sent. */
26
+ off?: string;
27
+ }
28
+ /** A person's opt-out on this machine (spec 14.6), or undefined. */
29
+ export declare function optOut(projectDir: string, env?: NodeJS.ProcessEnv): string | undefined;
30
+ /** `recorded` is the handler in the lock, which only a person's sync writes (spec 14.5). */
31
+ export declare function telemetryState(projectDir: string, config: TelemetryConfig | undefined, recorded: unknown): TelemetryState;
32
+ /** The state from harnesspm.json and the lock on disk, without resolving the harness. */
33
+ export declare function readTelemetryState(projectDir: string): TelemetryState;
34
+ export interface EventContext {
35
+ /** The project root, as a real path. */
36
+ projectDir: string;
37
+ project: string;
38
+ /** `<host>/<path>` of the `origin` remote. Undefined: looked up when an event is sent. Empty: none. */
39
+ repository?: string | undefined;
40
+ /** Workspace folders from the root, with forward slashes. */
41
+ workspaces: string[];
42
+ }
43
+ export type EventCaller = 'person' | 'agent' | 'hook' | 'ci';
44
+ export interface EventFields {
45
+ type: EventType;
46
+ caller: EventCaller;
47
+ agent?: string | undefined;
48
+ session?: string | undefined;
49
+ unit?: string | undefined;
50
+ package?: string | undefined;
51
+ version?: string | undefined;
52
+ [field: string]: unknown;
53
+ }
54
+ /** Who runs a harnesspm command, for events. Hooks and MCP servers pass `--agent` (spec 5.1). */
55
+ export declare function commandCaller(agentFlag?: string, env?: NodeJS.ProcessEnv): Pick<EventFields, 'caller' | 'agent' | 'session'>;
56
+ export type RunOutcome = 'ok' | 'answer' | 'failed';
57
+ /**
58
+ * What a run's exit code means (spec 14.2): `ok` for 0, `answer` for a code the tool lists in `answers`, `failed` for
59
+ * any other code. A run that a signal ended failed, whatever `answers` holds. No exit code: no outcome.
60
+ */
61
+ export declare function runOutcome(exit: number | undefined, answers?: readonly number[], signal?: boolean): RunOutcome | undefined;
62
+ /** `{ outside: true }` when harnesspm runs from a folder outside the project, such as with `-C` (spec 14.2). Otherwise nothing. */
63
+ export declare function outsideField(projectDir: string, from?: string): {
64
+ outside?: true;
65
+ };
66
+ /** One event (spec 14.2). Fields that are undefined are left out. */
67
+ export declare function makeEvent(ctx: EventContext, fields: EventFields, cwd?: string): Record<string, unknown>;
68
+ /** Notes a delivery problem in a per-machine log. Never throws, never prints (spec 14.3). */
69
+ export declare function note(projectDir: string, message: string): void;
70
+ /** Sends one event when telemetry is on and wants this type. Never throws, never waits. */
71
+ export declare function sendEvent(state: TelemetryState, ctx: EventContext, fields: EventFields, cwd?: string): void;
72
+ /** Sends the events that telemetry wants, in one hand-off. Never throws, never waits. */
73
+ export declare function sendEvents(state: TelemetryState, ctx: EventContext, list: EventFields[], cwd?: string): void;
74
+ /** What the agent hooks need to map a file or skill to a unit. `sync` writes it on each machine. */
75
+ export interface TelemetryIndex {
76
+ project: string;
77
+ /** `<host>/<path>` of the `origin` remote, so a hook does not ask git each time. */
78
+ repository?: string;
79
+ workspaces: string[];
80
+ /** Plugin name → its package. */
81
+ packages: Record<string, {
82
+ package: string;
83
+ version: string;
84
+ }>;
85
+ /** Real path of a file → unit ID: rule files, generated rules, generated docs indexes. */
86
+ files: Record<string, string>;
87
+ /** Real path of a folder → unit ID: skill folders and docs folders. */
88
+ dirs: Record<string, string>;
89
+ /** Skill name → unit ID. */
90
+ skills: Record<string, string>;
91
+ /** Real path of a workspace's AGENTS.md → the always-on rules in its managed block (spec 4.5). */
92
+ blocks?: Record<string, string[]>;
93
+ }
94
+ export declare function readIndex(projectDir: string): TelemetryIndex | undefined;
95
+ /** The unit a file belongs to. A docs file also gets its page, relative to the docs folder. */
96
+ export declare function unitOfFile(index: TelemetryIndex, file: string, cwd: string): {
97
+ unit: string;
98
+ page?: string;
99
+ } | undefined;
100
+ type AgentEvent = {
101
+ type: EventType;
102
+ [field: string]: unknown;
103
+ };
104
+ /** The events that an agent's hook payload stands for, without the common fields. Usually one; none for other files. */
105
+ export declare function agentEvents(payload: Record<string, unknown>, index: TelemetryIndex): AgentEvent[];
106
+ /** The nearest folder with harnesspm.json, as a real path. */
107
+ export declare function configDir(cwd: string): string | undefined;
108
+ /**
109
+ * The session of a hook's event (spec 14.4). Claude Code's commands see `CLAUDE_CODE_SESSION_ID`, and `run` events use it,
110
+ * so a Claude Code hook uses it too when it is set: on a person's machine it can differ from the payload's `session_id`.
111
+ */
112
+ export declare function hookSession(payload: Record<string, unknown>, agent: string | undefined, env?: NodeJS.ProcessEnv): string | undefined;
113
+ /**
114
+ * `harnesspm track --agent <agent>`: the command of harnesspm's agent hooks. It reads the hook's JSON
115
+ * on stdin, maps it to an event, hands the event off and exits 0 at once. It never prints.
116
+ * `project` comes from `-C`: a hook in a folder above the project names it, because the session's folder is not in it (spec 4.10).
117
+ */
118
+ export declare function track(args: string[], project?: string): number;
119
+ export {};