@harnesspm/cli 0.0.1 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/CHANGELOG.md +275 -0
  2. package/LICENSE +1 -1
  3. package/README.md +71 -3
  4. package/dist/added.d.ts +51 -0
  5. package/dist/added.js +192 -0
  6. package/dist/check.d.ts +14 -0
  7. package/dist/check.js +263 -0
  8. package/dist/cli.d.ts +2 -0
  9. package/dist/cli.js +230 -0
  10. package/dist/commands.d.ts +68 -0
  11. package/dist/commands.js +1441 -0
  12. package/dist/config.d.ts +15 -0
  13. package/dist/config.js +45 -0
  14. package/dist/deliver.d.ts +1 -0
  15. package/dist/deliver.js +31 -0
  16. package/dist/doctor.d.ts +18 -0
  17. package/dist/doctor.js +99 -0
  18. package/dist/exec-outputs.d.ts +77 -0
  19. package/dist/exec-outputs.js +426 -0
  20. package/dist/exec-units.d.ts +68 -0
  21. package/dist/exec-units.js +151 -0
  22. package/dist/fetch.d.ts +16 -0
  23. package/dist/fetch.js +145 -0
  24. package/dist/frontmatter.d.ts +16 -0
  25. package/dist/frontmatter.js +49 -0
  26. package/dist/homes.d.ts +7 -0
  27. package/dist/homes.js +21 -0
  28. package/dist/lock.d.ts +47 -0
  29. package/dist/lock.js +245 -0
  30. package/dist/manifest.d.ts +78 -0
  31. package/dist/manifest.js +169 -0
  32. package/dist/new.d.ts +33 -0
  33. package/dist/new.js +228 -0
  34. package/dist/outputs.d.ts +124 -0
  35. package/dist/outputs.js +875 -0
  36. package/dist/parent.d.ts +41 -0
  37. package/dist/parent.js +182 -0
  38. package/dist/render.d.ts +91 -0
  39. package/dist/render.js +221 -0
  40. package/dist/resolve.d.ts +132 -0
  41. package/dist/resolve.js +522 -0
  42. package/dist/reviewed.d.ts +15 -0
  43. package/dist/reviewed.js +41 -0
  44. package/dist/run.d.ts +18 -0
  45. package/dist/run.js +133 -0
  46. package/dist/sections.d.ts +32 -0
  47. package/dist/sections.js +121 -0
  48. package/dist/start.d.ts +18 -0
  49. package/dist/start.js +136 -0
  50. package/dist/telemetry-api.d.ts +26 -0
  51. package/dist/telemetry-api.js +60 -0
  52. package/dist/telemetry.d.ts +119 -0
  53. package/dist/telemetry.js +401 -0
  54. package/dist/user-outputs.d.ts +30 -0
  55. package/dist/user-outputs.js +239 -0
  56. package/dist/util.d.ts +137 -0
  57. package/dist/util.js +370 -0
  58. package/dist/workspaces.d.ts +2 -0
  59. package/dist/workspaces.js +62 -0
  60. package/docs/spec/01-overview.md +156 -0
  61. package/docs/spec/02-package-format.md +252 -0
  62. package/docs/spec/03-resolution.md +108 -0
  63. package/docs/spec/04-outputs.md +194 -0
  64. package/docs/spec/05-executables.md +170 -0
  65. package/docs/spec/06-trust.md +88 -0
  66. package/docs/spec/07-added.md +109 -0
  67. package/docs/spec/08-improving.md +79 -0
  68. package/docs/spec/09-cloud.md +68 -0
  69. package/docs/spec/10-cli.md +215 -0
  70. package/docs/spec/11-standards.md +52 -0
  71. package/docs/spec/12-dogfooding.md +51 -0
  72. package/docs/spec/13-open-questions.md +97 -0
  73. package/docs/spec/14-telemetry.md +199 -0
  74. package/docs/spec/README.md +33 -0
  75. package/harness/dev.harnesspm/rules/generated-files.md +9 -0
  76. package/harness/dev.harnesspm/rules/harnesspm-config.md +12 -0
  77. package/harness/plugin.json +13 -0
  78. package/harness/skills/harnesspm-export/SKILL.md +43 -0
  79. package/harness/skills/harnesspm-import/SKILL.md +32 -0
  80. package/harness/skills/harnesspm-improve/SKILL.md +38 -0
  81. package/package.json +66 -11
  82. package/schema/harnesspm.schema.json +58 -0
  83. package/index.js +0 -4
