@harnesspm/cli 0.0.0-snapshot.412a718

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/CHANGELOG.md +259 -0
  2. package/LICENSE +21 -0
  3. package/README.md +70 -0
  4. package/dist/added.d.ts +51 -0
  5. package/dist/added.js +192 -0
  6. package/dist/check.d.ts +14 -0
  7. package/dist/check.js +263 -0
  8. package/dist/cli.d.ts +2 -0
  9. package/dist/cli.js +218 -0
  10. package/dist/commands.d.ts +58 -0
  11. package/dist/commands.js +1299 -0
  12. package/dist/config.d.ts +15 -0
  13. package/dist/config.js +45 -0
  14. package/dist/deliver.d.ts +1 -0
  15. package/dist/deliver.js +31 -0
  16. package/dist/doctor.d.ts +18 -0
  17. package/dist/doctor.js +99 -0
  18. package/dist/exec-outputs.d.ts +75 -0
  19. package/dist/exec-outputs.js +425 -0
  20. package/dist/exec-units.d.ts +68 -0
  21. package/dist/exec-units.js +151 -0
  22. package/dist/fetch.d.ts +16 -0
  23. package/dist/fetch.js +145 -0
  24. package/dist/frontmatter.d.ts +16 -0
  25. package/dist/frontmatter.js +49 -0
  26. package/dist/homes.d.ts +7 -0
  27. package/dist/homes.js +21 -0
  28. package/dist/lock.d.ts +47 -0
  29. package/dist/lock.js +245 -0
  30. package/dist/manifest.d.ts +78 -0
  31. package/dist/manifest.js +169 -0
  32. package/dist/new.d.ts +33 -0
  33. package/dist/new.js +228 -0
  34. package/dist/outputs.d.ts +124 -0
  35. package/dist/outputs.js +875 -0
  36. package/dist/parent.d.ts +41 -0
  37. package/dist/parent.js +182 -0
  38. package/dist/render.d.ts +91 -0
  39. package/dist/render.js +221 -0
  40. package/dist/resolve.d.ts +132 -0
  41. package/dist/resolve.js +522 -0
  42. package/dist/reviewed.d.ts +15 -0
  43. package/dist/reviewed.js +41 -0
  44. package/dist/run.d.ts +18 -0
  45. package/dist/run.js +133 -0
  46. package/dist/sections.d.ts +32 -0
  47. package/dist/sections.js +121 -0
  48. package/dist/telemetry-api.d.ts +26 -0
  49. package/dist/telemetry-api.js +60 -0
  50. package/dist/telemetry.d.ts +119 -0
  51. package/dist/telemetry.js +401 -0
  52. package/dist/user-outputs.d.ts +30 -0
  53. package/dist/user-outputs.js +239 -0
  54. package/dist/util.d.ts +137 -0
  55. package/dist/util.js +370 -0
  56. package/dist/workspaces.d.ts +2 -0
  57. package/dist/workspaces.js +62 -0
  58. package/docs/spec/01-overview.md +149 -0
  59. package/docs/spec/02-package-format.md +252 -0
  60. package/docs/spec/03-resolution.md +108 -0
  61. package/docs/spec/04-outputs.md +194 -0
  62. package/docs/spec/05-executables.md +170 -0
  63. package/docs/spec/06-trust.md +88 -0
  64. package/docs/spec/07-added.md +109 -0
  65. package/docs/spec/08-improving.md +79 -0
  66. package/docs/spec/09-cloud.md +68 -0
  67. package/docs/spec/10-cli.md +181 -0
  68. package/docs/spec/11-standards.md +52 -0
  69. package/docs/spec/12-dogfooding.md +51 -0
  70. package/docs/spec/13-open-questions.md +97 -0
  71. package/docs/spec/14-telemetry.md +199 -0
  72. package/docs/spec/README.md +33 -0
  73. package/harness/dev.harnesspm/rules/generated-files.md +9 -0
  74. package/harness/dev.harnesspm/rules/harnesspm-config.md +12 -0
  75. package/harness/plugin.json +13 -0
  76. package/harness/skills/harnesspm-export/SKILL.md +43 -0
  77. package/harness/skills/harnesspm-import/SKILL.md +40 -0
  78. package/harness/skills/harnesspm-improve/SKILL.md +38 -0
  79. package/package.json +73 -0
  80. package/schema/harnesspm.schema.json +58 -0
