@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
@@ -0,0 +1,1299 @@
1
+ // CLI commands (spec chapter 10).
2
+ import * as fs from 'node:fs';
3
+ import * as path from 'node:path';
4
+ import { caller, configFileFor, entryFolders, entryPackage, fetchSource, loadAdded, parseSource, readList, updateSource, writeList, } from './added.js';
5
+ import { checkHarness } from './check.js';
6
+ import { checkLocalFiles, excludeWritable, formatFinding } from './doctor.js';
7
+ import { CONFIG_FILE, CONFIG_SCHEMA } from './config.js';
8
+ import { loadHarnessPackage, NS } from './manifest.js';
9
+ import { emptyEntries, heldEntries, trustOf } from './exec-outputs.js';
10
+ import { childProjects, childRepos, hasParentOutputs, isParentFolder, parentToSync, removeGone, writeParent, writePointer } from './parent.js';
11
+ import { buildLock, LOCK_FILE, readLock, serializeLock } from './lock.js';
12
+ import { applyPlan, checkPlan, claudeImport, computePlan, repoStateFile, STATE_DIR } from './outputs.js';
13
+ import { fetchLocked, locateLocked } from './fetch.js';
14
+ import { createPatch, createUnit, KINDS, resolveTarget } from './new.js';
15
+ import { reviewedState } from './reviewed.js';
16
+ import { runMcp, runScript } from './run.js';
17
+ import { pathTools } from './outputs.js';
18
+ import { alwaysOnText, blockRange, helpTarget, ruleBodyWithoutTitle } from './render.js';
19
+ import { describeMembers, localRuleChanges, resolve, resolvePackageDir, rulesForDirectory } from './resolve.js';
20
+ import { demoteHeadings } from './sections.js';
21
+ import { tryFrontmatter } from './frontmatter.js';
22
+ import { commandCaller, describeSend, outsideField, readIndex, readTelemetryState, sendEvent } from './telemetry.js';
23
+ import { migrateSessionHook, userHeld, writeUserOutputs, writeUserSettings } from './user-outputs.js';
24
+ import { HarnessError, NPX_ANY, OLD_PACKAGE_NAMES, PACKAGE_NAME, PACKAGE_NAMES, addExclude, codexRun, gitExcludeFile, inCloudSession, insideDir, isDir, isFile, isRecord, readJson, readJsonIfExists, readTextIfExists, relPosix, runner, shellWord, writeIfChanged } from './util.js';
25
+ import { spawnSync } from 'node:child_process';
26
+ const printWarnings = (out, warnings) => {
27
+ for (const w of [...new Set(warnings)])
28
+ out.warn(`⚠️ ${w}`);
29
+ };
30
+ const plural = (count, word, many = `${word}s`) => `${count} ${count === 1 ? word : many}`;
31
+ /**
32
+ * Where a person grants what an agent could not. A Claude Code cloud session has no terminal of the person's, and its
33
+ * container goes away, so there the setup script runs the command, before each new session starts (spec 9).
34
+ */
35
+ const cloudStep = (what, them) => `In a Claude Code cloud session, ask the person to run ${what} in the environment's setup script. New sessions then start with ${them}.`;
36
+ function grantStep(projectDir, inTerminal) {
37
+ if (!inCloudSession())
38
+ return inTerminal;
39
+ const line = setupLine(projectDir);
40
+ return cloudStep(`${line !== undefined ? `\`${line}\`` : 'the install'}, or their own \`${NPX_ANY} add <source>\`,`, 'these entries');
41
+ }
42
+ const firstThree = (items) => `${items.slice(0, 3).join('; ')}${items.length > 3 ? '; …' : ''}`;
43
+ const heldList = (report) => `${plural(report.held.length, 'entry', 'entries')} that an agent cannot grant (${firstThree(report.held)})${report.why !== undefined ? `, because ${report.why}` : ''}`;
44
+ const unwrittenList = ({ entries, branch }) => `${plural(entries.length, 'entry', 'entries')} that ${branch} records (${firstThree(entries)})`;
45
+ function printPending(out, report, projectDir) {
46
+ for (const line of [...new Set(report.pending)])
47
+ out.log(`⏳ pending: ${line}`);
48
+ if (report.unwritten)
49
+ out.log(`⏳ not written yet: ${unwrittenList(report.unwritten)}. Run \`${NPX_ANY} sync\`.`);
50
+ if (report.held.length > 0) {
51
+ out.log(`⏳ held back: ${heldList(report)}.`);
52
+ out.log(` ${grantStep(projectDir, `Ask the person to run \`${NPX_ANY} sync\` or \`${NPX_ANY} approve\` in their own terminal.`)}`);
53
+ }
54
+ }
55
+ /** The repository to work on: the nearest folder with harnesspm.json, else the git root, else `cwd`. */
56
+ export function findProjectDir(cwd) {
57
+ for (let dir = cwd;; dir = path.dirname(dir)) {
58
+ if (isFile(path.join(dir, CONFIG_FILE)))
59
+ return dir;
60
+ if (path.dirname(dir) === dir)
61
+ break;
62
+ }
63
+ const top = spawnSync('git', ['rev-parse', '--show-toplevel'], { cwd, encoding: 'utf8' });
64
+ return top.status === 0 ? top.stdout.trim() : cwd;
65
+ }
66
+ /** True when every direct dependency that is not optional is installed. */
67
+ function dependenciesInstalled(projectDir) {
68
+ const pkg = readJsonIfExists(path.join(projectDir, 'package.json'));
69
+ if (!isRecord(pkg))
70
+ return true;
71
+ if (!isDir(path.join(projectDir, 'node_modules'))) {
72
+ const any = ['dependencies', 'devDependencies'].some((f) => isRecord(pkg[f]) && Object.keys(pkg[f]).length > 0);
73
+ return !any;
74
+ }
75
+ for (const field of ['dependencies', 'devDependencies']) {
76
+ const deps = pkg[field];
77
+ if (!isRecord(deps))
78
+ continue;
79
+ for (const name of Object.keys(deps))
80
+ if (!resolvePackageDir(name, projectDir))
81
+ return false;
82
+ }
83
+ return true;
84
+ }
85
+ /** `addedOnly` resolves only the added harnesses, so the repository's own outputs stay as its own sync wrote them. */
86
+ function resolveAll(projectDir, options) {
87
+ const warnings = [];
88
+ const usesHarnesspm = !options.addedOnly && isFile(path.join(projectDir, CONFIG_FILE));
89
+ const installed = usesHarnesspm && dependenciesInstalled(projectDir);
90
+ if (usesHarnesspm && !installed)
91
+ warnings.push('the dependencies are not installed, so the committed outputs are left as they are');
92
+ const inRepo = gitExcludeFile(projectDir) !== undefined;
93
+ const added = options.withAdded && process.env['CI'] !== 'true' ? loadAdded(inRepo ? projectDir : undefined, warnings) : [];
94
+ const team = installed ? resolve(projectDir) : undefined;
95
+ // Outside a git repository only user-scope harnesses load, and no repository outputs are written.
96
+ const full = resolve(projectDir, { team: installed, added });
97
+ const mode = installed ? 'full' : inRepo && added.length > 0 ? 'added-only' : 'none';
98
+ return { ...(team ? { team } : {}), full, added, mode, warnings: [...warnings, ...(team?.warnings ?? []), ...full.warnings] };
99
+ }
100
+ /**
101
+ * `check` compares and writes nothing. With `CI=true`, the committed outputs stay as they are unless `write` is set,
102
+ * so that an install's sync cannot hide a missed sync from a later `sync --check` (spec 6.4, 10.1).
103
+ */
104
+ export function sync(cwd, out, options = {}) {
105
+ const projectDir = findProjectDir(cwd);
106
+ if (options.check && options.write)
107
+ throw new HarnessError('Use either --check or --write, not both.');
108
+ if (options.check) {
109
+ const { team, full, warnings } = resolveAll(projectDir, { withAdded: false });
110
+ const plan = computePlan(team, full);
111
+ printWarnings(out, [...warnings, ...plan.warnings]);
112
+ const problems = checkPlan(projectDir, plan);
113
+ for (const p of problems)
114
+ out.log(`❌ ${p}`);
115
+ if (problems.length > 0) {
116
+ out.log(`Run \`${NPX_ANY} sync\` and commit the result.`);
117
+ return 1;
118
+ }
119
+ out.log('✅ harnesspm outputs are up to date');
120
+ return 0;
121
+ }
122
+ const resolved = resolveAll(projectDir, { withAdded: true });
123
+ const { full, mode } = resolved;
124
+ const warnings = [...resolved.warnings];
125
+ const changed = [];
126
+ const report = { pending: [], held: [] };
127
+ const before = readLock(projectDir);
128
+ const keepCommitted = process.env['CI'] === 'true' && options.write !== true;
129
+ let keptCommitted = false;
130
+ const model = caller() === 'model';
131
+ if (mode !== 'none') {
132
+ const written = writeProject(projectDir, resolved, { keepCommitted, model, parentHooks: true }, report);
133
+ warnings.push(...written.warnings);
134
+ changed.push(...written.changed);
135
+ keptCommitted = written.keptCommitted;
136
+ }
137
+ // A folder above git repositories, such as `/home/user` in a cloud session with several: each repository gets the
138
+ // per-machine outputs of the added harnesses (spec 4.10). Only those: the repository's own outputs belong to its own
139
+ // install, whose harnesspm may be another version than the one that runs here. CI ignores added harnesses.
140
+ const repos = mode === 'none' && process.env['CI'] !== 'true' && resolved.added.length > 0 ? childRepos(projectDir) : [];
141
+ const applied = [];
142
+ for (const repo of repos) {
143
+ const sub = resolveAll(repo, { withAdded: true, addedOnly: true });
144
+ if (sub.mode === 'none')
145
+ continue;
146
+ const name = path.basename(repo);
147
+ const written = writeProject(repo, sub, { keepCommitted: true, model, parentHooks: false }, report);
148
+ warnings.push(...[...sub.warnings, ...written.warnings].map((w) => `${name}: ${w}`));
149
+ changed.push(...written.changed.map((file) => (path.isAbsolute(file) ? file : `${name}/${file}`)));
150
+ applied.push(name);
151
+ }
152
+ // Sync in a parent folder: the projects' hooks and a pointer to their harness, for sessions that start here, and
153
+ // nothing left of projects that are gone (spec 4.10).
154
+ const parentSync = mode === 'none' && parentToSync(projectDir);
155
+ const children = parentSync ? childProjects(projectDir) : [];
156
+ for (const child of children) {
157
+ const sub = resolveAll(child, { withAdded: false });
158
+ warnings.push(...sub.warnings.map((w) => `${path.basename(child)}: ${w}`));
159
+ const plan = sub.team ? computePlan(sub.team, sub.full, { widen: !model }) : undefined;
160
+ const written = writeParent(projectDir, child, plan?.exec.team ?? emptyEntries(), runner(child, NPX_ANY).shell, !model);
161
+ changed.push(...written.changed);
162
+ report.held.push(...written.held);
163
+ }
164
+ if (parentSync)
165
+ changed.push(...removeGone(projectDir, children), ...writePointer(projectDir));
166
+ if (resolved.team)
167
+ syncEvent(resolved.team, before, readLock(projectDir), report);
168
+ if (process.env['CI'] !== 'true')
169
+ changed.push(...writeUserOutputs(resolved.added, warnings, report));
170
+ if (process.env['CI'] !== 'true' && !model)
171
+ changed.push(...migrateSessionHook());
172
+ printWarnings(out, warnings);
173
+ printPending(out, report, projectDir);
174
+ if (options.quiet)
175
+ return 0;
176
+ if (keptCommitted)
177
+ out.log(`CI: committed outputs left as they are; \`${NPX_ANY} sync --check\` compares them, \`sync --write\` writes them.`);
178
+ const counts = `${plural(new Set(full.rules.map((r) => r.id)).size, 'rule')}, ${plural(full.skills.length, 'skill')}, ${plural(full.docs.length, 'doc')} from ${plural(full.packages.length, 'package')}`;
179
+ const above = `Sessions that start here get the hooks of ${plural(children.length, 'project')} below: ${children.map((c) => path.basename(c)).join(', ')}`;
180
+ const gone = 'No projects below this folder any more: removed what an earlier sync wrote for them';
181
+ const below = `Added harnesses in ${plural(applied.length, 'repository', 'repositories')} below: ${applied.join(', ')}`;
182
+ const parts = [...(children.length > 0 ? [above] : parentSync ? [gone] : []), ...(applied.length > 0 ? [below] : [])];
183
+ const what = mode === 'none' ? (parts.length > 0 ? parts.join('. ') : 'Nothing to do in this folder') : mode === 'added-only' ? `Added harnesses only: ${counts}` : counts;
184
+ out.log(changed.length > 0 ? `harnesspm: ${what}. Updated ${plural(changed.length, 'file')}.` : `harnesspm: ${what}. Nothing changed.`);
185
+ return 0;
186
+ }
187
+ /**
188
+ * Writes one project's outputs, as `sync` in it does. `keepCommitted` leaves the committed outputs as they are and
189
+ * writes only the per-machine ones. `parentHooks` also keeps the project's hooks current in a parent folder above it.
190
+ */
191
+ function writeProject(projectDir, resolved, options, report) {
192
+ const { model } = options;
193
+ const changed = [];
194
+ const plan = computePlan(resolved.team, resolved.full, { widen: !model });
195
+ const reviewed = model ? reviewedFor(projectDir, resolved.team, plan) : undefined;
196
+ const applied = applyPlan(projectDir, plan, { committed: !options.keepCommitted, reviewed: reviewed?.ok === true });
197
+ changed.push(...applied.changed);
198
+ report.held.push(...(plan.telemetryHeld !== undefined ? [plan.telemetryHeld] : []), ...applied.held);
199
+ if (reviewed?.ok === false && (applied.teamHeld || plan.telemetryHeld !== undefined))
200
+ report.why = reviewed.reason;
201
+ report.pending.push(...(plan.exec.team?.pending ?? []), ...plan.exec.added.pending);
202
+ // A parent folder above the project, once a sync ran there, gets this project's hooks too (spec 4.10). The agent's
203
+ // model never adds one there, not even what the default branch records: the folder is the person's.
204
+ const parent = path.dirname(projectDir);
205
+ if (options.parentHooks && plan.exec.team && hasParentOutputs(parent)) {
206
+ const written = writeParent(parent, projectDir, plan.exec.team, runner(projectDir, NPX_ANY).shell, !model);
207
+ changed.push(...written.changed, ...writePointer(parent));
208
+ report.held.push(...written.held);
209
+ }
210
+ return { changed, warnings: plan.warnings, keptCommitted: options.keepCommitted && plan.committed !== undefined };
211
+ }
212
+ /** Where events about a resolved project go (spec chapter 14). */
213
+ const eventContext = (res) => ({ projectDir: res.projectDir, project: res.projectName, workspaces: res.workspaces.map((ws) => ws.key) });
214
+ /**
215
+ * The `sync` event: packages, the units that changed since the last lock, and what an agent's sync held back and why
216
+ * (spec 14.2). CI sends none: every job syncs.
217
+ */
218
+ function syncEvent(team, before, after, report) {
219
+ const state = readTelemetryState(team.projectDir);
220
+ if (!state.events.has('sync') || !after || commandCaller().caller === 'ci')
221
+ return;
222
+ const old = before?.units ?? {};
223
+ const units = after.units;
224
+ const pending = team.packages.filter((pkg) => pkg.layer === 'dependencies' && [...team.scripts, ...team.hooks, ...team.mcp].some((u) => u.pkg === pkg) && !trustOf(pkg, team, after).trusted);
225
+ sendEvent(state, eventContext(team), {
226
+ type: 'sync',
227
+ ...commandCaller(),
228
+ packages: team.packages.filter((p) => p.layer !== 'added').map((p) => ({ name: p.name, version: p.version })),
229
+ added: Object.keys(units).filter((id) => old[id] === undefined),
230
+ removed: Object.keys(old).filter((id) => units[id] === undefined),
231
+ changed: Object.keys(units).filter((id) => old[id] !== undefined && old[id].hash !== units[id].hash),
232
+ pending: pending.map((p) => p.name),
233
+ // A hook above the project names it with `-C <its path>`; events carry no local paths (spec 14.2).
234
+ ...(report.held.length > 0 ? { held: report.held.map((entry) => entry.replace(/ -C (?:'(?:[^']|'\\'')*'|"[^"]*"|\S+)/g, '')), reason: report.why } : {}),
235
+ });
236
+ }
237
+ /**
238
+ * The install hook that `init` writes (spec 10.1). harnesspm is a dev dependency, so an install without dev
239
+ * dependencies, such as `npm ci --omit=dev`, has no `harnesspm` command. The `node -e` part ends with success
240
+ * exactly then, and `||` skips the sync. When harnesspm is installed, it fails, so the sync runs and a failing
241
+ * sync still fails the install. `node -e` and `||` work in sh, Windows cmd and Yarn's shell; `|| true` does not.
242
+ */
243
+ const installHook = (name) => `node -e "try{require.resolve('${name}/package.json');process.exit(1)}catch{}" || harnesspm sync`;
244
+ const HOOK_SCRIPTS = ['prepare', 'postinstall'];
245
+ const OLD_HOOK = 'harnesspm sync';
246
+ /**
247
+ * The script with the guarded hook for `name`, the package the project depends on, in place of a form that `init`
248
+ * wrote before: the unguarded hook, or a guard for another name of the package, which would skip every sync once
249
+ * that name is gone (spec 10.1). Undefined when there is nothing to change.
250
+ */
251
+ function upgradedHook(script, name) {
252
+ if (typeof script !== 'string')
253
+ return undefined;
254
+ if (script === OLD_HOOK)
255
+ return installHook(name);
256
+ // The parentheses keep a failure of the existing script visible: `a && b || c` runs c when a fails.
257
+ if (script.endsWith(` && ${OLD_HOOK}`))
258
+ return `${script.slice(0, -OLD_HOOK.length)}(${installHook(name)})`;
259
+ const other = PACKAGE_NAMES.find((n) => n !== name && script.includes(installHook(n)));
260
+ return other !== undefined ? script.replace(installHook(other), installHook(name)) : undefined;
261
+ }
262
+ /**
263
+ * The name under which a package.json lists harnesspm, so the project has the `harnesspm` command: the current name
264
+ * first, then an earlier one (spec 10.1). Its own repository is the package. Undefined when it does not list it.
265
+ */
266
+ function harnesspmDependency(pkg) {
267
+ if (!isRecord(pkg))
268
+ return undefined;
269
+ return PACKAGE_NAMES.find((name) => pkg['name'] === name ||
270
+ ['dependencies', 'devDependencies', 'optionalDependencies'].some((field) => {
271
+ const dependencies = pkg[field];
272
+ return isRecord(dependencies) && name in dependencies;
273
+ }));
274
+ }
275
+ const dependsOnHarnesspm = (pkg) => harnesspmDependency(pkg) !== undefined;
276
+ /** Lockfiles that an install changes, with the install that each one asks for. */
277
+ const INSTALLS = {
278
+ 'package-lock.json': 'npm ci',
279
+ 'npm-shrinkwrap.json': 'npm ci',
280
+ 'pnpm-lock.yaml': 'pnpm install',
281
+ 'yarn.lock': 'yarn install',
282
+ 'bun.lock': 'bun install',
283
+ 'bun.lockb': 'bun install',
284
+ };
285
+ /** `init` names the lockfile the project has with the files to commit. */
286
+ const LOCKFILES = Object.keys(INSTALLS);
287
+ /**
288
+ * The project's install for a Claude Code cloud environment's setup script (spec 9.1), or undefined when it is not
289
+ * known. It names the project by its absolute path, because the setup script does not start in the clone. A pinned
290
+ * package manager needs corepack, and the default network access does not reach corepack's host for Yarn, so corepack
291
+ * downloads from the npm registry.
292
+ */
293
+ function setupLine(projectDir) {
294
+ // A folder above projects: its sync, after the projects' installs (spec 4.10).
295
+ if (isParentFolder(projectDir))
296
+ return `cd ${/^[\w./-]+$/.test(projectDir) ? projectDir : `'${projectDir.replaceAll("'", "'\\''")}'`} && ${NPX_ANY} sync`;
297
+ const lock = LOCKFILES.find((file) => isFile(path.join(projectDir, file)));
298
+ if (lock === undefined || !isFile(path.join(projectDir, CONFIG_FILE)))
299
+ return undefined;
300
+ const pkg = readJsonIfExists(path.join(projectDir, 'package.json'));
301
+ const corepack = isRecord(pkg) && typeof pkg['packageManager'] === 'string' ? 'corepack enable && COREPACK_NPM_REGISTRY=https://registry.npmjs.org ' : '';
302
+ const dir = /^[\w./-]+$/.test(projectDir) ? projectDir : `'${projectDir.replaceAll("'", "'\\''")}'`;
303
+ return `cd ${dir} && ${corepack}${INSTALLS[lock]}`;
304
+ }
305
+ /** The committed files (spec 1.7) that git sees as new or changed, in a fixed order. Empty outside git. */
306
+ function filesToCommit(projectDir) {
307
+ const { team, full } = resolveAll(projectDir, { withAdded: false });
308
+ const committed = team ? computePlan(team, full).committed : undefined;
309
+ const nested = committed ? [...committed.workspaces.filter((ws) => ws.agentsMd !== undefined).map((ws) => path.join(ws.dir, 'AGENTS.md')), ...committed.claudeMds.map((c) => c.file)] : [];
310
+ const candidates = [...new Set(['AGENTS.md', 'CLAUDE.md', ...nested.map((file) => relPosix(projectDir, file)), CONFIG_FILE, LOCK_FILE, 'package.json', ...LOCKFILES])];
311
+ // The short format shows paths relative to the current folder, also in a subfolder of the repository.
312
+ const result = spawnSync('git', ['status', '--short', '--untracked-files=all', '--', ...candidates], { cwd: projectDir, encoding: 'utf8' });
313
+ if (result.status !== 0)
314
+ return [];
315
+ const changed = new Set(result.stdout.split('\n').filter((line) => line.length > 3).map((line) => line.slice(3).replace(/^.* -> /, '')));
316
+ return candidates.filter((file) => changed.has(file));
317
+ }
318
+ export function init(projectDir, out) {
319
+ const pkgFile = path.join(projectDir, 'package.json');
320
+ if (!isFile(pkgFile))
321
+ throw new HarnessError('No package.json here. Run `npm init` first.');
322
+ const raw = readTextIfExists(pkgFile);
323
+ const pkg = readJson(pkgFile);
324
+ if (!isRecord(pkg))
325
+ throw new HarnessError('package.json must be a JSON object');
326
+ // The script that `init` adds calls the `harnesspm` command. Without the dependency, the next install fails with
327
+ // "harnesspm: not found" (research/package-managers.md). So stop before anything changes.
328
+ const dependency = harnesspmDependency(pkg);
329
+ if (dependency === undefined) {
330
+ throw new HarnessError(`${PACKAGE_NAME} is not a dependency of this project, so the install script that \`init\` adds would fail. Run \`npm i -D ${PACKAGE_NAME}\` first, then \`${NPX_ANY} init\`.`);
331
+ }
332
+ const configFile = path.join(projectDir, CONFIG_FILE);
333
+ if (!isFile(configFile)) {
334
+ writeIfChanged(configFile, `${JSON.stringify({ $schema: CONFIG_SCHEMA }, null, 2)}\n`);
335
+ out.log(`Created ${CONFIG_FILE}`);
336
+ }
337
+ // A private package is never installed by others, so `postinstall` is safe there, and Yarn 2+ runs only
338
+ // `postinstall`. A published package uses `prepare`, which does not run when others install it.
339
+ const scripts = isRecord(pkg['scripts']) ? pkg['scripts'] : {};
340
+ const hookName = pkg['private'] === true ? 'postinstall' : 'prepare';
341
+ const has = (name) => typeof scripts[name] === 'string' && scripts[name].includes(OLD_HOOK);
342
+ let changed = false;
343
+ if (!HOOK_SCRIPTS.some(has)) {
344
+ const current = typeof scripts[hookName] === 'string' ? scripts[hookName] : undefined;
345
+ scripts[hookName] = current === undefined ? installHook(dependency) : `${current} && (${installHook(dependency)})`;
346
+ changed = true;
347
+ out.log(`Added \`harnesspm sync\` to the "${hookName}" script`);
348
+ }
349
+ else {
350
+ for (const name of HOOK_SCRIPTS) {
351
+ const before = scripts[name];
352
+ const next = upgradedHook(before, dependency);
353
+ if (next === undefined)
354
+ continue;
355
+ scripts[name] = next;
356
+ changed = true;
357
+ out.log(before.endsWith(OLD_HOOK) ? `Updated the "${name}" script: it now skips \`harnesspm sync\` when harnesspm is not installed, as in \`npm ci --omit=dev\`` : `Updated the "${name}" script: it now checks for ${dependency}`);
358
+ }
359
+ }
360
+ if (changed) {
361
+ pkg['scripts'] = scripts;
362
+ const indent = /^\{\r?\n(\s+)/.exec(raw)?.[1] ?? ' ';
363
+ writeIfChanged(pkgFile, `${JSON.stringify(pkg, null, indent)}\n`);
364
+ }
365
+ const claude = claudeImport(projectDir);
366
+ if (writeIfChanged(claude.file, claude.text))
367
+ out.log(`${relPosix(projectDir, claude.file)} now imports AGENTS.md`);
368
+ const code = sync(projectDir, out, { write: true });
369
+ // Say which files belong in git, and that the rest stays out of it, so nobody has to work it out from `git status`.
370
+ const toCommit = filesToCommit(projectDir);
371
+ if (toCommit.length > 0)
372
+ out.log(`To commit: ${toCommit.join(', ')}`);
373
+ if (gitExcludeFile(projectDir) !== undefined)
374
+ out.log('Links and settings for this machine stay out of git: .git/info/exclude lists them.');
375
+ return code;
376
+ }
377
+ /** Directories of editable added harnesses, which agents may write to (spec 8.5). */
378
+ function writableDirs() {
379
+ const dirs = new Set();
380
+ for (const spec of readList(configFileFor('user', ''))) {
381
+ const source = parseSource(spec);
382
+ if (source.editable)
383
+ dirs.add(source.dir);
384
+ }
385
+ return [...dirs].sort();
386
+ }
387
+ /** Writes the hook and write access, unless the agent's model runs harnesspm (spec 6.2, rule 4). */
388
+ function settingsAfterChange(out, hook) {
389
+ if (caller() === 'model') {
390
+ out.log('⏳ The SessionStart hook and write access to the harness folder are pending: an agent cannot grant them.');
391
+ out.log(` ${inCloudSession() ? cloudStep('the same command', 'them') : 'Ask the person to run the same command in their own terminal.'}`);
392
+ return;
393
+ }
394
+ const anyUser = readList(configFileFor('user', '')).length > 0;
395
+ writeUserSettings(hook && anyUser, writableDirs());
396
+ }
397
+ function printAddedRules(projectDir, spec, out) {
398
+ const warnings = [];
399
+ const harness = loadAdded(gitExcludeFile(projectDir) ? projectDir : undefined, warnings).find((h) => h.source.spec === spec);
400
+ if (!harness)
401
+ return;
402
+ const res = resolve(projectDir, { team: false, added: [harness] });
403
+ const always = res.rules.filter((r) => r.activation === 'always');
404
+ if (always.length === 0)
405
+ return;
406
+ out.log('');
407
+ out.log(`Rules from ${spec}, to follow from now on in this session:`);
408
+ out.log('');
409
+ for (const rule of always)
410
+ out.log(`${alwaysOnText(rule)}\n`);
411
+ }
412
+ export function add(cwd, spec, out, options = {}) {
413
+ const projectDir = findProjectDir(cwd);
414
+ const scope = options.local ? 'local' : 'user';
415
+ if (scope === 'local' && !gitExcludeFile(projectDir))
416
+ throw new HarnessError('--local needs a git repository');
417
+ const source = parseSource(spec, cwd);
418
+ const note = fetchSource(source);
419
+ if (note !== undefined)
420
+ out.log(note);
421
+ const pkg = loadHarnessPackage(source.dir, 'added');
422
+ if (!pkg)
423
+ throw new HarnessError(`${source.spec} has no harness/plugin.json`);
424
+ const file = configFileFor(scope, projectDir);
425
+ const list = readList(file);
426
+ if (!list.includes(source.spec)) {
427
+ writeList(file, [...list, source.spec]);
428
+ out.log(`Added ${pkg.plugin} (${source.spec}) with ${scope} scope`);
429
+ }
430
+ else
431
+ out.log(`${source.spec} is already added with ${scope} scope`);
432
+ if (scope === 'local')
433
+ addExclude(projectDir, 'harnesspm.local.json');
434
+ sync(projectDir, out, { quiet: true });
435
+ settingsAfterChange(out, options.hook !== false);
436
+ printAddedRules(projectDir, source.spec, out);
437
+ return 0;
438
+ }
439
+ export function remove(cwd, spec, out, options = {}) {
440
+ const projectDir = findProjectDir(cwd);
441
+ const scope = options.local ? 'local' : 'user';
442
+ const file = configFileFor(scope, projectDir);
443
+ const list = readList(file);
444
+ const target = parseSource(spec, cwd).spec;
445
+ const next = list.filter((s) => s !== spec && s !== target);
446
+ if (next.length === list.length)
447
+ throw new HarnessError(`${spec} is not added with ${scope} scope`);
448
+ writeList(file, next);
449
+ out.log(`Removed ${spec} (${scope} scope)`);
450
+ sync(projectDir, out, { quiet: true });
451
+ settingsAfterChange(out, true);
452
+ return 0;
453
+ }
454
+ /**
455
+ * Fetches the added harnesses, then syncs. The `SessionStart` hook runs it (spec 7.5), so a source that cannot be
456
+ * fetched never fails it: harnesspm warns and syncs what is on this machine. Without a person at a terminal, git never
457
+ * prompts and a slow fetch is stopped.
458
+ */
459
+ export function update(cwd, out) {
460
+ const projectDir = findProjectDir(cwd);
461
+ const specs = [...readList(configFileFor('user', projectDir)), ...(gitExcludeFile(projectDir) ? readList(configFileFor('local', projectDir)) : [])];
462
+ const quiet = caller() !== 'person' || process.stdin.isTTY !== true;
463
+ for (const spec of specs) {
464
+ try {
465
+ out.log(updateSource(parseSource(spec), { quiet }));
466
+ }
467
+ catch (error) {
468
+ if (!(error instanceof HarnessError))
469
+ throw error;
470
+ out.warn(`⚠️ ${spec}: ${error.message}. Kept what is on this machine.`);
471
+ }
472
+ }
473
+ return sync(projectDir, out);
474
+ }
475
+ /** Codex reads `AGENTS.md` files up to `project_doc_max_bytes`, 32 KiB by default, and cuts off the rest (spec 4.9). */
476
+ const CODEX_LIMIT = 32 * 1024;
477
+ const CODEX_OVER = "Codex's 32 KiB limit: Codex reads only the first 32 KiB";
478
+ const kib = (bytes) => `${(bytes / 1024).toFixed(1)} KiB`;
479
+ /**
480
+ * Managed blocks that Codex misses, in full or in part (spec 4.9). Codex joins one file per folder, from its project
481
+ * root, the git root, down to the folder it starts in: `AGENTS.override.md` when there is one, else `AGENTS.md`. Only
482
+ * file bytes count. The root block at the very start is left out: the size warning for the root `AGENTS.md` covers it.
483
+ */
484
+ function codexMisses(projectDirInput, plan) {
485
+ const committed = plan.committed;
486
+ if (!committed)
487
+ return [];
488
+ // Workspace folders are real paths, so the root is one too.
489
+ const projectDir = fs.realpathSync(projectDirInput);
490
+ // harnesspm.json can sit below the git root. Codex counts the AGENTS.md files above it too.
491
+ const top = spawnSync('git', ['rev-parse', '--show-toplevel'], { cwd: projectDir, encoding: 'utf8' });
492
+ const gitRoot = top.status === 0 && top.stdout.trim() !== '' ? fs.realpathSync(top.stdout.trim()) : projectDir;
493
+ const inside = (dir) => dir === gitRoot || dir.startsWith(gitRoot + path.sep);
494
+ const planned = new Map([[projectDir, committed.agentsMd], ...committed.workspaces.map((ws) => [ws.dir, ws.agentsMd])]);
495
+ const bytesIn = (dir) => {
496
+ const text = readTextIfExists(path.join(dir, 'AGENTS.override.md')) ?? (planned.has(dir) ? planned.get(dir) : readTextIfExists(path.join(dir, 'AGENTS.md')));
497
+ return text !== undefined ? Buffer.byteLength(text) : 0;
498
+ };
499
+ const problems = [];
500
+ for (const [dir, text] of planned) {
501
+ const range = blockRange(text);
502
+ if (text === undefined || range === undefined)
503
+ continue;
504
+ const rel = relPosix(projectDir, path.join(dir, 'AGENTS.md'));
505
+ if (isFile(path.join(dir, 'AGENTS.override.md'))) {
506
+ problems.push(`Codex never reads the harness block in ${rel}: it reads ${relPosix(projectDir, path.join(dir, 'AGENTS.override.md'))} there instead. ${STILL_HELP}`);
507
+ continue;
508
+ }
509
+ let above = 0;
510
+ for (let up = path.dirname(dir); dir !== gitRoot && inside(up); up = path.dirname(up)) {
511
+ above += bytesIn(up);
512
+ if (up === gitRoot)
513
+ break;
514
+ }
515
+ const before = Buffer.byteLength(text.slice(0, range[0]));
516
+ const start = above + before;
517
+ const end = start + Buffer.byteLength(text.slice(range[0], range[1]));
518
+ if (end <= CODEX_LIMIT || (dir === projectDir && start === 0))
519
+ continue;
520
+ const steps = [
521
+ ...(before > 0 ? ['move the block to the top of its file, where sync keeps it'] : []),
522
+ ...(above > 0 ? ['shorten the AGENTS.md files above it'] : []),
523
+ 'move details into on-demand rules or docs',
524
+ ].join(', or ');
525
+ const where = 'of the AGENTS.md files that Codex joins there, past its 32 KiB limit';
526
+ const what = start >= CODEX_LIMIT ? `Codex never reads the harness block in ${rel}: it starts at ${kib(start)} ${where}` : `Codex reads only part of the harness block in ${rel}: it ends at ${kib(end)} ${where}`;
527
+ problems.push(`${what}. To fix it, ${steps}. ${STILL_HELP}`);
528
+ }
529
+ return problems;
530
+ }
531
+ /** What an agent can still do when Codex misses a block: the block names its packages, and `help` prints them (spec 4.9). */
532
+ const STILL_HELP = `Agents can still get what it holds with \`${NPX_ANY} help <package>\`.`;
533
+ /** Agents often read only the top of AGENTS.md, such as with `head -30` (research/agent-capabilities.md). */
534
+ const TOP_LINES = 30;
535
+ /** Committed blocks that start past the first 30 lines of their file, so a partial read misses the outside line (spec 4.6). */
536
+ function lateBlocks(projectDir, plan) {
537
+ const committed = plan.committed;
538
+ if (!committed)
539
+ return [];
540
+ const files = [[projectDir, committed.agentsMd], ...committed.workspaces.map((ws) => [ws.dir, ws.agentsMd])];
541
+ const problems = [];
542
+ for (const [dir, text] of files) {
543
+ const range = blockRange(text);
544
+ if (text === undefined || range === undefined)
545
+ continue;
546
+ const line = text.slice(0, range[0]).split('\n').length;
547
+ if (line <= TOP_LINES)
548
+ continue;
549
+ const rel = relPosix(fs.realpathSync(projectDir), path.join(fs.realpathSync(dir), 'AGENTS.md'));
550
+ problems.push(`The harness block in ${rel} starts at line ${line}. Agents that read only the first ${TOP_LINES} lines, such as with \`head -30\`, miss it. Move the block to the top of its file, where sync keeps it.`);
551
+ }
552
+ return problems;
553
+ }
554
+ /**
555
+ * Whether a model run may write the repository's entries, because they are as a person reviewed them (spec 6.2,
556
+ * rule 4). Undefined when there is nothing to hold, and in a Codex run, whose sandbox keeps `.codex/` read-only.
557
+ */
558
+ function reviewedFor(projectDir, team, plan) {
559
+ if (team === undefined || plan.committed === undefined || plan.exec.team === undefined || codexRun())
560
+ return undefined;
561
+ if (plan.telemetryHeld === undefined && heldEntries('team', plan.exec.team, repoStateFile(projectDir)).length === 0)
562
+ return undefined;
563
+ return reviewedState(projectDir, team, plan.committed.lock);
564
+ }
565
+ /**
566
+ * What a sync by the agent's model would leave pending and hold back now (spec 6.2, rule 4), and what any sync would
567
+ * write because it is in the reviewed state. `status` and `doctor` show it; `sync` reports the same list from what it
568
+ * wrote, so the count matches everywhere.
569
+ */
570
+ function preview(projectDir, resolved) {
571
+ const plan = resolved.mode !== 'none' ? computePlan(resolved.team, resolved.full, { widen: false }) : undefined;
572
+ const report = { pending: [], held: [] };
573
+ if (plan) {
574
+ const stateFile = repoStateFile(projectDir);
575
+ report.pending.push(...(plan.exec.team?.pending ?? []), ...plan.exec.added.pending);
576
+ report.held.push(...(plan.telemetryHeld !== undefined ? [plan.telemetryHeld] : []));
577
+ const team = plan.exec.team ? heldEntries('team', plan.exec.team, stateFile) : [];
578
+ const reviewed = reviewedFor(projectDir, resolved.team, plan);
579
+ if (reviewed?.ok === true && team.length > 0)
580
+ report.unwritten = { entries: team, branch: reviewed.branch };
581
+ else
582
+ report.held.push(...team);
583
+ if (reviewed?.ok === false && report.held.length > 0)
584
+ report.why = reviewed.reason;
585
+ report.held.push(...heldEntries('added', plan.exec.added, stateFile));
586
+ }
587
+ if (process.env['CI'] !== 'true')
588
+ report.held.push(...userHeld(resolved.added));
589
+ return { ...(plan ? { plan } : {}), report };
590
+ }
591
+ function describeAdded(h) {
592
+ return `${h.pkg.plugin} (${h.source.spec}, ${h.scope})${h.entry ? ', with an entry for this repository' : ''}`;
593
+ }
594
+ export function status(cwd, out) {
595
+ const projectDir = findProjectDir(cwd);
596
+ const resolved = resolveAll(projectDir, { withAdded: true });
597
+ const res = resolved.team ?? resolved.full;
598
+ const deps = res.packages.filter((p) => p.layer === 'dependencies');
599
+ const describe = (name, version) => `${name} ${version}`;
600
+ const tops = deps.filter((p) => p.direct);
601
+ const parts = tops.map((p) => {
602
+ const below = deps.filter((d) => p.closure.has(d.name)).map((d) => describe(d.name, d.version));
603
+ return below.length > 0 ? `${describe(p.name, p.version)} → ${below.join(', ')}` : describe(p.name, p.version);
604
+ });
605
+ parts.push(...deps.filter((d) => !d.direct && !tops.some((t) => t.closure.has(d.name))).map((d) => describe(d.name, d.version)));
606
+ out.log(`📦 dependencies ${parts.length > 0 ? parts.join(' · ') : 'none'}`);
607
+ const own = res.packages.find((p) => p.layer === 'project');
608
+ const config = res.config;
609
+ const counts = [
610
+ config.exclude.length > 0 ? `${config.exclude.length} exclude` : '',
611
+ Object.keys(config.replace).length > 0 ? `${Object.keys(config.replace).length} replace` : '',
612
+ Object.keys(config.patch).length > 0 ? `${Object.keys(config.patch).length} patch` : '',
613
+ ].filter(Boolean);
614
+ const projectParts = isFile(path.join(projectDir, CONFIG_FILE)) ? [`${CONFIG_FILE}: ${counts.length > 0 ? counts.join(' · ') : 'no changes'}`] : ['does not use harnesspm'];
615
+ if (own)
616
+ projectParts.push(`harness/ (plugin ${own.plugin})`);
617
+ out.log(`🏢 project ${projectParts.join(' · ')}`);
618
+ out.log(`➕ added ${resolved.added.length > 0 ? resolved.added.map(describeAdded).join(' · ') : 'none'}`);
619
+ const { plan, report } = preview(projectDir, resolved);
620
+ printPending(out, report, projectDir);
621
+ if (resolved.team) {
622
+ const changes = [...new Set(localRuleChanges(resolved.team, resolved.full).map(({ id }) => id))];
623
+ if (changes.length > 0)
624
+ out.log(`✏️ changed here ${changes.join(', ')} (by added harnesses; see CLAUDE.local.md)`);
625
+ const agents = plan.committed.agentsMd;
626
+ const bytes = Buffer.byteLength(agents);
627
+ const claudeLines = agents.split('\n').length + (plan.localMd ?? '').split('\n').length;
628
+ out.log(`📏 always-on Codex ${(bytes / 1024).toFixed(1)} KiB of 32 KiB · Claude Code ${claudeLines} lines`);
629
+ if (bytes > CODEX_LIMIT)
630
+ out.warn(`⚠️ AGENTS.md is over ${CODEX_OVER}. Move details into on-demand rules or docs.`);
631
+ else if (bytes > 28 * 1024)
632
+ out.warn("⚠️ AGENTS.md is close to Codex's 32 KiB limit. Move details into on-demand rules or docs.");
633
+ for (const miss of [...lateBlocks(projectDir, plan), ...codexMisses(projectDir, plan)])
634
+ out.warn(`⚠️ ${miss}`);
635
+ }
636
+ const telemetry = readTelemetryState(projectDir);
637
+ if (telemetry.config) {
638
+ out.log(`📡 telemetry ${telemetry.send !== undefined ? `${[...telemetry.events].join(', ')} → ${describeSend(telemetry.send)}` : telemetry.off}`);
639
+ }
640
+ const local = checkLocalFiles(projectDir, telemetryFiles(projectDir));
641
+ if (local && local.problems.length > 0)
642
+ out.log(`🩺 local files ${plural(local.problems.length, 'problem')}. Run \`${syncCommand(projectDir).replace(/ sync$/, ' doctor')}\`.`);
643
+ printWarnings(out, resolved.warnings);
644
+ return 0;
645
+ }
646
+ /** The command that runs harnesspm here: the installed one in a project that uses it (spec 10). */
647
+ const syncCommand = (_projectDir) => `${NPX_ANY} sync`;
648
+ /** A telemetry file inside the project, which harnesspm keeps out of git (spec 14.1). */
649
+ function telemetryFiles(projectDir) {
650
+ const send = readTelemetryState(projectDir).config?.send;
651
+ if (send === undefined || typeof send === 'string')
652
+ return [];
653
+ const rel = relPosix(projectDir, path.resolve(projectDir, send.file));
654
+ return rel.startsWith('../') || path.isAbsolute(rel) ? [] : [rel];
655
+ }
656
+ const linkPointsTo = (link, target) => {
657
+ try {
658
+ return fs.lstatSync(link).isSymbolicLink() && path.resolve(path.dirname(link), fs.readlinkSync(link)) === path.resolve(target);
659
+ }
660
+ catch {
661
+ return false;
662
+ }
663
+ };
664
+ /**
665
+ * `harnesspm doctor`: whether this repository is ready for harnesses, its own and a person's (spec 10.1).
666
+ * It changes nothing. Exits 1 when a check fails; warnings do not fail.
667
+ */
668
+ export function doctor(cwd, out) {
669
+ const projectDir = findProjectDir(cwd);
670
+ const usesHarnesspm = isFile(path.join(projectDir, CONFIG_FILE));
671
+ const sync = syncCommand(projectDir);
672
+ const groups = [];
673
+ // Per-machine files never reach a commit.
674
+ const local = checkLocalFiles(projectDir, telemetryFiles(projectDir), sync);
675
+ groups.push([
676
+ '🔒 Local files',
677
+ local === undefined
678
+ ? [{ level: 'warn', text: 'Not a git repository: nothing keeps per-machine files out of commits, and harnesses added with --local cannot be used here.' }]
679
+ : local.problems.length > 0
680
+ ? local.problems
681
+ : [{ level: 'ok', text: local.checked > 0 ? `${plural(local.checked, 'per-machine file')}: ignored by git and not tracked` : 'No per-machine files yet' }],
682
+ ]);
683
+ // A person can add a harness of their own here.
684
+ const own = [];
685
+ const exclude = gitExcludeFile(projectDir);
686
+ if (exclude !== undefined) {
687
+ const shown = relPosix(projectDir, exclude);
688
+ own.push(excludeWritable(exclude) ? { level: 'ok', text: `${shown} can be written, so harnesspm keeps per-machine files out of git` } : { level: 'fail', text: `${shown} cannot be written, so harnesspm cannot keep per-machine files out of git. Fix the permissions of that file.` });
689
+ }
690
+ const addedWarnings = [];
691
+ const added = process.env['CI'] === 'true' ? [] : loadAdded(exclude !== undefined ? projectDir : undefined, addedWarnings);
692
+ for (const warning of addedWarnings)
693
+ own.push({ level: 'fail', text: warning });
694
+ if (added.length > 0)
695
+ own.push({ level: 'ok', text: `Added: ${added.map(describeAdded).join(' · ')}` });
696
+ else if (addedWarnings.length === 0)
697
+ own.push({ level: 'info', text: `No harness added yet. Add one with \`${NPX_ANY} add <source>\`.` });
698
+ groups.push(['➕ Harnesses of your own', own]);
699
+ // Outputs are in place.
700
+ const outputs = [];
701
+ const resolved = resolveAll(projectDir, { withAdded: true });
702
+ const { plan, report } = preview(projectDir, resolved);
703
+ if (!usesHarnesspm)
704
+ outputs.push({ level: 'info', text: `This repository does not use harnesspm (no ${CONFIG_FILE}), so only added harnesses apply.` });
705
+ else if (!resolved.team)
706
+ outputs.push({ level: 'warn', text: `The dependencies are not installed. Install them, then run \`${sync}\`.` });
707
+ else {
708
+ const forCheck = resolveAll(projectDir, { withAdded: false });
709
+ const problems = checkPlan(projectDir, computePlan(forCheck.team, forCheck.full));
710
+ for (const p of problems)
711
+ outputs.push({ level: 'fail', text: /Run `/.test(p) ? p : `${p}. Run \`${sync}\` and commit the result.` });
712
+ if (problems.length === 0)
713
+ outputs.push({ level: 'ok', text: 'Committed outputs are up to date' });
714
+ }
715
+ if (plan) {
716
+ const total = plan.links.size + plan.generated.size;
717
+ let stale = 0;
718
+ for (const [link, target] of plan.links)
719
+ if (!linkPointsTo(link, target))
720
+ stale++;
721
+ for (const [file, content] of plan.generated)
722
+ if (readTextIfExists(file) !== content)
723
+ stale++;
724
+ if (stale > 0)
725
+ outputs.push({ level: 'warn', text: `${plural(stale, 'per-machine output')} missing or out of date. Run \`${sync}\`.` });
726
+ else if (total > 0)
727
+ outputs.push({ level: 'ok', text: `${plural(total, 'per-machine output')} in place` });
728
+ if (!plan.codexOurs)
729
+ outputs.push({ level: 'warn', text: '.codex/ belongs to the repository, so harnesspm writes nothing there and Codex misses some units.' });
730
+ const pkgJson = readJsonIfExists(path.join(projectDir, 'package.json'));
731
+ const dependency = harnesspmDependency(pkgJson) ?? PACKAGE_NAME;
732
+ for (const name of HOOK_SCRIPTS) {
733
+ const script = isRecord(pkgJson) && isRecord(pkgJson['scripts']) ? pkgJson['scripts'][name] : undefined;
734
+ if (typeof script !== 'string' || upgradedHook(script, dependency) === undefined)
735
+ continue;
736
+ outputs.push({ level: 'warn', text: script.endsWith(OLD_HOOK) ? `The "${name}" script runs \`harnesspm sync\` also when harnesspm is not installed, so an install without dev dependencies, such as \`npm ci --omit=dev\`, fails. Run \`${NPX_ANY} init\` to update it.` : `The "${name}" script checks for another name of harnesspm than ${dependency}, so it skips \`harnesspm sync\`. Run \`${NPX_ANY} init\` to update it.` });
737
+ }
738
+ if (OLD_PACKAGE_NAMES.includes(dependency))
739
+ outputs.push({ level: 'warn', text: `harnesspm moved from ${dependency} to ${PACKAGE_NAME}. Run \`npm i -D ${PACKAGE_NAME} && npm rm ${dependency}\`, then \`${NPX_ANY} init\`.` });
740
+ const schema = readJsonIfExists(path.join(projectDir, CONFIG_FILE))?.['$schema'];
741
+ if (typeof schema === 'string' && OLD_PACKAGE_NAMES.some((n) => schema.includes(`/${n}/`)))
742
+ outputs.push({ level: 'info', text: `The $schema in ${CONFIG_FILE} names the earlier package. It still works. The current one is ${CONFIG_SCHEMA}.` });
743
+ const bytes = plan.committed !== undefined ? Buffer.byteLength(plan.committed.agentsMd) : 0;
744
+ if (bytes > CODEX_LIMIT)
745
+ outputs.push({ level: 'warn', text: `AGENTS.md is ${kib(bytes)}, over ${CODEX_OVER}. Move details into on-demand rules or docs.` });
746
+ for (const miss of [...lateBlocks(projectDir, plan), ...codexMisses(projectDir, plan)])
747
+ outputs.push({ level: 'warn', text: miss });
748
+ }
749
+ if (outputs.length > 0)
750
+ groups.push(['📦 Outputs', outputs]);
751
+ // Trust: pending entries are not errors (spec 10.4).
752
+ const trust = [];
753
+ // Each pending entry already says how to turn it on: trust the package, or approve a pinned version.
754
+ for (const p of new Set(report.pending))
755
+ trust.push({ level: 'warn', text: `Off: ${p}` });
756
+ if (report.unwritten)
757
+ trust.push({ level: 'warn', text: `${unwrittenList(report.unwritten)} are not written yet. Run \`${sync}\`.` });
758
+ if (report.held.length > 0)
759
+ trust.push({ level: 'warn', text: `${heldList(report)}. ${grantStep(projectDir, `Run \`${NPX_ANY} sync\` in your own terminal.`)}` });
760
+ const telemetry = readTelemetryState(projectDir);
761
+ // A held handler is in the list above, as `sync` lists it.
762
+ const heldHandler = plan?.telemetryHeld !== undefined;
763
+ if (telemetry.config && telemetry.send === undefined && !heldHandler)
764
+ trust.push({ level: telemetry.off?.startsWith('held') ? 'warn' : 'info', text: `Telemetry ${telemetry.off}` });
765
+ if (trust.length === 0 && plan)
766
+ trust.push({ level: 'ok', text: 'Nothing waits for trust' });
767
+ if (trust.length > 0)
768
+ groups.push(['🛡️ Trust', trust]);
769
+ for (const [title, findings] of groups) {
770
+ out.log(title);
771
+ for (const finding of findings)
772
+ out.log(formatFinding(finding));
773
+ }
774
+ const failed = groups.flatMap(([, findings]) => findings).filter((f) => f.level === 'fail').length;
775
+ out.log('');
776
+ out.log(failed > 0 ? `❌ ${plural(failed, 'problem')}. Each line above says how to fix it.` : '✅ Ready. Nothing to fix.');
777
+ return failed > 0 ? 1 : 0;
778
+ }
779
+ /** The unit `id` of a resolution, with the rules that apply in `cwd`. */
780
+ function findUnit(res, cwd, id) {
781
+ const visibleRules = rulesForDirectory(res, cwd);
782
+ const rules = visibleRules.filter((r) => r.id === id);
783
+ const skill = res.skills.find((s) => s.id === id);
784
+ const docs = res.docs.find((d) => d.id === id);
785
+ const exec = [...res.scripts, ...res.hooks, ...res.mcp, ...res.agents, ...res.permissions].find((u) => u.id === id);
786
+ return { visibleRules, rules, skill, docs, exec, pkg: rules[0]?.pkg ?? skill?.pkg ?? docs?.pkg ?? exec?.pkg };
787
+ }
788
+ /**
789
+ * A unit of a project entry that does not apply here, such as one an agent saw in another repository's
790
+ * `CLAUDE.local.md`: each entry folder of the user-scope added harnesses, resolved as in its repository (spec 8.1).
791
+ */
792
+ function entryUnitElsewhere(projectDir, cwd, id) {
793
+ if (process.env['CI'] === 'true')
794
+ return undefined;
795
+ for (const harness of loadAdded(undefined, [])) {
796
+ if (!id.startsWith(`${harness.pkg.plugin}:`))
797
+ continue;
798
+ for (const { dir, remotes } of entryFolders(harness.pkg)) {
799
+ const entry = entryPackage(harness.pkg, dir, remotes[0]);
800
+ if (!entry)
801
+ continue;
802
+ const res = resolve(projectDir, { team: false, added: [{ ...harness, entry }] });
803
+ const unit = findUnit(res, cwd, id);
804
+ if (unit.pkg?.entry)
805
+ return { res, unit, remotes };
806
+ }
807
+ }
808
+ return undefined;
809
+ }
810
+ export function why(cwd, id, out) {
811
+ const projectDir = findProjectDir(cwd);
812
+ let { full: res } = resolveAll(projectDir, { withAdded: true });
813
+ let unit = findUnit(res, cwd, id);
814
+ const excluded = res.excludedUnits.find((u) => u.id === id);
815
+ const elsewhere = unit.pkg === undefined && excluded === undefined ? entryUnitElsewhere(projectDir, cwd, id) : undefined;
816
+ if (elsewhere)
817
+ ({ res, unit } = elsewhere);
818
+ const { visibleRules, rules, skill, docs, exec, pkg } = unit;
819
+ const row = (label, value) => out.log(`${label.padEnd(11)} ${value}`);
820
+ const rel = (file) => {
821
+ for (const pkg of res.packages) {
822
+ if (pkg.layer === 'dependencies' && file.startsWith(pkg.dir + path.sep)) {
823
+ return path.posix.join(STATE_DIR.split(path.sep).join('/'), 'pkgs', pkg.name, relPosix(pkg.dir, file));
824
+ }
825
+ }
826
+ return file.startsWith(res.projectDir + path.sep) ? relPosix(res.projectDir, file) : file;
827
+ };
828
+ if (!pkg) {
829
+ if (excluded) {
830
+ row('excluded', `by ${excluded.by}`);
831
+ return 0;
832
+ }
833
+ const plugin = id.split(':')[0];
834
+ const all = [visibleRules, res.skills, res.docs, res.scripts, res.hooks, res.mcp, res.agents, res.permissions].flatMap((units) => units.map((u) => u.id));
835
+ const near = [...new Set(all.filter((x) => x.startsWith(`${plugin}:`)))].slice(0, 8);
836
+ throw new HarnessError(`No unit ${id}.${near.length > 0 ? ` Units of ${plugin}: ${near.join(', ')}` : ''}`);
837
+ }
838
+ if (pkg.layer !== 'added') {
839
+ sendEvent(readTelemetryState(res.projectDir), eventContext(res), { type: 'why', ...commandCaller(), unit: id, package: pkg.name, version: pkg.version, ...outsideField(res.projectDir) });
840
+ }
841
+ if (pkg.layer === 'project')
842
+ row('owner', `project ${pkg.name} (harness/)`);
843
+ else if (pkg.layer === 'added') {
844
+ const entry = pkg.entry ? `, entry for ${elsewhere ? elsewhere.remotes.join(', ') : 'this repository'}` : '';
845
+ row('owner', `added ${pkg.added.source.spec} (${pkg.scope} scope${entry})`);
846
+ }
847
+ else
848
+ row('owner', `dependency ${pkg.name} ${pkg.version}${pkg.via !== undefined ? ` (via ${pkg.via})` : ''}`);
849
+ if (rules.length > 0) {
850
+ for (const rule of rules) {
851
+ if (rules.length > 1)
852
+ row('applies in', describeMembers(rule.members));
853
+ row('source', rel(rule.source));
854
+ if (rule.replacedBy)
855
+ row('replaced', `by ${rule.replacedBy.by}: ${rel(rule.replacedBy.file)}`);
856
+ if (rule.original !== rule.source)
857
+ row('original', rel(rule.original));
858
+ for (const p of rule.patches)
859
+ row('patch', `${p.patch} (from ${p.by})`);
860
+ }
861
+ }
862
+ else {
863
+ row('source', rel(skill ? path.join(skill.dir, 'SKILL.md') : docs ? docs.dir : execSource(exec)));
864
+ }
865
+ // An entry's script runs only in its repository.
866
+ if (exec?.kind === 'scripts' && !elsewhere)
867
+ row('run', `${toolCommand(res.projectDir)} run ${pkg.plugin}:${exec.name}`);
868
+ // Deny and ask rules only restrict, so they need no trust (spec 6.1).
869
+ if (exec && exec.kind !== 'permissions' && pkg.layer === 'dependencies') {
870
+ const trust = res.config.trust[pkg.name];
871
+ row('trust', trust === true
872
+ ? 'yes'
873
+ : trust === 'pin'
874
+ ? 'pinned: active in the version approved in the lock'
875
+ : `no: it stays off. A person turns it on with "${pkg.name}": true in "trust" in ${CONFIG_FILE}.`);
876
+ }
877
+ if (skill?.replacedBy) {
878
+ row('replaced', `by ${skill.replacedBy.by}: ${rel(skill.replacedBy.file)}`);
879
+ row('original', rel(path.join(skill.original, 'SKILL.md')));
880
+ }
881
+ if (skill?.replacementConflict)
882
+ row('replacement', skill.replacementConflict);
883
+ if (pkg.layer === 'added') {
884
+ const rules = ['AGENTS.md', 'CONTRIBUTING.md'].map((f) => path.join(pkg.added.source.dir, f)).filter((f) => fs.existsSync(f));
885
+ if (rules.length > 0)
886
+ row('rules', rules.join(', '));
887
+ }
888
+ if (pkg.repository !== undefined)
889
+ row('repository', pkg.repository);
890
+ if (pkg.layer === 'project')
891
+ row('editable', `yes. Edit the source, then run \`${NPX_ANY} sync\`.`);
892
+ else if (pkg.layer === 'added') {
893
+ row('editable', pkg.added.source.editable ? "yes. Edit the source, then save it the way that harness's rules say." : 'no: it comes from npm. Change it in its own repository.');
894
+ }
895
+ else
896
+ row('editable', `no. Add a \`patch\`, \`replace\` or \`exclude\` in ${CONFIG_FILE}, or propose the change upstream.`);
897
+ return 0;
898
+ }
899
+ /** The file that defines an executable unit: a script or agent file, or the package's JSON for hooks, MCP servers and permissions. */
900
+ function execSource(unit) {
901
+ if (unit.kind === 'scripts' || unit.kind === 'agents')
902
+ return unit.file;
903
+ if (unit.kind === 'mcp')
904
+ return path.join(unit.pkg.harnessDir, 'mcp.json');
905
+ return path.join(unit.pkg.harnessDir, NS, unit.kind === 'hooks' ? 'hooks.json' : 'permissions.json');
906
+ }
907
+ /** Whether the caller's own folder, where harnesspm started, is inside `projectDir`. */
908
+ const callerInside = (projectDir) => insideDir(projectDir);
909
+ /** The project's folder as the caller names it, for `-C` and `cd`. */
910
+ const fromCaller = (projectDir) => shellWord(path.relative(process.cwd(), projectDir) || '.');
911
+ /** The command that runs the project's tools from where harnesspm started: with `-C` from outside it (spec 10.1). */
912
+ export function toolCommand(projectDir) {
913
+ return callerInside(projectDir) ? NPX_ANY : `${NPX_ANY} -C ${fromCaller(projectDir)}`;
914
+ }
915
+ /** The project's install, from the caller's folder. */
916
+ function installCommand(projectDir) {
917
+ const lock = LOCKFILES.find((file) => isFile(path.join(projectDir, file)));
918
+ const install = lock !== undefined ? INSTALLS[lock] : 'npm install';
919
+ return callerInside(projectDir) ? install : `cd ${fromCaller(projectDir)} && ${install}`;
920
+ }
921
+ /**
922
+ * The project's units for `run`, `mcp` and `help` (spec 10.1). A project without an install uses the harness packages
923
+ * that `fetch` downloaded. With `fetch`, the packages that are missing are downloaded first.
924
+ */
925
+ function resolveTools(projectDir, options = {}) {
926
+ const resolved = resolveAll(projectDir, { withAdded: true });
927
+ if (resolved.team || !isFile(path.join(projectDir, CONFIG_FILE)))
928
+ return { res: resolved.full, installed: true, missing: [], locked: true };
929
+ let where = locateLocked(projectDir);
930
+ if (where === undefined)
931
+ return { res: resolved.full, installed: false, missing: [], locked: false };
932
+ if (where.missing.length > 0 && options.fetch) {
933
+ const out = options.fetch;
934
+ out.warn(`harnesspm: ${relPosix(process.cwd(), projectDir) || '.'} has no install, so harnesspm fetches its harness packages first. Fetching runs no package code.`);
935
+ try {
936
+ fetch(projectDir, { log: out.warn, warn: out.warn });
937
+ }
938
+ catch (error) {
939
+ if (!(error instanceof HarnessError))
940
+ throw error;
941
+ out.warn(`⚠️ ${error.message}`);
942
+ }
943
+ where = locateLocked(projectDir);
944
+ }
945
+ const located = where.located;
946
+ const res = resolve(projectDir, { added: resolved.added, locate: (name) => located.get(name) });
947
+ return { res, installed: false, missing: where.missing, locked: true };
948
+ }
949
+ /** Why a project without an install has no unit `ref`, or undefined when that is not the reason. */
950
+ function notAvailable(projectDir, tools, what) {
951
+ if (tools.installed || (tools.locked && tools.missing.length === 0))
952
+ return undefined;
953
+ const fetchStep = tools.locked ? `Run \`${toolCommand(projectDir)} fetch\` to use the ${what} that need nothing else, or install the project with` : 'Install the project with';
954
+ return `${relPosix(process.cwd(), projectDir) || 'This project'} has no install and no fetched harness packages, so its ${what} are not available yet. ${fetchStep} \`${installCommand(projectDir)}\`.`;
955
+ }
956
+ export function run(cwd, ref, args, agent) {
957
+ const projectDir = findProjectDir(cwd);
958
+ const tools = resolveTools(projectDir);
959
+ if (!tools.res.scripts.some((s) => `${s.pkg.plugin}:${s.name}` === ref)) {
960
+ const reason = notAvailable(projectDir, tools, 'scripts');
961
+ if (reason !== undefined)
962
+ throw new HarnessError(reason);
963
+ }
964
+ const context = tools.installed ? {} : { install: installCommand(projectDir) };
965
+ // A hook from a parent folder (spec 4.10): it runs in its project, as in a session there, and not for a file outside it.
966
+ if (agent !== undefined && !insideDir(projectDir)) {
967
+ const input = hookInput();
968
+ if (fileOutside(input, projectDir))
969
+ return Promise.resolve(0);
970
+ return runScript(tools.res, ref, args, agent, { ...context, cwd: projectDir, input });
971
+ }
972
+ return runScript(tools.res, ref, args, agent, context);
973
+ }
974
+ /** The hook's JSON on stdin, or nothing when there is none to read. */
975
+ function hookInput() {
976
+ try {
977
+ return fs.readFileSync(0);
978
+ }
979
+ catch {
980
+ return Buffer.alloc(0);
981
+ }
982
+ }
983
+ /** Whether a hook's JSON names a file, such as the one an `Edit` changed, that is outside the project. */
984
+ function fileOutside(input, projectDir) {
985
+ try {
986
+ const payload = JSON.parse(input.toString('utf8'));
987
+ if (!isRecord(payload) || !isRecord(payload['tool_input']))
988
+ return false;
989
+ const file = payload['tool_input']['file_path'] ?? payload['tool_input']['notebook_path'];
990
+ if (typeof file !== 'string' || file === '')
991
+ return false;
992
+ const base = typeof payload['cwd'] === 'string' ? payload['cwd'] : process.cwd();
993
+ return !insideDir(projectDir, path.resolve(base, file));
994
+ }
995
+ catch {
996
+ return false;
997
+ }
998
+ }
999
+ export function mcp(cwd, ref, agent) {
1000
+ const projectDir = findProjectDir(cwd);
1001
+ const tools = resolveTools(projectDir);
1002
+ if (!tools.res.mcp.some((s) => `${s.pkg.plugin}:${s.name}` === ref)) {
1003
+ const reason = notAvailable(projectDir, tools, 'MCP servers');
1004
+ if (reason !== undefined)
1005
+ throw new HarnessError(reason);
1006
+ }
1007
+ return runMcp(tools.res, ref, agent);
1008
+ }
1009
+ /**
1010
+ * The project for `help`. Without an install it reads the fetched packages, and fetches them first when there are
1011
+ * none. Undefined when the project does not use harnesspm.
1012
+ */
1013
+ function helpView(cwd, out) {
1014
+ const projectDir = findProjectDir(cwd);
1015
+ if (!isFile(path.join(projectDir, CONFIG_FILE)))
1016
+ return undefined;
1017
+ const tools = resolveTools(projectDir, { fetch: out });
1018
+ const res = tools.res;
1019
+ const lock = readLock(projectDir);
1020
+ const { paths: projectPaths, display } = pathTools(res, () => path.join(projectDir, STATE_DIR), new Map(), []);
1021
+ // Paths in the managed block are relative to the project. From outside it, they start at the caller's folder.
1022
+ const base = callerInside(projectDir) ? undefined : path.relative(process.cwd(), projectDir);
1023
+ const shown = (p) => (base === undefined || path.isAbsolute(p) ? p : path.posix.join(base.split(path.sep).join('/'), p));
1024
+ // A stable path under node_modules/.harnesspm exists after a sync or a fetch. Else the file's own path.
1025
+ const existing = (p, file) => (path.isAbsolute(p) || fs.existsSync(path.join(projectDir, p)) ? p : relPosix(projectDir, file));
1026
+ return {
1027
+ projectDir,
1028
+ tools,
1029
+ res,
1030
+ rules: rulesForDirectory(res, cwd),
1031
+ command: toolCommand(projectDir),
1032
+ ...(base !== undefined ? { base } : {}),
1033
+ trusted: (pkg) => trustOf(pkg, res, lock).trusted,
1034
+ paths: {
1035
+ rule: (rule) => shown(existing(projectPaths.rule(rule), rule.source)),
1036
+ docsIndex: (pkg) => {
1037
+ const index = projectPaths.docsIndex(pkg);
1038
+ const docs = res.docs.find((d) => d.pkg === pkg);
1039
+ if (index === undefined || docs === undefined)
1040
+ return undefined;
1041
+ // The copy in .harnesspm/docs exists after a sync or a fetch. Else the package's own index, or its folder.
1042
+ const own = path.join(docs.dir, 'llms.txt');
1043
+ return shown(existing(index, isFile(own) ? own : docs.dir));
1044
+ },
1045
+ },
1046
+ file: (file) => shown(existing(display(file), file)),
1047
+ };
1048
+ }
1049
+ /** The lines above every part of `help` about the project: its name, where paths start, and whether it is installed. */
1050
+ function helpIntro(view, out) {
1051
+ const { projectDir, tools, res, base } = view;
1052
+ out.log(`This project: ${res.projectName}${base !== undefined ? ` (${fromCaller(projectDir)})` : ''}`);
1053
+ if (base !== undefined)
1054
+ out.log('Paths start at the current folder. The tools run here too, with -C.');
1055
+ if (!tools.installed)
1056
+ out.log(tools.missing.length > 0 ? `⚠️ No install and no fetched harness packages: ${notAvailable(projectDir, tools, 'tools')}` : `No install: tools run from the fetched harness packages. A tool that needs another package says so; install the project with \`${installCommand(projectDir)}\`.`);
1057
+ }
1058
+ const count = (n, word) => (n === 1 ? `1 ${word}` : `${n} ${word}s`);
1059
+ /**
1060
+ * The project's part of `help` (spec 10.1): one line per package, across workspaces, with what it covers and the
1061
+ * `help <package>` command that prints the rest.
1062
+ */
1063
+ export function projectHelp(cwd, out, named) {
1064
+ const view = helpView(cwd, out);
1065
+ if (view === undefined) {
1066
+ if (named)
1067
+ out.log(`\n${fromCaller(findProjectDir(cwd))} does not use harnesspm: it has no ${CONFIG_FILE}.`);
1068
+ return 0;
1069
+ }
1070
+ const { res, command } = view;
1071
+ out.log('');
1072
+ helpIntro(view, out);
1073
+ out.log('');
1074
+ const lines = res.packages
1075
+ .filter((p) => p.layer !== 'added')
1076
+ .map((pkg) => {
1077
+ const rules = view.rules.filter((r) => r.pkg === pkg);
1078
+ const always = rules.filter((r) => r.activation === 'always');
1079
+ const covers = pkg.description ?? [...new Set(always.map((r) => r.title))].join(', ');
1080
+ const parts = [
1081
+ rules.length > 0 ? count(new Set(rules.map((r) => r.id)).size, 'rule') : '',
1082
+ res.docs.some((d) => d.pkg === pkg) ? 'docs' : '',
1083
+ count(res.scripts.filter((s) => s.pkg === pkg && s.description !== undefined).length, 'tool'),
1084
+ count(res.mcp.filter((m) => m.pkg === pkg).length, 'MCP server'),
1085
+ count(res.skills.filter((k) => k.pkg === pkg).length, 'skill'),
1086
+ count(res.hooks.filter((h) => h.pkg === pkg).length, 'hook'),
1087
+ ].filter((part) => part !== '' && !part.startsWith('0 '));
1088
+ const name = `${pkg.name}${pkg.via !== undefined ? ` (via ${pkg.via})` : pkg.layer === 'project' ? ' (this project)' : ''}`;
1089
+ return `- ${name}${covers !== '' ? ` — ${covers}` : ''}. ${parts.length > 0 ? `${parts.join(', ')}: ` : ''}\`${command} help ${helpTarget(pkg)}\``;
1090
+ });
1091
+ out.log(lines.length > 0 ? lines.join('\n') : 'No harness units yet.');
1092
+ if (lines.length > 0)
1093
+ out.log(`\nA tool's options: \`${command} help <tool>\`. Run a tool: \`${command} run <tool> [args]\`.`);
1094
+ return 0;
1095
+ }
1096
+ /** How a rule becomes active, in words (spec 2.5). */
1097
+ function activationLine(rule, file) {
1098
+ if (rule.activation === 'always')
1099
+ return 'Always on.';
1100
+ if (rule.activation === 'file')
1101
+ return `When editing ${(rule.paths ?? []).map((p) => `\`${p.replace(/^\/(?!\/)/, '')}\``).join(', ')}${rule.description !== undefined ? ` — ${rule.description}` : ''}. File: ${file}`;
1102
+ return `On demand: ${rule.description}. File: ${file}`;
1103
+ }
1104
+ /** Who changed a rule's text: replacements and patches, as `why` lists them. */
1105
+ function changedBy(rule) {
1106
+ const by = [...new Set([rule.replacedBy?.by, ...rule.patches.map((p) => p.by)].filter((b) => b !== undefined))];
1107
+ return by.length > 0 ? `Changed by ${by.join(', ')}: this is the text agents get here.` : undefined;
1108
+ }
1109
+ function ruleHelp(view, rule, level) {
1110
+ const head = `${'#'.repeat(level)} ${rule.title} (${rule.id})`;
1111
+ const where = view.rules.some((other) => other.id === rule.id && other !== rule) ? `Applies in ${describeMembers(rule.members)}.` : undefined;
1112
+ const about = [where, activationLine(rule, view.paths.rule(rule)), changedBy(rule)].filter((l) => l !== undefined).join(' ');
1113
+ const body = demoteHeadings(ruleBodyWithoutTitle(rule), level - 1);
1114
+ return [head, about, ...(body !== '' ? [body] : [])].join('\n\n');
1115
+ }
1116
+ function trustNote(pkg) {
1117
+ return `Not trusted in this project, so they stay off and \`run\` refuses them. A person turns them on with "${pkg.name}": true in "trust" in ${CONFIG_FILE}.`;
1118
+ }
1119
+ function toolLines(view, script) {
1120
+ const ref = `${script.pkg.plugin}:${script.name}`;
1121
+ const lines = [`- \`${view.command} run ${ref}${script.usage !== undefined && !script.usage.includes('\n') ? ` ${script.usage}` : ' [args]'}\`${script.description !== undefined ? ` — ${script.description}` : ''} (${script.id})`];
1122
+ if (script.usage !== undefined && script.usage.includes('\n'))
1123
+ lines.push(...script.usage.split('\n').map((l) => ` ${l}`));
1124
+ return lines;
1125
+ }
1126
+ function hookLine(hook) {
1127
+ const on = Object.entries(hook.matchers).map(([agent, matcher]) => `${agent === 'claude' ? 'Claude Code' : 'Codex'}${matcher !== undefined && matcher !== '' && matcher !== '*' ? ` on \`${matcher}\`` : ''}`);
1128
+ return `- ${hook.event}, ${on.join(' and ')}: runs \`${hook.pkg.plugin}:${hook.run}\` (${hook.id})`;
1129
+ }
1130
+ function mcpLine(view, server) {
1131
+ return server.config['type'] === 'stdio' ? `- \`${view.command} mcp ${server.pkg.plugin}:${server.name}\` (${server.id})` : `- ${String(server.config['url'])} (${server.id})`;
1132
+ }
1133
+ /** Everything a package contributes, with the project's patches applied (spec 10.1, `help <package>`). */
1134
+ function packageHelp(view, pkg) {
1135
+ const { res } = view;
1136
+ const parts = [];
1137
+ const where = pkg.layer === 'project' ? 'this project' : pkg.layer === 'added' ? `added ${pkg.added?.source.spec ?? pkg.plugin}` : `${pkg.version}${pkg.via !== undefined ? `, via ${pkg.via}` : ''}`;
1138
+ parts.push(`# ${pkg.name} (${where}), plugin ${pkg.plugin}${pkg.description !== undefined ? `\n\n${pkg.description}` : ''}`);
1139
+ const trusted = view.trusted(pkg);
1140
+ const rules = view.rules.filter((r) => r.pkg === pkg);
1141
+ if (rules.length > 0)
1142
+ parts.push('## Rules', ...rules.map((r) => ruleHelp(view, r, 3)));
1143
+ const index = view.paths.docsIndex(pkg);
1144
+ if (index !== undefined)
1145
+ parts.push('## Docs', `- ${index} (${pkg.plugin}:docs)`);
1146
+ const scripts = res.scripts.filter((s) => s.pkg === pkg && s.description !== undefined);
1147
+ if (scripts.length > 0)
1148
+ parts.push('## Tools', [...(trusted ? [] : [`⚠️ ${trustNote(pkg)}`]), ...scripts.flatMap((s) => toolLines(view, s))].join('\n'));
1149
+ const servers = res.mcp.filter((m) => m.pkg === pkg);
1150
+ if (servers.length > 0)
1151
+ parts.push('## MCP servers', [...(trusted ? [] : [`⚠️ ${trustNote(pkg)}`]), ...servers.map((m) => mcpLine(view, m))].join('\n'));
1152
+ const skills = res.skills.filter((k) => k.pkg === pkg);
1153
+ if (skills.length > 0) {
1154
+ const line = (skill) => {
1155
+ const file = path.join(skill.dir, 'SKILL.md');
1156
+ const description = tryFrontmatter(readTextIfExists(file) ?? '', file).data['description'];
1157
+ return `- ${skill.name}: read ${view.file(file)} (${skill.id})${typeof description === 'string' ? `\n ${description}` : ''}`;
1158
+ };
1159
+ parts.push('## Skills', skills.map(line).join('\n'));
1160
+ }
1161
+ const hooks = res.hooks.filter((h) => h.pkg === pkg);
1162
+ if (hooks.length > 0)
1163
+ parts.push('## Hooks', [...(trusted ? [] : [`⚠️ ${trustNote(pkg)}`]), ...hooks.map(hookLine)].join('\n'));
1164
+ if (parts.length === 1)
1165
+ parts.push('No harness units.');
1166
+ return parts.join('\n\n');
1167
+ }
1168
+ /** One tool: its description, usage and the command that runs it. It never runs the script (spec 10.1, `help <tool>`). */
1169
+ function scriptHelp(view, script) {
1170
+ const ref = `${script.pkg.plugin}:${script.name}`;
1171
+ const lines = [`${ref} (${script.id}), from ${script.pkg.name}`];
1172
+ if (script.description !== undefined)
1173
+ lines.push('', script.description);
1174
+ else
1175
+ lines.push('', 'No description: hooks and MCP servers use it, agents do not run it themselves.');
1176
+ lines.push('');
1177
+ if (script.usage !== undefined)
1178
+ lines.push(`Usage: ${script.usage.split('\n').join('\n ')}`);
1179
+ else
1180
+ lines.push(`Usage: none declared. Its package can add "usage" next to "description" in its manifest. harnesspm does not run the script to ask.`);
1181
+ if (script.answers !== undefined)
1182
+ lines.push(`Exit: 0 is ok. ${script.answers.join(', ')} ${script.answers.length > 1 ? 'are answers' : 'is an answer'}, such as "found problems", not a broken tool. Any other code is a failure.`);
1183
+ lines.push(`Run: ${view.command} run ${ref} [args]`);
1184
+ if (!view.trusted(script.pkg))
1185
+ lines.push('', `⚠️ ${trustNote(script.pkg)}`);
1186
+ return lines.join('\n');
1187
+ }
1188
+ /**
1189
+ * `help <target>`: a package or plugin, a rule ID, or a tool by `<plugin>:<script>` or its ID (spec 10.1). It works
1190
+ * without an install, like `help`, and sends a `help` event (spec 14.2).
1191
+ */
1192
+ export function targetHelp(cwd, target, out) {
1193
+ const view = helpView(cwd, out);
1194
+ if (view === undefined)
1195
+ throw new HarnessError(`No command "${target}", and ${fromCaller(findProjectDir(cwd))} does not use harnesspm, so it has no packages, rules or tools. Run \`harnesspm help\`.`);
1196
+ const { res } = view;
1197
+ const pkg = res.packages.find((p) => p.name === target || p.plugin === target);
1198
+ const rules = pkg === undefined ? view.rules.filter((r) => r.id === target) : [];
1199
+ const rule = rules[0];
1200
+ const script = pkg === undefined && rule === undefined ? res.scripts.find((s) => `${s.pkg.plugin}:${s.name}` === target || s.id === target) : undefined;
1201
+ const owner = pkg ?? rule?.pkg ?? script?.pkg;
1202
+ if (owner === undefined) {
1203
+ const reason = notAvailable(view.projectDir, view.tools, 'harness packages');
1204
+ if (reason !== undefined)
1205
+ throw new HarnessError(reason);
1206
+ const names = res.packages.map(helpTarget).join(', ');
1207
+ throw new HarnessError(`No command, package, rule or tool "${target}".${names !== '' ? ` Packages: ${names}.` : ''} \`${view.command} help\` lists them.`);
1208
+ }
1209
+ helpIntro(view, out);
1210
+ out.log('');
1211
+ out.log(pkg !== undefined ? packageHelp(view, pkg) : rule !== undefined ? rules.map((r) => ruleHelp(view, r, 1)).join('\n\n') : scriptHelp(view, script));
1212
+ // Units of added harnesses belong to a person: their use never reaches the team's handler (spec 14.2, rule 2).
1213
+ if (owner.layer !== 'added') {
1214
+ const repository = readIndex(res.projectDir)?.repository;
1215
+ const ctx = { ...eventContext(res), ...(repository !== undefined ? { repository } : {}) };
1216
+ const unit = rule?.id ?? script?.id;
1217
+ sendEvent(readTelemetryState(res.projectDir), ctx, { type: 'help', ...commandCaller(), ...(unit !== undefined ? { unit } : {}), package: owner.name, version: owner.version, ...outsideField(view.projectDir) }, callerInside(view.projectDir) ? process.cwd() : view.projectDir);
1218
+ }
1219
+ return 0;
1220
+ }
1221
+ /** Approves new versions of "pin" packages and writes what a model run left pending (spec 6.2). */
1222
+ export function approve(cwd, name, out) {
1223
+ if (caller() === 'model')
1224
+ throw new HarnessError('`harnesspm approve` is for a person. Ask the person to run it in their own terminal.');
1225
+ const projectDir = findProjectDir(cwd);
1226
+ const resolved = resolveAll(projectDir, { withAdded: false });
1227
+ if (resolved.team) {
1228
+ const lock = readLock(projectDir) ?? buildLock(resolved.team, undefined);
1229
+ let approved = 0;
1230
+ for (const pkg of resolved.team.packages) {
1231
+ if (resolved.team.config.trust[pkg.name] !== 'pin' || (name !== undefined && pkg.name !== name))
1232
+ continue;
1233
+ const entry = lock.packages[pkg.name];
1234
+ if (entry && entry.approved !== pkg.version) {
1235
+ entry.version = pkg.version;
1236
+ entry.approved = pkg.version;
1237
+ approved++;
1238
+ out.log(`✅ approved ${pkg.name} ${pkg.version}`);
1239
+ }
1240
+ }
1241
+ if (name !== undefined && approved === 0 && resolved.team.config.trust[name] !== 'pin')
1242
+ throw new HarnessError(`${name} is not a "pin" package in ${CONFIG_FILE}`);
1243
+ if (approved > 0)
1244
+ writeIfChanged(path.join(projectDir, LOCK_FILE), serializeLock(lock));
1245
+ }
1246
+ return sync(projectDir, out, { write: true });
1247
+ }
1248
+ /** What to do after `new`. `why` and `sync` reach the project's own harness only where the project uses harnesspm. */
1249
+ function nextAfterNew(projectDir, added) {
1250
+ const npx = NPX_ANY;
1251
+ if (added)
1252
+ return `Next: edit it, run \`${npx} sync\`, then save the change the way that harness's own AGENTS.md or CONTRIBUTING.md says.`;
1253
+ if (isFile(path.join(projectDir, CONFIG_FILE)))
1254
+ return `Next: edit it, then run \`${npx} sync\` and \`${npx} check\`.`;
1255
+ return `Next: edit it, then run \`${npx} check\`. To see the harness in this repository's AGENTS.md too, run \`${npx} init\`.`;
1256
+ }
1257
+ export function newUnit(cwd, kind, name, options, out) {
1258
+ const projectDir = findProjectDir(cwd);
1259
+ const show = (file) => (file.startsWith(projectDir + path.sep) ? relPosix(projectDir, file) : file);
1260
+ if (kind === 'patch') {
1261
+ const { full } = resolveAll(projectDir, { withAdded: true });
1262
+ const result = createPatch(projectDir, { ...full, rules: rulesForDirectory(full, cwd) }, name, options);
1263
+ out.log(`Wrote ${show(result.file)}, registered in ${show(result.registeredIn)}.`);
1264
+ out.log('Keep only the sections you change and edit them. Delete the others. To drop a section, list its heading in `remove:` frontmatter.');
1265
+ }
1266
+ else {
1267
+ if (!KINDS.includes(kind))
1268
+ throw new HarnessError(`Unknown kind "${kind}". Use one of: ${KINDS.join(', ')}, patch.`);
1269
+ const target = resolveTarget(projectDir, options);
1270
+ const files = [...new Set([...target.written, ...createUnit(target, kind, name)])];
1271
+ out.log(`Wrote in ${target.label}:`);
1272
+ for (const file of files)
1273
+ out.log(` ${show(file)}`);
1274
+ out.log(nextAfterNew(projectDir, options.to !== undefined));
1275
+ }
1276
+ sync(projectDir, out, { quiet: true, write: true });
1277
+ return 0;
1278
+ }
1279
+ export function fetch(cwd, out) {
1280
+ const projectDir = findProjectDir(cwd);
1281
+ const report = fetchLocked(projectDir);
1282
+ printWarnings(out, report.warnings);
1283
+ out.log(`harnesspm: fetched ${plural(report.fetched.length, 'package')}${report.fetched.length > 0 ? ` (${report.fetched.join(', ')})` : ''}, reused ${report.reused.length}.`);
1284
+ return 0;
1285
+ }
1286
+ export function check(target, out) {
1287
+ const result = checkHarness(target);
1288
+ printWarnings(out, result.warnings);
1289
+ for (const e of result.errors)
1290
+ out.log(`❌ ${e}`);
1291
+ out.log(`📏 always-on text of ${result.plugin}: ${kib(result.alwaysOnBytes)}`);
1292
+ // In its repository, an entry's always-on rules add to the harness's (spec 2.10).
1293
+ for (const entry of result.entries)
1294
+ out.log(`📏 always-on text of the entry ${entry.dir} (${entry.remotes.join(', ')}): ${kib(entry.alwaysOnBytes)}`);
1295
+ if (result.errors.length > 0)
1296
+ return 1;
1297
+ out.log('✅ harness is valid');
1298
+ return 0;
1299
+ }