@@ -0,0 +1,426 @@
1
+ // Executable outputs (spec 4.3, 4.4, 5.2–5.4) with trust (spec 6.2) and ownership of shared files (spec 4.7).
2
+ import * as fs from 'node:fs';
3
+ import * as path from 'node:path';
4
+ import { stringify } from 'yaml';
5
+ import { AGENTS, WIDENING_AGENT_KEYS } from './exec-units.js';
6
+ import { tomlString } from './render.js';
7
+ import { skillAuthor } from './resolve.js';
8
+ import { NPX_ANY, PACKAGE_NAMES, ensureDir, isFile, isRecord, readJsonIfExists, readTextIfExists, writeIfChanged } from './util.js';
9
+ /** Trust of a package's executable units (spec 6.2). The project and added harnesses are trusted. */
10
+ export function trustOf(pkg, res, lock) {
11
+ if (pkg.layer !== 'dependencies')
12
+ return { trusted: true };
13
+ const value = res.config.trust[pkg.name];
14
+ if (value === true)
15
+ return { trusted: true };
16
+ if (value === 'pin') {
17
+ const approved = lock?.packages[pkg.name]?.approved;
18
+ if (approved === undefined || approved === pkg.version)
19
+ return { trusted: true };
20
+ return { trusted: false, reason: `version ${pkg.version} is not approved; approved: ${approved}`, action: `A person runs \`${NPX_ANY} approve ${pkg.name}\`.` };
21
+ }
22
+ // Trust is the person's decision (spec 6.2). The action says who acts, so an agent does not take it as its next step.
23
+ return { trusted: false, reason: 'not trusted', action: `A person adds "${pkg.name}": true to "trust" in harnesspm.json, then runs \`${NPX_ANY} approve\`.` };
24
+ }
25
+ export function emptyEntries() {
26
+ return { claude: { allow: [], deny: [], ask: [], hooks: [], mcp: {} }, codex: { hooks: [], rules: [], mcp: {} }, agentFiles: new Map(), pending: [], warnings: [] };
27
+ }
28
+ function tomlValue(value) {
29
+ if (typeof value === 'string')
30
+ return JSON.stringify(value);
31
+ if (typeof value === 'number' || typeof value === 'boolean')
32
+ return String(value);
33
+ if (Array.isArray(value)) {
34
+ const items = value.map(tomlValue);
35
+ return items.every((i) => i !== undefined) ? `[${items.join(', ')}]` : undefined;
36
+ }
37
+ if (isRecord(value)) {
38
+ const items = Object.entries(value).map(([k, v]) => [k, tomlValue(v)]);
39
+ return items.every(([, v]) => v !== undefined) ? `{ ${items.map(([k, v]) => `${JSON.stringify(k)} = ${v}`).join(', ')} }` : undefined;
40
+ }
41
+ return undefined;
42
+ }
43
+ export function tomlTables(prefix, tables) {
44
+ return Object.entries(tables)
45
+ .map(([name, table]) => {
46
+ const lines = Object.entries(table).flatMap(([k, v]) => {
47
+ const value = tomlValue(v);
48
+ return value === undefined ? [] : [`${k} = ${value}`];
49
+ });
50
+ return `[${prefix}.${JSON.stringify(name)}]\n${lines.join('\n')}`;
51
+ })
52
+ .join('\n\n');
53
+ }
54
+ /** Words of a command prefix, for Claude Code's Bash rules. */
55
+ const bashRule = (words) => `Bash(${words.join(' ')} *)`;
56
+ const codexRule = (words, decision) => `prefix_rule(pattern = ${JSON.stringify(words)}, decision = "${decision}")`;
57
+ /**
58
+ * The entries that `packages` ask for. `npx` lists the prefixes that the agent types: `npx -y @harnesspm/cli`, and
59
+ * for a project's scripts also the bare `npx harnesspm`, which some packages' text still types. Allow rules use them, so they match the
60
+ * command. `runner`
61
+ * starts hooks and MCP servers, which nobody types, so it can start the installed CLI file, which is faster (spec 5.2).
62
+ */
63
+ export function desiredEntries(res, packages, trust, where) {
64
+ const entries = emptyEntries();
65
+ const mine = (units) => units.filter((u) => packages.has(u.pkg));
66
+ const pendingCounts = new Map();
67
+ const pend = (pkg, what) => {
68
+ const counts = pendingCounts.get(pkg) ?? new Map();
69
+ counts.set(what, (counts.get(what) ?? 0) + 1);
70
+ pendingCounts.set(pkg, counts);
71
+ };
72
+ // A replaced skill runs the files of the package that replaced it, so that package's trust decides (spec 6.1).
73
+ for (const skill of mine(res.skills)) {
74
+ const author = skillAuthor(skill);
75
+ if (author === undefined || trust(author).trusted)
76
+ entries.claude.allow.push(`Skill(${skill.name})`);
77
+ }
78
+ for (const script of mine(res.scripts)) {
79
+ if (!trust(script.pkg).trusted) {
80
+ pend(script.pkg, 'script');
81
+ continue;
82
+ }
83
+ if (!script.allow)
84
+ continue;
85
+ for (const npx of where.npx(script.pkg)) {
86
+ const words = [...npx.split(' '), 'run', `${script.pkg.plugin}:${script.name}`];
87
+ // `Bash(<prefix> *)` also matches the command without arguments (observed with Claude Code 2.1.322).
88
+ entries.claude.allow.push(bashRule(words));
89
+ entries.codex.rules.push(codexRule(words, 'allow'));
90
+ }
91
+ }
92
+ for (const hook of mine(res.hooks)) {
93
+ if (!trust(hook.pkg).trusted) {
94
+ pend(hook.pkg, 'hook');
95
+ continue;
96
+ }
97
+ for (const agent of AGENTS) {
98
+ if (!(agent in hook.matchers))
99
+ continue;
100
+ const matcher = hook.matchers[agent];
101
+ const entry = {
102
+ event: hook.event,
103
+ ...(matcher !== undefined ? { matcher } : {}),
104
+ command: `${where.runner(hook.pkg).shell} run --agent ${agent} ${hook.pkg.plugin}:${hook.run}`,
105
+ ...(hook.timeout !== undefined ? { timeout: hook.timeout } : {}),
106
+ };
107
+ entries[agent].hooks.push(entry);
108
+ }
109
+ }
110
+ for (const server of mine(res.mcp)) {
111
+ if (!trust(server.pkg).trusted) {
112
+ pend(server.pkg, 'MCP server');
113
+ continue;
114
+ }
115
+ const name = `${server.pkg.plugin}-${server.name}`;
116
+ const type = server.config['type'];
117
+ for (const agent of AGENTS) {
118
+ let config;
119
+ if (type === 'stdio') {
120
+ const [command, ...prefix] = where.runner(server.pkg).argv;
121
+ config = { command, args: [...prefix, 'mcp', '--agent', agent, `${server.pkg.plugin}:${server.name}`] };
122
+ if (agent === 'claude')
123
+ config = { type: 'stdio', ...config };
124
+ }
125
+ else if (agent === 'claude') {
126
+ config = { type: type === 'sse' ? 'sse' : 'http', url: server.config['url'], ...(isRecord(server.config['headers']) ? { headers: server.config['headers'] } : {}) };
127
+ }
128
+ else if (type === 'streamable-http') {
129
+ config = { url: server.config['url'], ...(isRecord(server.config['headers']) ? { http_headers: server.config['headers'] } : {}) };
130
+ }
131
+ else
132
+ entries.warnings.push(`${server.id}: Codex has no SSE transport, so the server is written for Claude Code only`);
133
+ if (config)
134
+ entries[agent].mcp[name] = config;
135
+ }
136
+ entries.claude.allow.push(`mcp__${name}`);
137
+ }
138
+ for (const perms of mine(res.permissions)) {
139
+ for (const words of perms.deny) {
140
+ entries.claude.deny.push(bashRule(words));
141
+ entries.codex.rules.push(codexRule(words, 'forbidden'));
142
+ }
143
+ for (const words of perms.ask) {
144
+ entries.claude.ask.push(bashRule(words));
145
+ entries.codex.rules.push(codexRule(words, 'prompt'));
146
+ }
147
+ }
148
+ // Sub-agents are text, but some agent-specific keys widen what the agent may do (spec 2.6).
149
+ for (const agentUnit of mine(res.agents)) {
150
+ const trusted = trust(agentUnit.pkg).trusted;
151
+ const keys = (agent) => {
152
+ const source = agent === 'claude' ? agentUnit.claude : agentUnit.codex;
153
+ const result = {};
154
+ for (const [key, value] of Object.entries(source)) {
155
+ if (!trusted && WIDENING_AGENT_KEYS[agent].includes(key))
156
+ entries.warnings.push(`${agentUnit.id}: "${key}" is left out, because ${agentUnit.pkg.name} is not trusted`);
157
+ else
158
+ result[key] = value;
159
+ }
160
+ return result;
161
+ };
162
+ const note = `Generated by harnesspm from ${agentUnit.id}. To change it, run \`${NPX_ANY} why ${agentUnit.id}\`.`;
163
+ const front = stringify({ name: agentUnit.name, description: agentUnit.description, ...keys('claude') }).trimEnd();
164
+ entries.agentFiles.set(path.join(where.claudeAgents, `${agentUnit.name}.md`), `---\n${front}\n---\n\n<!-- ${note} -->\n\n${agentUnit.body}\n`);
165
+ const codexKeys = Object.entries(keys('codex')).flatMap(([k, v]) => {
166
+ const value = tomlValue(v);
167
+ return value === undefined ? [] : [`${k} = ${value}`];
168
+ });
169
+ entries.agentFiles.set(path.join(where.codexAgents, `${agentUnit.name}.toml`), `# ${note}\nname = ${JSON.stringify(agentUnit.name)}\ndescription = ${JSON.stringify(agentUnit.description)}\n${codexKeys.map((l) => `${l}\n`).join('')}developer_instructions = ${tomlString(agentUnit.body)}\n`);
170
+ }
171
+ for (const [pkg, counts] of pendingCounts) {
172
+ const what = [...counts].map(([kind, n]) => `${n} ${kind}${n === 1 ? '' : 's'}`).join(', ');
173
+ const state = trust(pkg);
174
+ entries.pending.push(`${pkg.name}: ${what} (${state.reason}). ${state.action}`);
175
+ }
176
+ return entries;
177
+ }
178
+ const emptyOwned = () => ({ claude: { allow: [], deny: [], ask: [], hooks: [], mcp: [] }, codex: { hooks: [], mcp: {}, rules: [] }, agentFiles: [] });
179
+ function readOwned(stateFile) {
180
+ const raw = readJsonIfExists(stateFile);
181
+ return isRecord(raw) && isRecord(raw['exec']) ? raw['exec'] : {};
182
+ }
183
+ function writeOwned(stateFile, state) {
184
+ const raw = readJsonIfExists(stateFile);
185
+ const data = isRecord(raw) ? raw : {};
186
+ data['exec'] = state;
187
+ ensureDir(path.dirname(stateFile));
188
+ writeIfChanged(stateFile, `${JSON.stringify(data, null, 2)}\n`);
189
+ }
190
+ const hookKey = (h) => `${h.event}\u0000${h.matcher ?? ''}\u0000${h.command}`;
191
+ /** The package names as one regular expression group, such as `(?:@harnesspm\/cli|@tenphi\/harnesspm)`. */
192
+ const NAMES = `(?:${PACKAGE_NAMES.map((n) => n.replaceAll('/', String.raw `\/`)).join('|')})`;
193
+ /**
194
+ * What a hook command of harnesspm runs, without the runner prefix, such as `harnesspm run --agent claude kit:check`.
195
+ * The prefix is one of the forms that `runner` writes, matched as whole shell words: the bare `npx harnesspm` that earlier versions wrote,
196
+ * `npx -y @harnesspm/cli`, `node` with the installed CLI file, or the project's `.bin/harnesspm` that 0.5.0 wrote. The
197
+ * earlier package name, `@tenphi/harnesspm`, counts too, until 1.0 (spec 10.1). A path is quoted when it needs it.
198
+ */
199
+ const LOCAL_CLI = String.raw `\/node_modules\/(?:\.bin\/harnesspm|${NAMES}\/[\w./-]+\.js)`;
200
+ const RUNNER_PREFIX = new RegExp(String.raw `^(?:npx harnesspm|npx -y ${NAMES}|(?:node )?(?:[\w@%+=:,./-]*${LOCAL_CLI}|'(?:[^']|'\\'')*${LOCAL_CLI}')) `);
201
+ const hookTask = (command) => command.replace(RUNNER_PREFIX, 'harnesspm ');
202
+ /** What a hook grants. A new runner prefix, such as the installed CLI file in place of npx, grants nothing new. */
203
+ const grantKey = (h) => `${h.event}\u0000${h.matcher ?? ''}\u0000${hookTask(h.command)}`;
204
+ /** Keeps what a model run may keep: entries it already had. Returns the entries and what is held back. */
205
+ function limit(wanted, had, key, widen) {
206
+ if (widen)
207
+ return { kept: wanted, held: [] };
208
+ const before = new Set(had.map(key));
209
+ return { kept: wanted.filter((w) => before.has(key(w))), held: wanted.filter((w) => !before.has(key(w))) };
210
+ }
211
+ const isAllowRule = (rule) => rule.includes('decision = "allow"');
212
+ /**
213
+ * What an allow rule grants. The npx prefixes run the same unit, so the form that tool lines use now,
214
+ * `npx -y @harnesspm/cli run`, grants nothing new where `npx harnesspm run` or the earlier
215
+ * `npx -y @tenphi/harnesspm run` was allowed, until 1.0 (spec 5.4, 10.1).
216
+ */
217
+ const ALLOW_NPX = new RegExp(String.raw `npx -y ${NAMES} run `);
218
+ const ALLOW_WORDS = new RegExp(String.raw `\["npx","-y","${NAMES}","run",`);
219
+ const allowKey = (rule) => rule.replace(ALLOW_NPX, 'npx harnesspm run ').replace(ALLOW_WORDS, '["npx","harnesspm","run",');
220
+ /** A Codex rule as the words it matches, such as `npx harnesspm run kit:probe`. */
221
+ function ruleWords(rule) {
222
+ try {
223
+ return JSON.parse(/pattern = (\[.*?\]), decision/.exec(rule)?.[1] ?? '').join(' ');
224
+ }
225
+ catch {
226
+ return rule;
227
+ }
228
+ }
229
+ /**
230
+ * The widening entries that a run may write: all of them for a person, a setup script or a hook, and for the agent's
231
+ * model only those it had before (spec 6.2, rule 4). `held` names the rest. `sync` writes with it, and `status` and
232
+ * `doctor` preview it, so all three list the same entries.
233
+ */
234
+ function widening(entries, prev, widen) {
235
+ const allow = limit(entries.claude.allow, prev.claude.allow, allowKey, widen);
236
+ const claudeHooks = limit(entries.claude.hooks, prev.claude.hooks, grantKey, widen);
237
+ const claudeMcpNames = limit(Object.keys(entries.claude.mcp), prev.claude.mcp, (s) => s, widen);
238
+ const codexHooks = limit(entries.codex.hooks, prev.codex.hooks, grantKey, widen);
239
+ const codexMcpNames = limit(Object.keys(entries.codex.mcp), Object.keys(prev.codex.mcp), (s) => s, widen);
240
+ const codexAllow = limit(entries.codex.rules.filter(isAllowRule), prev.codex.rules.filter(isAllowRule), allowKey, widen);
241
+ const held = [
242
+ ...allow.held.map((a) => `allow ${a}`),
243
+ ...claudeHooks.held.map((h) => `Claude Code hook: ${hookTask(h.command)}`),
244
+ ...claudeMcpNames.held.map((n) => `Claude Code MCP server ${n}`),
245
+ ...codexHooks.held.map((h) => `Codex hook: ${hookTask(h.command)}`),
246
+ ...codexMcpNames.held.map((n) => `Codex MCP server ${n}`),
247
+ ...codexAllow.held.map((r) => `Codex allow rule: ${ruleWords(r)}`),
248
+ ];
249
+ return { allow, claudeHooks, claudeMcpNames, codexHooks, codexMcpNames, codexAllow, held };
250
+ }
251
+ /**
252
+ * Replaces the owned hook entries in an agent's hooks object. An entry that is there already is not added again, so a
253
+ * state file that is missing, such as the first one of a project below the git root, never doubles a hook.
254
+ */
255
+ function mergeHooks(hooks, previous, next) {
256
+ // An owned entry that stays keeps its place, so several owners of one file, such as the projects below a parent
257
+ // folder (spec 4.10), do not move each other's entries on every sync.
258
+ const wanted = new Map(next.map((entry) => [hookKey(entry), entry]));
259
+ const owned = new Set(previous.map(hookKey));
260
+ const handlerOf = (entry) => ({ type: 'command', command: entry.command, ...(entry.timeout !== undefined ? { timeout: entry.timeout } : {}), ...(entry.async ? { async: true } : {}) });
261
+ const keyOf = (event, g, h) => hookKey({ event, ...(g.matcher !== undefined ? { matcher: g.matcher } : {}), command: h.command ?? '' });
262
+ const result = {};
263
+ const present = new Set();
264
+ for (const [event, groups] of Object.entries(hooks)) {
265
+ const kept = groups
266
+ .map((g) => ({
267
+ ...g,
268
+ hooks: (g.hooks ?? [])
269
+ .filter((h) => !owned.has(keyOf(event, g, h)) || wanted.has(keyOf(event, g, h)))
270
+ .map((h) => (owned.has(keyOf(event, g, h)) ? handlerOf(wanted.get(keyOf(event, g, h))) : h)),
271
+ }))
272
+ .filter((g) => g.hooks.length > 0);
273
+ for (const g of kept)
274
+ for (const h of g.hooks)
275
+ present.add(keyOf(event, g, h));
276
+ if (kept.length > 0)
277
+ result[event] = kept;
278
+ }
279
+ for (const entry of next) {
280
+ if (present.has(hookKey(entry)))
281
+ continue;
282
+ present.add(hookKey(entry));
283
+ const list = (result[entry.event] ??= []);
284
+ list.push({ ...(entry.matcher !== undefined ? { matcher: entry.matcher } : {}), hooks: [handlerOf(entry)] });
285
+ }
286
+ return result;
287
+ }
288
+ function editJson(file, edit) {
289
+ const raw = readJsonIfExists(file);
290
+ const data = isRecord(raw) ? raw : {};
291
+ const before = JSON.stringify(data);
292
+ edit(data);
293
+ if (JSON.stringify(data) === before)
294
+ return false;
295
+ if (Object.keys(data).length === 0) {
296
+ fs.rmSync(file, { force: true });
297
+ return true;
298
+ }
299
+ ensureDir(path.dirname(file));
300
+ fs.writeFileSync(file, `${JSON.stringify(data, null, 2)}\n`);
301
+ return true;
302
+ }
303
+ function setList(holder, key, previous, next) {
304
+ const current = Array.isArray(holder[key]) ? holder[key].filter((v) => typeof v === 'string') : [];
305
+ const kept = current.filter((v) => !previous.includes(v));
306
+ const result = [...kept, ...next.filter((v) => !kept.includes(v))];
307
+ if (result.length > 0)
308
+ holder[key] = result;
309
+ else
310
+ delete holder[key];
311
+ }
312
+ /** The entries that a sync by the agent's model would hold back now, without writing anything. */
313
+ export function heldEntries(group, entries, stateFile) {
314
+ return widening(entries, readOwned(stateFile)[group] ?? emptyOwned(), false).held;
315
+ }
316
+ export function applyEntries(group, entries, targets, widen) {
317
+ const state = readOwned(targets.stateFile);
318
+ const prev = state[group] ?? emptyOwned();
319
+ const writeClaude = targets.writeClaude !== false;
320
+ const writeCodex = targets.writeCodex !== false;
321
+ const changed = [];
322
+ const files = [];
323
+ const { allow, claudeHooks, claudeMcpNames, codexHooks, codexMcpNames, codexAllow, held } = widening(entries, prev, widen);
324
+ // A model run never removes a restriction either.
325
+ const keepRestrictions = (next, before) => (widen ? next : [...new Set([...next, ...before])]);
326
+ const deny = keepRestrictions(entries.claude.deny, prev.claude.deny);
327
+ const ask = keepRestrictions(entries.claude.ask, prev.claude.ask);
328
+ const codexRestrict = keepRestrictions(entries.codex.rules.filter((r) => !isAllowRule(r)), prev.codex.rules.filter((r) => !isAllowRule(r)));
329
+ // Claude Code settings: permissions and hooks.
330
+ if (writeClaude &&
331
+ editJson(targets.claudeSettings, (data) => {
332
+ const permissions = isRecord(data['permissions']) ? data['permissions'] : {};
333
+ setList(permissions, 'allow', prev.claude.allow, allow.kept);
334
+ setList(permissions, 'deny', prev.claude.deny, deny);
335
+ setList(permissions, 'ask', prev.claude.ask, ask);
336
+ if (Object.keys(permissions).length > 0)
337
+ data['permissions'] = permissions;
338
+ else
339
+ delete data['permissions'];
340
+ const hooks = mergeHooks(isRecord(data['hooks']) ? data['hooks'] : {}, prev.claude.hooks, claudeHooks.kept);
341
+ if (Object.keys(hooks).length > 0)
342
+ data['hooks'] = hooks;
343
+ else
344
+ delete data['hooks'];
345
+ }))
346
+ changed.push(targets.claudeSettings);
347
+ if (isFile(targets.claudeSettings))
348
+ files.push(targets.claudeSettings);
349
+ // Claude Code MCP servers: ~/.claude.json, at user scope or in the project's local scope.
350
+ const claudeMcp = Object.fromEntries(claudeMcpNames.kept.map((n) => [n, entries.claude.mcp[n]]));
351
+ if (writeClaude && (Object.keys(claudeMcp).length > 0 || prev.claude.mcp.length > 0)) {
352
+ if (editJson(targets.claudeJson, (data) => {
353
+ let holder = data;
354
+ if (targets.claudeProject !== undefined) {
355
+ const projects = isRecord(data['projects']) ? data['projects'] : {};
356
+ holder = isRecord(projects[targets.claudeProject]) ? projects[targets.claudeProject] : {};
357
+ projects[targets.claudeProject] = holder;
358
+ data['projects'] = projects;
359
+ }
360
+ const servers = isRecord(holder['mcpServers']) ? holder['mcpServers'] : {};
361
+ for (const name of prev.claude.mcp)
362
+ delete servers[name];
363
+ Object.assign(servers, claudeMcp);
364
+ if (Object.keys(servers).length > 0)
365
+ holder['mcpServers'] = servers;
366
+ else
367
+ delete holder['mcpServers'];
368
+ if (targets.claudeProject !== undefined && Object.keys(holder).length === 0)
369
+ delete data['projects'][targets.claudeProject];
370
+ if (isRecord(data['projects']) && Object.keys(data['projects']).length === 0)
371
+ delete data['projects'];
372
+ }))
373
+ changed.push(targets.claudeJson);
374
+ }
375
+ // Codex hooks.json, owned entries only.
376
+ if (writeCodex && (codexHooks.kept.length > 0 || prev.codex.hooks.length > 0)) {
377
+ if (editJson(targets.codexHooks, (data) => {
378
+ const hooks = mergeHooks(isRecord(data['hooks']) ? data['hooks'] : {}, prev.codex.hooks, codexHooks.kept);
379
+ if (Object.keys(hooks).length > 0)
380
+ data['hooks'] = hooks;
381
+ else
382
+ delete data['hooks'];
383
+ }))
384
+ changed.push(targets.codexHooks);
385
+ if (isFile(targets.codexHooks))
386
+ files.push(targets.codexHooks);
387
+ }
388
+ const codexMcp = Object.fromEntries(codexMcpNames.kept.map((n) => [n, entries.codex.mcp[n]]));
389
+ const nextOwned = {
390
+ claude: writeClaude ? { allow: allow.kept, deny, ask, hooks: claudeHooks.kept, mcp: claudeMcpNames.kept } : prev.claude,
391
+ codex: writeCodex ? { hooks: codexHooks.kept, mcp: codexMcp, rules: [...codexAllow.kept, ...codexRestrict] } : prev.codex,
392
+ agentFiles: [...entries.agentFiles.keys()].sort(),
393
+ };
394
+ // Codex rules: one file that all groups share.
395
+ const nextState = { ...state, [group]: nextOwned };
396
+ const allRules = [...new Set(Object.values(nextState).flatMap((o) => o?.codex.rules ?? []))];
397
+ if (!writeCodex) {
398
+ // The repository owns its Codex files.
399
+ }
400
+ else if (allRules.length > 0) {
401
+ if (writeIfChanged(targets.codexRules, `# Generated by \`harnesspm sync\`. Do not edit.\n${allRules.join('\n')}\n`))
402
+ changed.push(targets.codexRules);
403
+ files.push(targets.codexRules);
404
+ }
405
+ else if (isFile(targets.codexRules)) {
406
+ fs.rmSync(targets.codexRules);
407
+ changed.push(targets.codexRules);
408
+ }
409
+ // Sub-agent files.
410
+ for (const [file, content] of entries.agentFiles) {
411
+ if (!writeCodex && file.endsWith('.toml'))
412
+ continue;
413
+ if (writeIfChanged(file, content))
414
+ changed.push(file);
415
+ files.push(file);
416
+ }
417
+ for (const old of prev.agentFiles) {
418
+ if (!entries.agentFiles.has(old) && isFile(old) && (readTextIfExists(old) ?? '').includes('Generated by harnesspm from')) {
419
+ fs.rmSync(old);
420
+ changed.push(old);
421
+ }
422
+ }
423
+ writeOwned(targets.stateFile, nextState);
424
+ const allCodexMcp = Object.assign({}, ...Object.values(nextState).map((o) => o?.codex.mcp ?? {}));
425
+ return { changed, held, codexMcp: allCodexMcp, files };
426
+ }
@@ -0,0 +1,68 @@
1
+ import { type HarnessPackage } from './manifest.ts';
2
+ export interface ScriptUnit {
3
+ kind: 'scripts';
4
+ id: string;
5
+ name: string;
6
+ file: string;
7
+ description?: string;
8
+ usage?: string;
9
+ answers?: number[];
10
+ allow: boolean;
11
+ pkg: HarnessPackage;
12
+ }
13
+ export type Agent = 'claude' | 'codex';
14
+ export declare const AGENTS: Agent[];
15
+ /** Events both agents support (spec 5.2). */
16
+ export declare const PORTABLE_EVENTS: string[];
17
+ export interface HookUnit {
18
+ kind: 'hooks';
19
+ id: string;
20
+ name: string;
21
+ event: string;
22
+ /** Matcher per agent. A missing agent means the hook is not written for it. Undefined value: every tool. */
23
+ matchers: Partial<Record<Agent, string | undefined>>;
24
+ run: string;
25
+ timeout?: number;
26
+ pkg: HarnessPackage;
27
+ }
28
+ export interface McpUnit {
29
+ kind: 'mcp';
30
+ id: string;
31
+ name: string;
32
+ config: Record<string, unknown>;
33
+ pkg: HarnessPackage;
34
+ }
35
+ export interface PermissionsUnit {
36
+ kind: 'permissions';
37
+ id: string;
38
+ deny: string[][];
39
+ ask: string[][];
40
+ pkg: HarnessPackage;
41
+ }
42
+ export interface AgentUnit {
43
+ kind: 'agents';
44
+ id: string;
45
+ name: string;
46
+ description: string;
47
+ body: string;
48
+ claude: Record<string, unknown>;
49
+ codex: Record<string, unknown>;
50
+ file: string;
51
+ pkg: HarnessPackage;
52
+ }
53
+ export interface ExecUnits {
54
+ scripts: ScriptUnit[];
55
+ hooks: HookUnit[];
56
+ mcp: McpUnit[];
57
+ permissions?: PermissionsUnit;
58
+ agents: AgentUnit[];
59
+ }
60
+ /** Finds the executable units and sub-agents of a package. Problems are what `harnesspm check` reports. */
61
+ export declare function discoverExecUnits(pkg: HarnessPackage, problems: string[]): ExecUnits;
62
+ /**
63
+ * Sub-agent keys that widen what the agent may do. Written only for trusted owners (spec 2.6). Claude Code's list is
64
+ * the one it ignores in plugin sub-agents, for security.
65
+ */
66
+ export declare const WIDENING_AGENT_KEYS: Record<Agent, string[]>;
67
+ /** SKILL.md keys that widen what the agent may do. An untrusted package's skill gets a copy without them (spec 6.1). */
68
+ export declare const WIDENING_SKILL_KEYS: string[];
@@ -0,0 +1,151 @@
1
+ // Scripts, hooks, MCP servers, permissions (spec chapter 5) and sub-agents (spec 2.6).
2
+ import * as path from 'node:path';
3
+ import { parseFrontmatter } from './frontmatter.js';
4
+ import { NS } from './manifest.js';
5
+ import { isFile, isRecord, listDir, readJson, readText } from './util.js';
6
+ export const AGENTS = ['claude', 'codex'];
7
+ /** Events both agents support (spec 5.2). */
8
+ export const PORTABLE_EVENTS = ['SessionStart', 'SessionEnd', 'UserPromptSubmit', 'PreToolUse', 'PermissionRequest', 'PostToolUse', 'PreCompact', 'PostCompact', 'SubagentStart', 'SubagentStop', 'Stop'];
9
+ /** Events only one agent supports. Others are dropped with a warning. */
10
+ const AGENT_EVENTS = {
11
+ claude: [...PORTABLE_EVENTS, 'Notification'],
12
+ codex: PORTABLE_EVENTS,
13
+ };
14
+ function commandLists(value, field, problems) {
15
+ if (value === undefined)
16
+ return [];
17
+ if (Array.isArray(value) && value.every((v) => Array.isArray(v) && v.length > 0 && v.every((w) => typeof w === 'string')))
18
+ return value;
19
+ problems.push(`permissions.json: "${field}" must be a list of command prefixes, such as [["git", "push", "--force"]]`);
20
+ return [];
21
+ }
22
+ /** Finds the executable units and sub-agents of a package. Problems are what `harnesspm check` reports. */
23
+ export function discoverExecUnits(pkg, problems) {
24
+ const scripts = Object.entries(pkg.ext.scripts).map(([name, def]) => ({
25
+ kind: 'scripts',
26
+ id: `${pkg.plugin}:scripts/${name}`,
27
+ name,
28
+ file: path.resolve(pkg.harnessDir, def.file),
29
+ ...(def.description !== undefined ? { description: def.description } : {}),
30
+ ...(def.usage !== undefined ? { usage: def.usage } : {}),
31
+ ...(def.answers !== undefined ? { answers: def.answers } : {}),
32
+ allow: def.allow === true,
33
+ pkg,
34
+ }));
35
+ const hooks = [];
36
+ const hooksFile = path.join(pkg.harnessDir, NS, 'hooks.json');
37
+ if (isFile(hooksFile)) {
38
+ const raw = readJson(hooksFile);
39
+ const byEvent = isRecord(raw) && isRecord(raw['hooks']) ? raw['hooks'] : {};
40
+ for (const [event, list] of Object.entries(byEvent)) {
41
+ if (!Array.isArray(list)) {
42
+ problems.push(`hooks.json: "${event}" must be a list`);
43
+ continue;
44
+ }
45
+ for (const def of list) {
46
+ if (!isRecord(def) || typeof def['id'] !== 'string' || typeof def['run'] !== 'string') {
47
+ problems.push(`hooks.json: every ${event} hook needs "id" and "run"`);
48
+ continue;
49
+ }
50
+ if (pkg.ext.scripts[def['run']] === undefined)
51
+ problems.push(`hooks.json: hook "${def['id']}" runs "${def['run']}", which is not in "scripts"`);
52
+ const matcher = def['matcher'];
53
+ let matchers;
54
+ if (matcher === undefined || typeof matcher === 'string')
55
+ matchers = { claude: matcher, codex: matcher };
56
+ else if (isRecord(matcher)) {
57
+ matchers = {};
58
+ for (const agent of AGENTS)
59
+ if (typeof matcher[agent] === 'string')
60
+ matchers[agent] = matcher[agent];
61
+ for (const key of Object.keys(matcher))
62
+ if (!AGENTS.includes(key))
63
+ problems.push(`hooks.json: hook "${def['id']}" has an unknown agent "${key}" in "matcher"`);
64
+ }
65
+ else {
66
+ problems.push(`hooks.json: hook "${def['id']}": "matcher" must be a string or an object`);
67
+ continue;
68
+ }
69
+ for (const agent of AGENTS)
70
+ if (agent in matchers && !AGENT_EVENTS[agent].includes(event))
71
+ delete matchers[agent];
72
+ if (Object.keys(matchers).length === 0)
73
+ problems.push(`hooks.json: hook "${def['id']}" uses ${event}, which no agent it names supports`);
74
+ hooks.push({
75
+ kind: 'hooks',
76
+ id: `${pkg.plugin}:hooks/${def['id']}`,
77
+ name: def['id'],
78
+ event,
79
+ matchers,
80
+ run: def['run'],
81
+ ...(typeof def['timeout'] === 'number' ? { timeout: def['timeout'] } : {}),
82
+ pkg,
83
+ });
84
+ }
85
+ }
86
+ }
87
+ const mcp = [];
88
+ const mcpFile = path.join(pkg.harnessDir, 'mcp.json');
89
+ if (isFile(mcpFile)) {
90
+ const raw = readJson(mcpFile);
91
+ const servers = isRecord(raw) && isRecord(raw['mcpServers']) ? raw['mcpServers'] : {};
92
+ for (const [name, config] of Object.entries(servers)) {
93
+ if (!isRecord(config)) {
94
+ problems.push(`mcp.json: server "${name}" must be an object`);
95
+ continue;
96
+ }
97
+ const type = config['type'] ?? 'stdio';
98
+ if (type === 'stdio' && typeof config['command'] !== 'string')
99
+ problems.push(`mcp.json: stdio server "${name}" needs a "command"`);
100
+ if ((type === 'streamable-http' || type === 'sse') && typeof config['url'] !== 'string')
101
+ problems.push(`mcp.json: server "${name}" needs a "url"`);
102
+ if (!['stdio', 'streamable-http', 'sse'].includes(String(type)))
103
+ problems.push(`mcp.json: server "${name}" has an unknown type "${String(type)}"`);
104
+ mcp.push({ kind: 'mcp', id: `${pkg.plugin}:mcp/${name}`, name, config: { ...config, type }, pkg });
105
+ }
106
+ }
107
+ let permissions;
108
+ const permFile = path.join(pkg.harnessDir, NS, 'permissions.json');
109
+ if (isFile(permFile)) {
110
+ const raw = readJson(permFile);
111
+ const data = isRecord(raw) ? raw : {};
112
+ for (const key of Object.keys(data)) {
113
+ if (key === 'allow')
114
+ problems.push('permissions.json: "allow" is not supported. Set "allow": true on a script instead (spec 5.4).');
115
+ else if (key !== 'deny' && key !== 'ask')
116
+ problems.push(`permissions.json: unknown field "${key}"`);
117
+ }
118
+ permissions = { kind: 'permissions', id: `${pkg.plugin}:permissions`, deny: commandLists(data['deny'], 'deny', problems), ask: commandLists(data['ask'], 'ask', problems), pkg };
119
+ }
120
+ const agentsDir = path.join(pkg.harnessDir, NS, 'agents');
121
+ const agents = [];
122
+ for (const file of listDir(agentsDir).filter((f) => f.endsWith('.md'))) {
123
+ const full = path.join(agentsDir, file);
124
+ const { data, body } = parseFrontmatter(readText(full), full);
125
+ const name = typeof data['name'] === 'string' ? data['name'] : file.slice(0, -3);
126
+ if (typeof data['description'] !== 'string')
127
+ problems.push(`agents/${file}: needs a "description"`);
128
+ agents.push({
129
+ kind: 'agents',
130
+ id: `${pkg.plugin}:agents/${name}`,
131
+ name,
132
+ description: typeof data['description'] === 'string' ? data['description'] : '',
133
+ body: body.trim(),
134
+ claude: isRecord(data['claude']) ? data['claude'] : {},
135
+ codex: isRecord(data['codex']) ? data['codex'] : {},
136
+ file: full,
137
+ pkg,
138
+ });
139
+ }
140
+ return { scripts, hooks, mcp, ...(permissions ? { permissions } : {}), agents };
141
+ }
142
+ /**
143
+ * Sub-agent keys that widen what the agent may do. Written only for trusted owners (spec 2.6). Claude Code's list is
144
+ * the one it ignores in plugin sub-agents, for security.
145
+ */
146
+ export const WIDENING_AGENT_KEYS = {
147
+ claude: ['permissionMode', 'hooks', 'mcpServers'],
148
+ codex: ['sandbox_mode', 'approval_policy'],
149
+ };
150
+ /** SKILL.md keys that widen what the agent may do. An untrusted package's skill gets a copy without them (spec 6.1). */
151
+ export const WIDENING_SKILL_KEYS = ['allowed-tools', 'hooks'];
@@ -0,0 +1,16 @@
1
+ export interface FetchReport {
2
+ fetched: string[];
3
+ reused: string[];
4
+ warnings: string[];
5
+ }
6
+ /** Where `fetch` puts a package. */
7
+ export declare const fetchedDir: (projectDir: string, name: string) => string;
8
+ /**
9
+ * Where each harness package in the lock is on this machine: installed in the version the lock names, else fetched in
10
+ * that version. `missing` names the packages that are neither. Undefined when the project has no lock.
11
+ */
12
+ export declare function locateLocked(projectDir: string): {
13
+ located: Map<string, string>;
14
+ missing: string[];
15
+ } | undefined;
16
+ export declare function fetchLocked(projectDir: string): FetchReport;