@harnesspm/cli 0.0.1 → 0.17.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 (81) hide show
  1. package/CHANGELOG.md +269 -0
  2. package/LICENSE +1 -1
  3. package/README.md +68 -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 +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 +187 -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 +66 -11
  80. package/schema/harnesspm.schema.json +58 -0
  81. 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}`);
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,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 {};