@@ -0,0 +1,401 @@
1
+ // Telemetry (spec chapter 14): events about how a harness is used, sent to the project's handler.
2
+ // `harnesspm track` runs this module from agent hooks, so it imports only Node.js built-ins and light modules.
3
+ import { spawn } from 'node:child_process';
4
+ import * as fs from 'node:fs';
5
+ import * as path from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { harnesspmHome } from './homes.js';
8
+ import { HarnessError, NPX_ANY, addExclude, agentOf, caller, insideDir, isFile, isRecord, readTextIfExists, remoteKey, toPosix } from './util.js';
9
+ export const EVENT_TYPES = ['run', 'mcp', 'sync', 'why', 'help', 'read', 'skill', 'session'];
10
+ /** Events that harnesspm's own agent hooks send (spec 14.4). */
11
+ export const AGENT_EVENTS = ['read', 'skill', 'session'];
12
+ export const EVENT_SCHEMA = 'harnesspm.event/1';
13
+ /** Per-machine files, next to the stable package paths (spec 4.2). */
14
+ export const INDEX_FILE = path.join('node_modules', '.harnesspm', 'telemetry.json');
15
+ const LOG_FILE = path.join('node_modules', '.harnesspm', 'telemetry.log');
16
+ /** An event is passed to the delivering process in an environment variable, which has a size limit. */
17
+ const MAX_EVENT = 100_000;
18
+ /** Validates the `telemetry` field of harnesspm.json (spec 14.1). */
19
+ export function parseTelemetry(value) {
20
+ if (value === undefined)
21
+ return undefined;
22
+ const where = 'harnesspm.json: "telemetry"';
23
+ if (!isRecord(value))
24
+ throw new HarnessError(`${where} must be an object with "send"`);
25
+ for (const key of Object.keys(value))
26
+ if (key !== 'events' && key !== 'send')
27
+ throw new HarnessError(`${where} has an unknown field "${key}"`);
28
+ const send = value['send'];
29
+ let parsed;
30
+ if (typeof send === 'string' && send.trim() !== '')
31
+ parsed = send;
32
+ else if (isRecord(send) && Object.keys(send).length === 1 && typeof send['file'] === 'string' && send['file'] !== '')
33
+ parsed = { file: send['file'] };
34
+ else
35
+ throw new HarnessError(`${where} needs "send": a command, or { "file": "<path>" }`);
36
+ const raw = value['events'] ?? 'all';
37
+ if (raw === 'all')
38
+ return { events: [...EVENT_TYPES], send: parsed };
39
+ if (!Array.isArray(raw) || !raw.every((e) => typeof e === 'string'))
40
+ throw new HarnessError(`${where}: "events" must be "all" or a list of event types`);
41
+ const unknown = raw.filter((e) => !EVENT_TYPES.includes(e));
42
+ if (unknown.length > 0)
43
+ throw new HarnessError(`${where}: unknown event "${unknown[0]}". Use "all" or some of: ${EVENT_TYPES.join(', ')}`);
44
+ return { events: EVENT_TYPES.filter((e) => raw.includes(e)), send: parsed };
45
+ }
46
+ export const sameSend = (a, b) => a !== undefined && b !== undefined && JSON.stringify(a) === JSON.stringify(b);
47
+ export const describeSend = (send) => (typeof send === 'string' ? `command \`${send}\`` : `file ${send.file}`);
48
+ function flagOff(file) {
49
+ try {
50
+ const raw = JSON.parse(fs.readFileSync(file, 'utf8'));
51
+ return isRecord(raw) && raw['telemetry'] === false;
52
+ }
53
+ catch {
54
+ return false;
55
+ }
56
+ }
57
+ /** A person's opt-out on this machine (spec 14.6), or undefined. */
58
+ export function optOut(projectDir, env = process.env) {
59
+ const dnt = (env['DO_NOT_TRACK'] ?? '').trim().toLowerCase();
60
+ if (dnt !== '' && dnt !== '0' && dnt !== 'false')
61
+ return 'DO_NOT_TRACK is set';
62
+ if (flagOff(path.join(projectDir, 'harnesspm.local.json')))
63
+ return '"telemetry": false in harnesspm.local.json';
64
+ const user = path.join(harnesspmHome(), 'config.json');
65
+ if (flagOff(user))
66
+ return `"telemetry": false in ${user}`;
67
+ return undefined;
68
+ }
69
+ /** `recorded` is the handler in the lock, which only a person's sync writes (spec 14.5). */
70
+ export function telemetryState(projectDir, config, recorded) {
71
+ if (!config)
72
+ return { events: new Set(), off: 'not configured' };
73
+ const opted = optOut(projectDir);
74
+ if (opted !== undefined)
75
+ return { config, events: new Set(), off: `off on this machine: ${opted}` };
76
+ if (!sameSend(config.send, recorded)) {
77
+ return { config, events: new Set(), off: `held: the handler in harnesspm.json is not the one a person's sync recorded in harnesspm.lock.json. A person runs \`${NPX_ANY} sync\`.` };
78
+ }
79
+ return { config, send: config.send, events: new Set(config.events) };
80
+ }
81
+ const readJsonQuietly = (file) => {
82
+ const text = readTextIfExists(file);
83
+ return text === undefined ? undefined : JSON.parse(text);
84
+ };
85
+ /** The state from harnesspm.json and the lock on disk, without resolving the harness. */
86
+ export function readTelemetryState(projectDir) {
87
+ try {
88
+ const config = readJsonQuietly(path.join(projectDir, 'harnesspm.json'));
89
+ const lock = readJsonQuietly(path.join(projectDir, 'harnesspm.lock.json'));
90
+ const recorded = isRecord(lock) && isRecord(lock['telemetry']) ? lock['telemetry']['send'] : undefined;
91
+ return telemetryState(projectDir, isRecord(config) ? parseTelemetry(config['telemetry']) : undefined, recorded);
92
+ }
93
+ catch (error) {
94
+ return { events: new Set(), off: `invalid configuration: ${error.message}` };
95
+ }
96
+ }
97
+ let version;
98
+ function harnesspmVersion() {
99
+ if (version === undefined) {
100
+ try {
101
+ const raw = JSON.parse(fs.readFileSync(fileURLToPath(new URL('../package.json', import.meta.url)), 'utf8'));
102
+ version = isRecord(raw) && typeof raw['version'] === 'string' ? raw['version'] : '';
103
+ }
104
+ catch {
105
+ version = '';
106
+ }
107
+ }
108
+ return version;
109
+ }
110
+ function workspaceOf(ctx, cwd) {
111
+ let dir = cwd;
112
+ try {
113
+ dir = fs.realpathSync(cwd);
114
+ }
115
+ catch {
116
+ // Keep the path as it is.
117
+ }
118
+ const rel = toPosix(path.relative(ctx.projectDir, dir));
119
+ let best = '.';
120
+ for (const key of ctx.workspaces)
121
+ if ((rel === key || rel.startsWith(`${key}/`)) && (best === '.' || key.length > best.length))
122
+ best = key;
123
+ return best;
124
+ }
125
+ /** Who runs a harnesspm command, for events. Hooks and MCP servers pass `--agent` (spec 5.1). */
126
+ export function commandCaller(agentFlag, env = process.env) {
127
+ const who = caller(env);
128
+ const value = who === 'model' ? 'agent' : who === 'hook' || agentFlag !== undefined ? 'hook' : env['CI'] === 'true' ? 'ci' : 'person';
129
+ const agent = agentFlag ?? agentOf(env);
130
+ const session = env['CLAUDE_CODE_SESSION_ID'];
131
+ return { caller: value, agent, session: agent !== undefined && session !== '' ? session : undefined };
132
+ }
133
+ /**
134
+ * What a run's exit code means (spec 14.2): `ok` for 0, `answer` for a code the tool lists in `answers`, `failed` for
135
+ * any other code. A run that a signal ended failed, whatever `answers` holds. No exit code: no outcome.
136
+ */
137
+ export function runOutcome(exit, answers = [], signal = false) {
138
+ if (signal)
139
+ return 'failed';
140
+ if (typeof exit !== 'number' || !Number.isInteger(exit))
141
+ return undefined;
142
+ return exit === 0 ? 'ok' : answers.includes(exit) ? 'answer' : 'failed';
143
+ }
144
+ /** `{ outside: true }` when harnesspm runs from a folder outside the project, such as with `-C` (spec 14.2). Otherwise nothing. */
145
+ export function outsideField(projectDir, from = process.cwd()) {
146
+ return insideDir(projectDir, from) ? {} : { outside: true };
147
+ }
148
+ const worktrees = new Map();
149
+ /**
150
+ * True when `dir` is in a linked git worktree, one that `git worktree add` made (spec 14.2). Its `.git` is a file that
151
+ * points into the main repository's `worktrees/` folder; a submodule's points into `modules/`. Reads files only, so a
152
+ * hook never waits for git.
153
+ */
154
+ function inWorktree(dir) {
155
+ const start = path.resolve(dir);
156
+ const known = worktrees.get(start);
157
+ if (known !== undefined)
158
+ return known;
159
+ let found = false;
160
+ for (let at = start;; at = path.dirname(at)) {
161
+ const dotGit = path.join(at, '.git');
162
+ const stat = fs.statSync(dotGit, { throwIfNoEntry: false });
163
+ if (stat?.isFile()) {
164
+ try {
165
+ found = /^gitdir:\s*.*[\\/]worktrees[\\/][^\\/]+[\\/]?\s*$/m.test(fs.readFileSync(dotGit, 'utf8'));
166
+ }
167
+ catch {
168
+ // An unreadable .git file: not known to be a worktree.
169
+ }
170
+ }
171
+ if (stat !== undefined || path.dirname(at) === at)
172
+ break;
173
+ }
174
+ worktrees.set(start, found);
175
+ return found;
176
+ }
177
+ /** One event (spec 14.2). Fields that are undefined are left out. */
178
+ export function makeEvent(ctx, fields, cwd = process.cwd()) {
179
+ const { type, ...rest } = fields;
180
+ const event = { schema: EVENT_SCHEMA, type, time: new Date().toISOString(), project: ctx.project };
181
+ if (ctx.repository)
182
+ event['repository'] = ctx.repository;
183
+ Object.assign(event, { workspace: workspaceOf(ctx, cwd), harnesspm: harnesspmVersion() });
184
+ if (inWorktree(cwd))
185
+ event['worktree'] = true;
186
+ for (const [key, value] of Object.entries(rest))
187
+ if (value !== undefined)
188
+ event[key] = value;
189
+ return event;
190
+ }
191
+ /** Notes a delivery problem in a per-machine log. Never throws, never prints (spec 14.3). */
192
+ export function note(projectDir, message) {
193
+ try {
194
+ const file = path.join(projectDir, LOG_FILE);
195
+ if (!fs.existsSync(path.dirname(file)))
196
+ return;
197
+ if ((fs.statSync(file, { throwIfNoEntry: false })?.size ?? 0) > 256 * 1024)
198
+ fs.rmSync(file);
199
+ fs.appendFileSync(file, `${new Date().toISOString()} ${message.replace(/\s+/g, ' ').slice(0, 2000)}\n`);
200
+ }
201
+ catch {
202
+ // Telemetry never fails a command.
203
+ }
204
+ }
205
+ /** Adds a file inside the project to .git/info/exclude, once. */
206
+ function excludeFromGit(projectDir, file) {
207
+ const rel = path.relative(projectDir, file);
208
+ if (rel.startsWith('..') || path.isAbsolute(rel))
209
+ return;
210
+ addExclude(projectDir, toPosix(rel));
211
+ }
212
+ const DELIVER = fileURLToPath(new URL(`./deliver${path.extname(fileURLToPath(import.meta.url))}`, import.meta.url));
213
+ /**
214
+ * Hands events to the handler without waiting for it (spec 14.3). A command handler gets them in one detached process,
215
+ * which runs the command once for each event, so a hook that sends many events starts one process.
216
+ */
217
+ function deliver(projectDir, send, events) {
218
+ const lines = events.map((event) => JSON.stringify(event));
219
+ if (lines.length === 0)
220
+ return;
221
+ if (typeof send !== 'string') {
222
+ const file = path.resolve(projectDir, send.file);
223
+ const fresh = !fs.existsSync(file);
224
+ fs.mkdirSync(path.dirname(file), { recursive: true });
225
+ fs.appendFileSync(file, `${lines.join('\n')}\n`);
226
+ if (fresh)
227
+ excludeFromGit(projectDir, file);
228
+ return;
229
+ }
230
+ const big = events.findIndex((_, i) => lines[i].length > MAX_EVENT);
231
+ if (big >= 0)
232
+ throw new Error(`a ${String(events[big]['type'])} event of ${lines[big].length} bytes is too large to send`);
233
+ // One environment variable holds the events, one per line. Keep it under MAX_EVENT, so it fits the system's limit.
234
+ const chunks = [];
235
+ for (const line of lines) {
236
+ const last = chunks.at(-1);
237
+ if (last && last.join('\n').length + 1 + line.length <= MAX_EVENT)
238
+ last.push(line);
239
+ else
240
+ chunks.push([line]);
241
+ }
242
+ for (const chunk of chunks) {
243
+ const child = spawn(process.execPath, [DELIVER], {
244
+ cwd: projectDir,
245
+ detached: true,
246
+ stdio: 'ignore',
247
+ env: { ...process.env, HARNESSPM_EVENT: chunk.join('\n'), HARNESSPM_HANDLER: send },
248
+ });
249
+ child.on('error', (error) => note(projectDir, `handler: ${error.message}`));
250
+ child.unref();
251
+ }
252
+ }
253
+ /** Sends one event when telemetry is on and wants this type. Never throws, never waits. */
254
+ export function sendEvent(state, ctx, fields, cwd = process.cwd()) {
255
+ sendEvents(state, ctx, [fields], cwd);
256
+ }
257
+ /** Sends the events that telemetry wants, in one hand-off. Never throws, never waits. */
258
+ export function sendEvents(state, ctx, list, cwd = process.cwd()) {
259
+ const wanted = list.filter((fields) => state.events.has(fields.type));
260
+ if (state.send === undefined || wanted.length === 0)
261
+ return;
262
+ try {
263
+ const known = ctx.repository !== undefined ? ctx : { ...ctx, repository: remoteKey(ctx.projectDir) ?? '' };
264
+ deliver(ctx.projectDir, state.send, wanted.map((fields) => makeEvent(known, fields, cwd)));
265
+ }
266
+ catch (error) {
267
+ note(ctx.projectDir, `${wanted.map((fields) => fields.type).join(', ')} event: ${error.message}`);
268
+ }
269
+ }
270
+ export function readIndex(projectDir) {
271
+ const raw = readJsonQuietly(path.join(projectDir, INDEX_FILE));
272
+ return isRecord(raw) && isRecord(raw['files']) && isRecord(raw['dirs']) && isRecord(raw['skills']) ? raw : undefined;
273
+ }
274
+ /** The unit a file belongs to. A docs file also gets its page, relative to the docs folder. */
275
+ export function unitOfFile(index, file, cwd) {
276
+ const abs = path.resolve(cwd, file);
277
+ const candidates = [abs];
278
+ try {
279
+ const real = fs.realpathSync(abs);
280
+ if (real !== abs)
281
+ candidates.unshift(real);
282
+ }
283
+ catch {
284
+ // A file that is gone can still match by its path.
285
+ }
286
+ for (const p of candidates) {
287
+ const direct = index.files[p];
288
+ if (direct !== undefined)
289
+ return { unit: direct, ...(direct.endsWith(':docs') ? { page: path.basename(p) } : {}) };
290
+ let best;
291
+ for (const dir of Object.keys(index.dirs))
292
+ if (p.startsWith(dir + path.sep) && (best === undefined || dir.length > best.length))
293
+ best = dir;
294
+ if (best !== undefined) {
295
+ const unit = index.dirs[best];
296
+ return { unit, ...(unit.endsWith(':docs') ? { page: toPosix(path.relative(best, p)) } : {}) };
297
+ }
298
+ }
299
+ return undefined;
300
+ }
301
+ /** The always-on rules in the managed block of a workspace's AGENTS.md, by the file's path or real path. */
302
+ function blockUnits(index, file, cwd) {
303
+ const abs = path.resolve(cwd, file);
304
+ let real = abs;
305
+ try {
306
+ real = fs.realpathSync(abs);
307
+ }
308
+ catch {
309
+ // A file that is gone can still match by its path.
310
+ }
311
+ return index.blocks?.[real] ?? index.blocks?.[abs] ?? [];
312
+ }
313
+ /** The events that an agent's hook payload stands for, without the common fields. Usually one; none for other files. */
314
+ export function agentEvents(payload, index) {
315
+ const hook = payload['hook_event_name'];
316
+ const cwd = typeof payload['cwd'] === 'string' ? payload['cwd'] : process.cwd();
317
+ if (hook === 'SessionStart')
318
+ return [{ type: 'session', source: typeof payload['source'] === 'string' ? payload['source'] : undefined }];
319
+ const input = isRecord(payload['tool_input']) ? payload['tool_input'] : {};
320
+ let found;
321
+ let type;
322
+ let via;
323
+ const ofFile = (file, blocks) => {
324
+ const one = unitOfFile(index, file, cwd);
325
+ return one ? [one] : blocks ? blockUnits(index, file, cwd).map((unit) => ({ unit })) : [];
326
+ };
327
+ if (hook === 'PostToolUse' && payload['tool_name'] === 'Read' && typeof input['file_path'] === 'string') {
328
+ // A Read of a workspace's AGENTS.md sends nothing for its block: the Read makes Claude Code load that folder's
329
+ // CLAUDE.md and its import, and that load sends the block's rules, so each is counted once.
330
+ [found, type, via] = [ofFile(input['file_path'], false), 'read', 'tool'];
331
+ }
332
+ else if (hook === 'InstructionsLoaded' && typeof payload['file_path'] === 'string') {
333
+ // A workspace's CLAUDE.md loads with `nested_traversal`, and the AGENTS.md it imports with `include`. The index
334
+ // lists only AGENTS.md, so one load sends each rule once.
335
+ [found, type, via] = [ofFile(payload['file_path'], true), 'read', 'auto'];
336
+ }
337
+ else if (hook === 'PostToolUse' && payload['tool_name'] === 'Skill' && typeof input['skill'] === 'string') {
338
+ const unit = index.skills[input['skill']];
339
+ [found, type] = [unit !== undefined ? [{ unit }] : [], 'skill'];
340
+ }
341
+ else
342
+ return [];
343
+ return found.map(({ unit, page }) => {
344
+ const pkg = index.packages[unit.slice(0, unit.indexOf(':'))];
345
+ return { type, unit, package: pkg?.package, version: pkg?.version, page, via };
346
+ });
347
+ }
348
+ /** The nearest folder with harnesspm.json, as a real path. */
349
+ export function configDir(cwd) {
350
+ for (let dir = path.resolve(cwd);; dir = path.dirname(dir)) {
351
+ if (isFile(path.join(dir, 'harnesspm.json')))
352
+ return fs.realpathSync(dir);
353
+ if (path.dirname(dir) === dir)
354
+ return undefined;
355
+ }
356
+ }
357
+ /**
358
+ * The session of a hook's event (spec 14.4). Claude Code's commands see `CLAUDE_CODE_SESSION_ID`, and `run` events use it,
359
+ * 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`.
360
+ */
361
+ export function hookSession(payload, agent, env = process.env) {
362
+ const fromEnv = agent === 'claude' ? env['CLAUDE_CODE_SESSION_ID'] : undefined;
363
+ if (fromEnv !== undefined && fromEnv !== '')
364
+ return fromEnv;
365
+ return typeof payload['session_id'] === 'string' ? payload['session_id'] : undefined;
366
+ }
367
+ /**
368
+ * `harnesspm track --agent <agent>`: the command of harnesspm's agent hooks. It reads the hook's JSON
369
+ * on stdin, maps it to an event, hands the event off and exits 0 at once. It never prints.
370
+ * `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).
371
+ */
372
+ export function track(args, project) {
373
+ let projectDir;
374
+ try {
375
+ const at = args.indexOf('--agent');
376
+ const agent = at >= 0 ? args[at + 1] : undefined;
377
+ const payload = JSON.parse(fs.readFileSync(0, 'utf8'));
378
+ if (!isRecord(payload))
379
+ return 0;
380
+ const cwd = typeof payload['cwd'] === 'string' ? payload['cwd'] : process.cwd();
381
+ projectDir = project !== undefined ? configDir(project) : configDir(cwd);
382
+ if (projectDir === undefined)
383
+ return 0;
384
+ const state = readTelemetryState(projectDir);
385
+ if (state.send === undefined)
386
+ return 0;
387
+ const index = readIndex(projectDir);
388
+ if (!index)
389
+ return 0;
390
+ const session = hookSession(payload, agent);
391
+ // The index has the remote, so a hook never waits for git.
392
+ const ctx = { projectDir, project: index.project, repository: index.repository ?? '', workspaces: index.workspaces };
393
+ const outside = outsideField(projectDir, cwd);
394
+ sendEvents(state, ctx, agentEvents(payload, index).map(({ type, ...rest }) => ({ type, caller: 'agent', agent, session, ...rest, ...outside })), cwd);
395
+ }
396
+ catch (error) {
397
+ if (projectDir !== undefined)
398
+ note(projectDir, `track: ${error.message}`);
399
+ }
400
+ return 0;
401
+ }
@@ -0,0 +1,30 @@
1
+ import { type AddedHarness } from './added.ts';
2
+ import { claudeHome, codexHome } from './homes.ts';
3
+ /** The user-level `SessionStart` hook: it fetches the added harnesses and rewrites the outputs (spec 7.5). */
4
+ export declare const HOOK_COMMAND = "npx -y @harnesspm/cli update";
5
+ export { claudeHome, codexHome };
6
+ export interface UserReport {
7
+ pending: string[];
8
+ held: string[];
9
+ /** Why the repository's entries are held: what differs from the reviewed state (spec 6.2, rule 4). */
10
+ why?: string;
11
+ /** The repository's entries that this machine lacks and any sync writes, as `branch` records them. */
12
+ unwritten?: {
13
+ entries: string[];
14
+ branch: string;
15
+ };
16
+ }
17
+ /** What `writeUserOutputs` would hold back in a run of the agent's model, without writing anything. */
18
+ export declare function userHeld(added: AddedHarness[]): string[];
19
+ /** Writes rules, docs, skills and executables of user-scope harnesses into the agents' user folders. */
20
+ export declare function writeUserOutputs(added: AddedHarness[], warnings: string[], report?: UserReport): string[];
21
+ /**
22
+ * Turns the hook an older harnesspm installed into today's, in place, where a person already granted it (spec 7.5). It
23
+ * adds no hook. The callers skip runs of the agent's model, because the new command also fetches (spec 6.2, rule 4).
24
+ */
25
+ export declare function migrateSessionHook(): string[];
26
+ /**
27
+ * The user-level SessionStart hook and write access to editable working copies (spec 7.5, 8.5).
28
+ * These widen what agents do, so callers check rule 4 first.
29
+ */
30
+ export declare function writeUserSettings(hook: boolean, writableDirs: string[]): string[];
@@ -0,0 +1,239 @@
1
+ // User-level outputs of added harnesses with user scope (spec 4.4), and the user-level hook.
2
+ import * as fs from 'node:fs';
3
+ import * as path from 'node:path';
4
+ import { caller, harnesspmHome } from './added.js';
5
+ import { applyEntries, desiredEntries, heldEntries, tomlTables } from './exec-outputs.js';
6
+ import { agentsHome, claudeHome, claudeJsonFile, codexHome } from './homes.js';
7
+ import { pathTools } from './outputs.js';
8
+ import { removeBlock, renderSections, sectionsFor, upsertBlock, wrapBlock } from './render.js';
9
+ import { resolve } from './resolve.js';
10
+ import { NPX_ANY, OLD_PACKAGE_NAMES, npxRunner, ensureDir, exists, isDir, isRecord, isSymlink, linkIfChanged, readJsonIfExists, readTextIfExists, realpath, writeIfChanged } from './util.js';
11
+ /** The user-level `SessionStart` hook: it fetches the added harnesses and rewrites the outputs (spec 7.5). */
12
+ export const HOOK_COMMAND = `${NPX_ANY} update`;
13
+ /**
14
+ * Hooks that earlier versions installed, which a sync replaces (spec 7.5, 10.1): 0.14 and earlier synced without fetching,
15
+ * and 0.16 and earlier named the package `@tenphi/harnesspm`.
16
+ */
17
+ const OLD_HOOK_COMMANDS = [`${NPX_ANY} sync`, ...OLD_PACKAGE_NAMES.flatMap((name) => [`npx -y ${name} update`, `npx -y ${name} sync`])];
18
+ const isHookCommand = (command) => command === HOOK_COMMAND || OLD_HOOK_COMMANDS.includes(command ?? '');
19
+ export { claudeHome, codexHome };
20
+ const stateFile = () => path.join(harnesspmHome(), 'state.json');
21
+ function readState() {
22
+ const raw = readJsonIfExists(stateFile());
23
+ const data = isRecord(raw) ? raw : {};
24
+ const list = (key) => (Array.isArray(data[key]) ? data[key].filter((v) => typeof v === 'string') : []);
25
+ return { userLinks: list('userLinks'), claudeDirs: list('claudeDirs') };
26
+ }
27
+ function writeState(state) {
28
+ // Other parts of harnesspm keep their own keys in the same file.
29
+ const raw = readJsonIfExists(stateFile());
30
+ const data = isRecord(raw) ? raw : {};
31
+ ensureDir(path.dirname(stateFile()));
32
+ writeIfChanged(stateFile(), `${JSON.stringify({ ...data, ...state }, null, 2)}\n`);
33
+ }
34
+ const CODEX_BEGIN = '# BEGIN harnesspm (generated by `harnesspm sync`; do not edit)';
35
+ const CODEX_END = '# END harnesspm';
36
+ /** Puts MCP servers into a managed block at the end of ~/.codex/config.toml. */
37
+ function writeCodexBlock(servers) {
38
+ const file = path.join(codexHome(), 'config.toml');
39
+ const text = readTextIfExists(file) ?? '';
40
+ const lines = text.split('\n');
41
+ const start = lines.indexOf(CODEX_BEGIN);
42
+ const end = start >= 0 ? lines.indexOf(CODEX_END, start) : -1;
43
+ const kept = start >= 0 && end >= 0 ? [...lines.slice(0, start), ...lines.slice(end + 1)] : lines;
44
+ while (kept.length > 0 && kept[kept.length - 1] === '')
45
+ kept.pop();
46
+ const block = Object.keys(servers).length > 0 ? [CODEX_BEGIN, tomlTables('mcp_servers', servers), CODEX_END] : [];
47
+ const next = [...kept, ...(kept.length > 0 && block.length > 0 ? [''] : []), ...block].join('\n');
48
+ if (next.trim() === '') {
49
+ if (text === '')
50
+ return false;
51
+ fs.rmSync(file, { force: true });
52
+ return true;
53
+ }
54
+ return writeIfChanged(file, `${next}\n`);
55
+ }
56
+ function resolveUser(added) {
57
+ const user = added.filter((h) => h.scope === 'user').map(({ entry: _entry, ...rest }) => rest);
58
+ return resolve(harnesspmHome(), { team: false, added: user });
59
+ }
60
+ /** Hooks, permissions, MCP servers and sub-agents of user-scope harnesses (spec 4.4). Adding a harness trusts it. */
61
+ function userEntries(res) {
62
+ // User-level files serve every repository, so they start harnesspm through npx.
63
+ return desiredEntries(res, new Set(res.packages), () => ({ trusted: true }), {
64
+ claudeAgents: path.join(claudeHome(), 'agents'),
65
+ codexAgents: path.join(codexHome(), 'agents'),
66
+ npx: () => [NPX_ANY],
67
+ runner: () => npxRunner(NPX_ANY),
68
+ });
69
+ }
70
+ /** What `writeUserOutputs` would hold back in a run of the agent's model, without writing anything. */
71
+ export function userHeld(added) {
72
+ if (!added.some((h) => h.scope === 'user'))
73
+ return [];
74
+ return heldEntries('added', userEntries(resolveUser(added)), stateFile());
75
+ }
76
+ /** Writes rules, docs, skills and executables of user-scope harnesses into the agents' user folders. */
77
+ export function writeUserOutputs(added, warnings, report = { pending: [], held: [] }) {
78
+ const home = harnesspmHome();
79
+ ensureDir(home);
80
+ const res = resolveUser(added);
81
+ warnings.push(...res.warnings);
82
+ const generatedRoot = path.join(home, 'generated', 'user');
83
+ const generated = new Map();
84
+ // The working copies and caches live in harnesspm's home, which resolves as the project here, so every path is shown in full.
85
+ const tools = pathTools(res, () => generatedRoot, generated, warnings, { absolute: true });
86
+ for (const rule of res.rules)
87
+ if (rule.activation !== 'always' && rule.patches.length > 0)
88
+ generated.set(tools.generatedRule(rule), rule.text);
89
+ const content = renderSections(sectionsFor(res, res.packages, tools.paths, () => NPX_ANY), tools.paths);
90
+ const changed = [];
91
+ fs.rmSync(generatedRoot, { recursive: true, force: true });
92
+ for (const [file, text] of generated)
93
+ writeIfChanged(file, text);
94
+ for (const file of [path.join(claudeHome(), 'CLAUDE.md'), path.join(codexHome(), 'AGENTS.md')]) {
95
+ const existing = readTextIfExists(file);
96
+ const next = content !== '' ? upsertBlock(existing, wrapBlock(content)) : removeBlock(existing);
97
+ if (next === undefined) {
98
+ if (existing !== undefined && existing.includes('BEGIN:harnesspm')) {
99
+ fs.rmSync(file);
100
+ changed.push(file);
101
+ }
102
+ }
103
+ else if (writeIfChanged(file, next))
104
+ changed.push(file);
105
+ }
106
+ // Skills: ~/.claude/skills and ~/.agents/skills, once when one links to the other.
107
+ const state = readState();
108
+ const links = new Map();
109
+ const seen = new Set();
110
+ for (const root of [path.join(claudeHome(), 'skills'), path.join(agentsHome(), 'skills')]) {
111
+ const real = isDir(root) ? realpath(root) : root;
112
+ if (seen.has(real))
113
+ continue;
114
+ seen.add(real);
115
+ for (const skill of res.skills) {
116
+ const link = path.join(root, skill.name);
117
+ if (exists(link) && !isSymlink(link))
118
+ warnings.push(`${link} exists and is not a harnesspm link; left as it is`);
119
+ else
120
+ links.set(link, skill.dir);
121
+ }
122
+ }
123
+ for (const [link, target] of links)
124
+ if (linkIfChanged(link, target))
125
+ changed.push(link);
126
+ for (const old of state.userLinks) {
127
+ if (!links.has(old) && isSymlink(old)) {
128
+ fs.unlinkSync(old);
129
+ changed.push(old);
130
+ }
131
+ }
132
+ writeState({ ...state, userLinks: [...links.keys()].sort() });
133
+ const entries = userEntries(res);
134
+ warnings.push(...entries.warnings);
135
+ const applied = applyEntries('added', entries, {
136
+ claudeSettings: path.join(claudeHome(), 'settings.json'),
137
+ claudeJson: claudeJsonFile(),
138
+ codexHooks: path.join(codexHome(), 'hooks.json'),
139
+ codexRules: path.join(codexHome(), 'rules', 'harnesspm.rules'),
140
+ stateFile: stateFile(),
141
+ }, caller() !== 'model');
142
+ changed.push(...applied.changed);
143
+ if (writeCodexBlock(applied.codexMcp))
144
+ changed.push(path.join(codexHome(), 'config.toml'));
145
+ report.pending.push(...entries.pending);
146
+ report.held.push(...applied.held);
147
+ return changed;
148
+ }
149
+ function editJson(file, edit) {
150
+ const raw = readJsonIfExists(file);
151
+ const data = isRecord(raw) ? raw : {};
152
+ const before = JSON.stringify(data);
153
+ edit(data);
154
+ if (JSON.stringify(data) === before)
155
+ return false;
156
+ // A settings file that held only harnesspm's entries goes away with them.
157
+ if (Object.keys(data).length === 0 || (Object.keys(data).length === 1 && isRecord(data['hooks']) && Object.keys(data['hooks']).length === 0)) {
158
+ fs.rmSync(file, { force: true });
159
+ return true;
160
+ }
161
+ ensureDir(path.dirname(file));
162
+ fs.writeFileSync(file, `${JSON.stringify(data, null, 2)}\n`);
163
+ return true;
164
+ }
165
+ function setSessionHook(hooks, on) {
166
+ const groups = (Array.isArray(hooks['SessionStart']) ? hooks['SessionStart'] : []);
167
+ const ours = (g) => (g.hooks ?? []).some((h) => isHookCommand(h.command));
168
+ const rest = groups.filter((g) => !ours(g));
169
+ const next = on ? [...rest, { hooks: [{ type: 'command', command: HOOK_COMMAND, timeout: 120 }] }] : rest;
170
+ if (next.length > 0)
171
+ hooks['SessionStart'] = next;
172
+ else
173
+ delete hooks['SessionStart'];
174
+ }
175
+ /**
176
+ * Turns the hook an older harnesspm installed into today's, in place, where a person already granted it (spec 7.5). It
177
+ * adds no hook. The callers skip runs of the agent's model, because the new command also fetches (spec 6.2, rule 4).
178
+ */
179
+ export function migrateSessionHook() {
180
+ const changed = [];
181
+ for (const file of [path.join(claudeHome(), 'settings.json'), path.join(codexHome(), 'hooks.json')]) {
182
+ if (!exists(file))
183
+ continue;
184
+ const did = editJson(file, (data) => {
185
+ const hooks = isRecord(data['hooks']) ? data['hooks'] : undefined;
186
+ const groups = hooks !== undefined && Array.isArray(hooks['SessionStart']) ? hooks['SessionStart'] : [];
187
+ for (const group of groups)
188
+ for (const hook of group.hooks ?? [])
189
+ if (OLD_HOOK_COMMANDS.includes(hook.command ?? ''))
190
+ hook.command = HOOK_COMMAND;
191
+ });
192
+ if (did)
193
+ changed.push(file);
194
+ }
195
+ return changed;
196
+ }
197
+ /**
198
+ * The user-level SessionStart hook and write access to editable working copies (spec 7.5, 8.5).
199
+ * These widen what agents do, so callers check rule 4 first.
200
+ */
201
+ export function writeUserSettings(hook, writableDirs) {
202
+ const changed = [];
203
+ const state = readState();
204
+ const claudeSettings = path.join(claudeHome(), 'settings.json');
205
+ const didClaude = editJson(claudeSettings, (data) => {
206
+ const hooks = isRecord(data['hooks']) ? data['hooks'] : {};
207
+ setSessionHook(hooks, hook);
208
+ if (Object.keys(hooks).length > 0)
209
+ data['hooks'] = hooks;
210
+ else
211
+ delete data['hooks'];
212
+ const permissions = isRecord(data['permissions']) ? data['permissions'] : {};
213
+ const current = Array.isArray(permissions['additionalDirectories']) ? permissions['additionalDirectories'].filter((d) => typeof d === 'string') : [];
214
+ const kept = current.filter((d) => !state.claudeDirs.includes(d) || writableDirs.includes(d));
215
+ const dirs = [...new Set([...kept, ...writableDirs])];
216
+ if (dirs.length > 0)
217
+ permissions['additionalDirectories'] = dirs;
218
+ else
219
+ delete permissions['additionalDirectories'];
220
+ if (Object.keys(permissions).length > 0)
221
+ data['permissions'] = permissions;
222
+ else
223
+ delete data['permissions'];
224
+ });
225
+ if (didClaude)
226
+ changed.push(claudeSettings);
227
+ const codexHooks = path.join(codexHome(), 'hooks.json');
228
+ if (hook || exists(codexHooks)) {
229
+ const didCodex = editJson(codexHooks, (data) => {
230
+ const hooks = isRecord(data['hooks']) ? data['hooks'] : {};
231
+ setSessionHook(hooks, hook);
232
+ data['hooks'] = hooks;
233
+ });
234
+ if (didCodex)
235
+ changed.push(codexHooks);
236
+ }
237
+ writeState({ ...state, claudeDirs: writableDirs });
238
+ return changed;
239
+ }