@harnesspm/cli 0.0.0-snapshot.412a718 → 0.0.0-snapshot.5e392dd

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.
package/dist/commands.js CHANGED
@@ -14,14 +14,15 @@ import { fetchLocked, locateLocked } from './fetch.js';
14
14
  import { createPatch, createUnit, KINDS, resolveTarget } from './new.js';
15
15
  import { reviewedState } from './reviewed.js';
16
16
  import { runMcp, runScript } from './run.js';
17
- import { pathTools } from './outputs.js';
17
+ import { DOCS_EXCLUDE, DOCS_PROBE, pathTools } from './outputs.js';
18
+ import { afterInit, EVERY_COMMAND, nextAfterNew, startText, version } from './start.js';
18
19
  import { alwaysOnText, blockRange, helpTarget, ruleBodyWithoutTitle } from './render.js';
19
20
  import { describeMembers, localRuleChanges, resolve, resolvePackageDir, rulesForDirectory } from './resolve.js';
20
21
  import { demoteHeadings } from './sections.js';
21
22
  import { tryFrontmatter } from './frontmatter.js';
22
23
  import { commandCaller, describeSend, outsideField, readIndex, readTelemetryState, sendEvent } from './telemetry.js';
23
24
  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 { HarnessError, NPX_ANY, OLD_PACKAGE_NAMES, PACKAGE_NAME, PACKAGE_NAMES, addExclude, codexRun, gitExclude, gitExcludeFile, gitIgnoreSource, inCloudSession, insideDir, isDir, isFile, isRecord, readJson, readJsonIfExists, readTextIfExists, relPosix, runner, shellWord, writeIfChanged } from './util.js';
25
26
  import { spawnSync } from 'node:child_process';
26
27
  const printWarnings = (out, warnings) => {
27
28
  for (const w of [...new Set(warnings)])
@@ -32,25 +33,34 @@ const plural = (count, word, many = `${word}s`) => `${count} ${count === 1 ? wor
32
33
  * Where a person grants what an agent could not. A Claude Code cloud session has no terminal of the person's, and its
33
34
  * container goes away, so there the setup script runs the command, before each new session starts (spec 9).
34
35
  */
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) {
36
+ const cloudStep = (what) => `A Claude Code cloud session gives the person no terminal, so the environment's setup script grants this before each new session: ask them to add ${what} to it.`;
37
+ /** `withAdd` also names a person's own `add`, which grants entries of added harnesses; trusting a package needs only the install. */
38
+ function grantStep(projectDir, inTerminal, withAdd = true) {
37
39
  if (!inCloudSession())
38
40
  return inTerminal;
39
41
  const line = setupLine(projectDir);
40
- return cloudStep(`${line !== undefined ? `\`${line}\`` : 'the install'}, or their own \`${NPX_ANY} add <source>\`,`, 'these entries');
42
+ const install = line !== undefined ? `\`${line}\`` : "the project's install";
43
+ return cloudStep(withAdd ? `${install}, or their own \`${NPX_ANY} add <source>\`,` : install);
41
44
  }
42
45
  const firstThree = (items) => `${items.slice(0, 3).join('; ')}${items.length > 3 ? '; …' : ''}`;
43
46
  const heldList = (report) => `${plural(report.held.length, 'entry', 'entries')} that an agent cannot grant (${firstThree(report.held)})${report.why !== undefined ? `, because ${report.why}` : ''}`;
44
47
  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
- }
48
+ /** The person's step for everything an agent cannot grant itself (spec 6.2, rule 4). */
49
+ const APPROVE = `A person runs \`${NPX_ANY} approve\` in their own terminal.`;
50
+ const WAITING = '⏳ Waiting for a person';
51
+ /**
52
+ * Everything that waits for a person, one line each with the step that ends the wait: packages to trust or versions to
53
+ * approve, and entries an agent's run held back (spec 6.2). What any sync writes is not a person's step.
54
+ */
55
+ function waitingLines(report, projectDir) {
56
+ return [...new Set(report.pending), ...(report.held.length > 0 ? [`${heldList(report)}. ${grantStep(projectDir, APPROVE)}`] : [])];
57
+ }
58
+ function printWaiting(out, lines) {
59
+ if (lines.length === 0)
60
+ return;
61
+ out.log(WAITING);
62
+ for (const line of lines)
63
+ out.log(` - ${line}`);
54
64
  }
55
65
  /** The repository to work on: the nearest folder with harnesspm.json, else the git root, else `cwd`. */
56
66
  export function findProjectDir(cwd) {
@@ -102,23 +112,36 @@ function resolveAll(projectDir, options) {
102
112
  * so that an install's sync cannot hide a missed sync from a later `sync --check` (spec 6.4, 10.1).
103
113
  */
104
114
  export function sync(cwd, out, options = {}) {
105
- const projectDir = findProjectDir(cwd);
106
115
  if (options.check && options.write)
107
116
  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');
117
+ if (options.check)
118
+ return syncCheck(findProjectDir(cwd), out);
119
+ const done = syncProject(cwd, out, options);
120
+ printWaiting(out, waitingLines(done.report, done.projectDir));
121
+ if (options.quiet)
120
122
  return 0;
123
+ if (done.keptCommitted)
124
+ out.log(`CI: committed outputs left as they are; \`${NPX_ANY} sync --check\` compares them, \`sync --write\` writes them.`);
125
+ out.log(done.changed > 0 ? `harnesspm: ${done.what}. Updated ${plural(done.changed, 'file')}.` : `harnesspm: ${done.what}. Nothing changed.`);
126
+ return 0;
127
+ }
128
+ function syncCheck(projectDir, out) {
129
+ const { team, full, warnings } = resolveAll(projectDir, { withAdded: false });
130
+ const plan = computePlan(team, full);
131
+ printWarnings(out, [...warnings, ...plan.warnings]);
132
+ const problems = checkPlan(projectDir, plan);
133
+ for (const p of problems)
134
+ out.log(`❌ ${p}`);
135
+ if (problems.length > 0) {
136
+ out.log(`Run \`${NPX_ANY} sync\` and commit the result.`);
137
+ return 1;
121
138
  }
139
+ out.log('✅ harnesspm outputs are up to date');
140
+ return 0;
141
+ }
142
+ /** Writes every output, as `sync` does, and prints only the warnings. */
143
+ function syncProject(cwd, out, options) {
144
+ const projectDir = findProjectDir(cwd);
122
145
  const resolved = resolveAll(projectDir, { withAdded: true });
123
146
  const { full, mode } = resolved;
124
147
  const warnings = [...resolved.warnings];
@@ -170,19 +193,13 @@ export function sync(cwd, out, options = {}) {
170
193
  if (process.env['CI'] !== 'true' && !model)
171
194
  changed.push(...migrateSessionHook());
172
195
  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
196
  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
197
  const above = `Sessions that start here get the hooks of ${plural(children.length, 'project')} below: ${children.map((c) => path.basename(c)).join(', ')}`;
180
198
  const gone = 'No projects below this folder any more: removed what an earlier sync wrote for them';
181
199
  const below = `Added harnesses in ${plural(applied.length, 'repository', 'repositories')} below: ${applied.join(', ')}`;
182
200
  const parts = [...(children.length > 0 ? [above] : parentSync ? [gone] : []), ...(applied.length > 0 ? [below] : [])];
183
201
  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;
202
+ return { projectDir, report, what, mode, changed: changed.length, keptCommitted };
186
203
  }
187
204
  /**
188
205
  * Writes one project's outputs, as `sync` in it does. `keepCommitted` leaves the committed outputs as they are and
@@ -273,17 +290,89 @@ function harnesspmDependency(pkg) {
273
290
  }));
274
291
  }
275
292
  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',
293
+ /** Lockfiles that an install changes, with the package manager that writes each one. */
294
+ const LOCKS = {
295
+ 'package-lock.json': 'npm',
296
+ 'npm-shrinkwrap.json': 'npm',
297
+ 'pnpm-lock.yaml': 'pnpm',
298
+ 'yarn.lock': 'yarn',
299
+ 'bun.lock': 'bun',
300
+ 'bun.lockb': 'bun',
301
+ };
302
+ /** The install that each package manager's lockfile asks for, and its command that adds a dev dependency. */
303
+ const MANAGERS = {
304
+ npm: { install: 'npm ci', add: 'npm i -D' },
305
+ pnpm: { install: 'pnpm install', add: 'pnpm add -D' },
306
+ yarn: { install: 'yarn install', add: 'yarn add -D' },
307
+ bun: { install: 'bun install', add: 'bun add -d' },
284
308
  };
285
309
  /** `init` names the lockfile the project has with the files to commit. */
286
- const LOCKFILES = Object.keys(INSTALLS);
310
+ const LOCKFILES = Object.keys(LOCKS);
311
+ const lockfileOf = (projectDir) => LOCKFILES.find((file) => isFile(path.join(projectDir, file)));
312
+ /** The project's package manager: by its lockfile, else by its `packageManager` field, else npm. */
313
+ function managerOf(projectDir, pkg) {
314
+ const lock = lockfileOf(projectDir);
315
+ if (lock !== undefined)
316
+ return LOCKS[lock];
317
+ const field = typeof pkg['packageManager'] === 'string' ? /^(npm|pnpm|yarn|bun)@/.exec(pkg['packageManager'])?.[1] : undefined;
318
+ return field ?? 'npm';
319
+ }
320
+ /**
321
+ * Yarn 2 and later install with Plug'n'Play unless `.yarnrc.yml` sets another `nodeLinker`. Plug'n'Play writes no
322
+ * `node_modules`, where harnesspm finds each package's harness, so harnesspm supports Yarn with `nodeLinker: node-modules`.
323
+ */
324
+ function yarnPnp(projectDir) {
325
+ if (isFile(path.join(projectDir, '.pnp.cjs')))
326
+ return true;
327
+ const rc = readTextIfExists(path.join(projectDir, '.yarnrc.yml'));
328
+ return rc !== undefined && !/^nodeLinker:\s*["']?node-modules\b/m.test(rc);
329
+ }
330
+ /**
331
+ * The path or spec of a Yarn plugin in `.yarnrc.yml` that names harnesspm, such as one that syncs after every install
332
+ * (spec 10.1). With one, the install hook would sync a second time on each install.
333
+ */
334
+ function yarnSyncPlugin(projectDir) {
335
+ const rc = readTextIfExists(path.join(projectDir, '.yarnrc.yml'));
336
+ const section = rc === undefined ? undefined : /^plugins:[ \t]*\r?\n((?:(?:[ \t]+[^\r\n]*|[ \t]*)(?:\r?\n|$))*)/m.exec(rc)?.[1];
337
+ for (const line of section?.split(/\r?\n/) ?? []) {
338
+ const entry = /^\s*-?\s*(?:(?:path|spec):\s*)?["']?([^"'\s#]*harnesspm[^"'\s#]*)/.exec(line)?.[1];
339
+ if (entry !== undefined)
340
+ return entry;
341
+ }
342
+ return undefined;
343
+ }
344
+ /**
345
+ * Adds harnesspm as a dev dependency with the project's package manager, at this version or a later compatible one
346
+ * (spec 10.1), and returns the command. A workspace root needs pnpm's `-w` and Yarn 1's `-W`. The package manager's
347
+ * own output goes to stderr, so the report on stdout stays as `init` prints it.
348
+ */
349
+ function installHarnesspm(projectDir, manager, pkg) {
350
+ const root = manager === 'pnpm' ? isFile(path.join(projectDir, 'pnpm-workspace.yaml')) : manager === 'yarn' && 'workspaces' in pkg && !isFile(path.join(projectDir, '.yarnrc.yml'));
351
+ const add = `${MANAGERS[manager].add}${root ? (manager === 'pnpm' ? ' -w' : ' -W') : ''}`;
352
+ const own = version();
353
+ const spec = `${PACKAGE_NAME}@${own.includes('-') ? own : `^${own}`}`;
354
+ const windows = process.platform === 'win32';
355
+ const [command, ...args] = add.split(' ');
356
+ const result = spawnSync(windows ? `${add} ${spec}` : command, windows ? [] : [...args, spec], { cwd: projectDir, stdio: ['ignore', 2, 2], shell: windows });
357
+ if (result.status !== 0) {
358
+ throw new HarnessError(`\`${add} ${spec}\` failed${result.error ? ` (${result.error.message})` : ''}, so init stopped before it changed anything. Add ${PACKAGE_NAME} as a dev dependency yourself, then run \`${NPX_ANY} init\` again.`);
359
+ }
360
+ return add;
361
+ }
362
+ /**
363
+ * Adds `/.harnesspm/` to the project folder's `.gitignore`, so formatters skip the docs copies (spec 4.3, note 8), unless
364
+ * a `.gitignore` already ignores the folder. Only `init` edits `.gitignore`, and only this line. False outside git.
365
+ */
366
+ function ignoreDocsCopies(projectDir) {
367
+ if (gitExclude(projectDir) === undefined)
368
+ return false;
369
+ const source = gitIgnoreSource(projectDir, DOCS_PROBE);
370
+ if (typeof source === 'string' && !path.isAbsolute(source) && path.basename(source) === '.gitignore')
371
+ return false;
372
+ const file = path.join(projectDir, '.gitignore');
373
+ const text = readTextIfExists(file) ?? '';
374
+ return writeIfChanged(file, `${text}${text === '' || text.endsWith('\n') ? '' : '\n'}${DOCS_EXCLUDE}\n`);
375
+ }
287
376
  /**
288
377
  * The project's install for a Claude Code cloud environment's setup script (spec 9.1), or undefined when it is not
289
378
  * known. It names the project by its absolute path, because the setup script does not start in the clone. A pinned
@@ -294,20 +383,20 @@ function setupLine(projectDir) {
294
383
  // A folder above projects: its sync, after the projects' installs (spec 4.10).
295
384
  if (isParentFolder(projectDir))
296
385
  return `cd ${/^[\w./-]+$/.test(projectDir) ? projectDir : `'${projectDir.replaceAll("'", "'\\''")}'`} && ${NPX_ANY} sync`;
297
- const lock = LOCKFILES.find((file) => isFile(path.join(projectDir, file)));
386
+ const lock = lockfileOf(projectDir);
298
387
  if (lock === undefined || !isFile(path.join(projectDir, CONFIG_FILE)))
299
388
  return undefined;
300
389
  const pkg = readJsonIfExists(path.join(projectDir, 'package.json'));
301
390
  const corepack = isRecord(pkg) && typeof pkg['packageManager'] === 'string' ? 'corepack enable && COREPACK_NPM_REGISTRY=https://registry.npmjs.org ' : '';
302
391
  const dir = /^[\w./-]+$/.test(projectDir) ? projectDir : `'${projectDir.replaceAll("'", "'\\''")}'`;
303
- return `cd ${dir} && ${corepack}${INSTALLS[lock]}`;
392
+ return `cd ${dir} && ${corepack}${MANAGERS[LOCKS[lock]].install}`;
304
393
  }
305
394
  /** The committed files (spec 1.7) that git sees as new or changed, in a fixed order. Empty outside git. */
306
395
  function filesToCommit(projectDir) {
307
396
  const { team, full } = resolveAll(projectDir, { withAdded: false });
308
397
  const committed = team ? computePlan(team, full).committed : undefined;
309
398
  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])];
399
+ const candidates = [...new Set(['.gitignore', 'AGENTS.md', 'CLAUDE.md', ...nested.map((file) => relPosix(projectDir, file)), CONFIG_FILE, LOCK_FILE, 'package.json', ...LOCKFILES])];
311
400
  // The short format shows paths relative to the current folder, also in a subfolder of the repository.
312
401
  const result = spawnSync('git', ['status', '--short', '--untracked-files=all', '--', ...candidates], { cwd: projectDir, encoding: 'utf8' });
313
402
  if (result.status !== 0)
@@ -315,24 +404,75 @@ function filesToCommit(projectDir) {
315
404
  const changed = new Set(result.stdout.split('\n').filter((line) => line.length > 3).map((line) => line.slice(3).replace(/^.* -> /, '')));
316
405
  return candidates.filter((file) => changed.has(file));
317
406
  }
407
+ /** More tool lines than this, and `init` lists one line per package instead. */
408
+ const TOOL_LINES = 8;
409
+ /**
410
+ * The executable units of the packages that the project does not trust yet, as `init` lists them: each tool with what
411
+ * it does and whether it runs without a prompt, the hooks and MCP servers, or one line per package when there are many.
412
+ */
413
+ function untrustedTools(team) {
414
+ const rows = [];
415
+ const perPackage = [];
416
+ const packages = [];
417
+ for (const pkg of team.packages) {
418
+ if (pkg.layer !== 'dependencies' || team.config.trust[pkg.name] !== undefined)
419
+ continue;
420
+ const scripts = team.scripts.filter((s) => s.pkg === pkg);
421
+ const hooks = team.hooks.filter((h) => h.pkg === pkg);
422
+ const servers = team.mcp.filter((m) => m.pkg === pkg);
423
+ if (scripts.length + hooks.length + servers.length === 0)
424
+ continue;
425
+ packages.push(pkg.name);
426
+ const tools = scripts.filter((s) => s.description !== undefined);
427
+ for (const s of tools) {
428
+ const events = [...new Set(hooks.filter((h) => h.run === s.name).map((h) => h.event))];
429
+ rows.push([pkg.name, `${pkg.plugin}:${s.name} — ${s.description}${s.allow ? ' · no prompt' : ''}${events.length > 0 ? ` · a ${events.join(' and ')} hook runs it` : ''}`]);
430
+ }
431
+ for (const h of hooks)
432
+ if (!tools.some((s) => s.name === h.run))
433
+ rows.push([pkg.name, `a ${h.event} hook runs ${pkg.plugin}:${h.run}`]);
434
+ for (const m of servers)
435
+ rows.push([pkg.name, `MCP server ${pkg.plugin}:${m.name}`]);
436
+ const what = [plural(scripts.length, 'script'), plural(hooks.length, 'hook'), plural(servers.length, 'MCP server')].filter((w) => !w.startsWith('0 '));
437
+ perPackage.push([pkg.name, `${what.join(', ')}: \`${NPX_ANY} help ${helpTarget(pkg)}\``]);
438
+ }
439
+ const chosen = rows.length > TOOL_LINES ? perPackage : rows;
440
+ const width = Math.max(0, ...chosen.map(([name]) => name.length)) + 2;
441
+ return { lines: chosen.map(([name, text]) => ` ${name.padEnd(width)}${text}`), packages };
442
+ }
443
+ /**
444
+ * `harnesspm init` (spec 10.1): installs harnesspm when the project does not list it, writes the configuration, the
445
+ * install hook, the import in CLAUDE.md and the `.gitignore` line, syncs, and reports what waits for a person and what
446
+ * to commit.
447
+ */
318
448
  export function init(projectDir, out) {
319
449
  const pkgFile = path.join(projectDir, 'package.json');
320
450
  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);
451
+ throw new HarnessError(`No package.json here, so there is no project to set up. \`${NPX_ANY}\` names the tasks for this folder.`);
452
+ let pkg = readJson(pkgFile);
324
453
  if (!isRecord(pkg))
325
454
  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);
455
+ const manager = managerOf(projectDir, pkg);
456
+ if (manager === 'yarn' && yarnPnp(projectDir)) {
457
+ throw new HarnessError(`This project uses Yarn Plug'n'Play, which writes no node_modules, where harnesspm finds each package's harness. Set \`nodeLinker: node-modules\` in .yarnrc.yml, run \`yarn install\`, then run \`${NPX_ANY} init\` again.`);
458
+ }
459
+ // The script that `init` adds calls the `harnesspm` command, so the project must list harnesspm: without it, the next
460
+ // install fails with "harnesspm: not found" (research/package-managers.md). Install it first, before anything changes.
461
+ let dependency = harnesspmDependency(pkg);
329
462
  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\`.`);
463
+ const add = installHarnesspm(projectDir, manager, pkg);
464
+ pkg = readJson(pkgFile);
465
+ dependency = harnesspmDependency(pkg);
466
+ if (!isRecord(pkg) || dependency === undefined)
467
+ throw new HarnessError(`\`${add}\` did not list ${PACKAGE_NAME} in package.json. Add it as a dev dependency yourself, then run \`${NPX_ANY} init\` again.`);
468
+ out.log(`Installed ${PACKAGE_NAME} as a dev dependency (${add})`);
331
469
  }
470
+ const raw = readTextIfExists(pkgFile);
471
+ const wrote = [];
332
472
  const configFile = path.join(projectDir, CONFIG_FILE);
333
473
  if (!isFile(configFile)) {
334
474
  writeIfChanged(configFile, `${JSON.stringify({ $schema: CONFIG_SCHEMA }, null, 2)}\n`);
335
- out.log(`Created ${CONFIG_FILE}`);
475
+ wrote.push(CONFIG_FILE);
336
476
  }
337
477
  // A private package is never installed by others, so `postinstall` is safe there, and Yarn 2+ runs only
338
478
  // `postinstall`. A published package uses `prepare`, which does not run when others install it.
@@ -340,11 +480,15 @@ export function init(projectDir, out) {
340
480
  const hookName = pkg['private'] === true ? 'postinstall' : 'prepare';
341
481
  const has = (name) => typeof scripts[name] === 'string' && scripts[name].includes(OLD_HOOK);
342
482
  let changed = false;
343
- if (!HOOK_SCRIPTS.some(has)) {
483
+ const hooked = HOOK_SCRIPTS.some(has);
484
+ const plugin = hooked ? undefined : yarnSyncPlugin(projectDir);
485
+ if (plugin !== undefined)
486
+ out.log(`Added no install hook: the Yarn plugin ${plugin} in .yarnrc.yml runs harnesspm, and the hook would sync a second time on each install`);
487
+ else if (!hooked) {
344
488
  const current = typeof scripts[hookName] === 'string' ? scripts[hookName] : undefined;
345
489
  scripts[hookName] = current === undefined ? installHook(dependency) : `${current} && (${installHook(dependency)})`;
346
490
  changed = true;
347
- out.log(`Added \`harnesspm sync\` to the "${hookName}" script`);
491
+ wrote.push(`the "${hookName}" script (syncs on every install)`);
348
492
  }
349
493
  else {
350
494
  for (const name of HOOK_SCRIPTS) {
@@ -364,15 +508,40 @@ export function init(projectDir, out) {
364
508
  }
365
509
  const claude = claudeImport(projectDir);
366
510
  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;
511
+ wrote.push(`${relPosix(projectDir, claude.file)} (imports AGENTS.md)`);
512
+ if (ignoreDocsCopies(projectDir))
513
+ wrote.push(`.gitignore (${DOCS_EXCLUDE})`);
514
+ if (wrote.length > 0)
515
+ out.log(`Wrote ${wrote.join(', ')}`);
516
+ const done = syncProject(projectDir, out, { write: true });
517
+ out.log(`harnesspm: ${done.what}.${done.mode === 'full' ? ' Agents find them through the block in AGENTS.md.' : ''}`);
518
+ // What waits for a person, with the tools of each package that is not trusted, so the person can decide on trust.
519
+ const { team } = resolveAll(projectDir, { withAdded: false });
520
+ const tools = team ? untrustedTools(team) : { lines: [], packages: [] };
521
+ const others = waitingLines(done.report, projectDir).filter((line) => !tools.packages.some((name) => line.startsWith(`${name}: `)));
522
+ const waiting = tools.lines.length + others.length > 0;
523
+ // Without an installed dependency, the sync wrote no units, and its warning says why.
524
+ const full = done.mode === 'full';
525
+ out.log('');
526
+ if (!waiting)
527
+ out.log(full ? 'Rules, docs, skills and tools work now. Nothing waits for a person.' : 'Nothing waits for a person.');
528
+ else {
529
+ if (full)
530
+ out.log('Rules, docs and skills work now.');
531
+ out.log(`${WAITING}${tools.lines.length > 0 ? ': these tools stay off until a person trusts their package.' : ''}`);
532
+ for (const line of tools.lines)
533
+ out.log(line);
534
+ if (tools.lines.length > 0) {
535
+ const step = inCloudSession() ? ` and commits it. ${grantStep(projectDir, APPROVE, false)}` : `, then runs \`${NPX_ANY} approve\` in their own terminal.`;
536
+ out.log(` To turn one on, a person adds its package to "trust" in ${CONFIG_FILE}${step} An agent never changes "trust" itself.`);
537
+ }
538
+ for (const line of others)
539
+ out.log(` - ${line}`);
540
+ }
541
+ out.log('');
542
+ for (const line of afterInit(filesToCommit(projectDir), waiting))
543
+ out.log(line);
544
+ return 0;
376
545
  }
377
546
  /** Directories of editable added harnesses, which agents may write to (spec 8.5). */
378
547
  function writableDirs() {
@@ -388,7 +557,7 @@ function writableDirs() {
388
557
  function settingsAfterChange(out, hook) {
389
558
  if (caller() === 'model') {
390
559
  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.'}`);
560
+ out.log(` ${inCloudSession() ? cloudStep('the same command') : 'Ask the person to run the same command in their own terminal.'}`);
392
561
  return;
393
562
  }
394
563
  const anyUser = readList(configFileFor('user', '')).length > 0;
@@ -591,9 +760,35 @@ function preview(projectDir, resolved) {
591
760
  function describeAdded(h) {
592
761
  return `${h.pkg.plugin} (${h.source.spec}, ${h.scope})${h.entry ? ', with an entry for this repository' : ''}`;
593
762
  }
763
+ /** `harnesspm status`: the project's report (spec 10.5). It always exits 0. */
594
764
  export function status(cwd, out) {
595
- const projectDir = findProjectDir(cwd);
596
- const resolved = resolveAll(projectDir, { withAdded: true });
765
+ report(cwd, out);
766
+ return 0;
767
+ }
768
+ /** `harnesspm doctor`: the same report, which exits 1 when a check fails; what waits for a person does not fail. */
769
+ export function doctor(cwd, out) {
770
+ return report(cwd, out) > 0 ? 1 : 0;
771
+ }
772
+ /** The command that runs harnesspm here: the installed one in a project that uses it (spec 10). */
773
+ const syncCommand = (_projectDir) => `${NPX_ANY} sync`;
774
+ /** A telemetry file inside the project, which harnesspm keeps out of git (spec 14.1). */
775
+ function telemetryFiles(projectDir) {
776
+ const send = readTelemetryState(projectDir).config?.send;
777
+ if (send === undefined || typeof send === 'string')
778
+ return [];
779
+ const rel = relPosix(projectDir, path.resolve(projectDir, send.file));
780
+ return rel.startsWith('../') || path.isAbsolute(rel) ? [] : [rel];
781
+ }
782
+ const linkPointsTo = (link, target) => {
783
+ try {
784
+ return fs.lstatSync(link).isSymbolicLink() && path.resolve(path.dirname(link), fs.readlinkSync(link)) === path.resolve(target);
785
+ }
786
+ catch {
787
+ return false;
788
+ }
789
+ };
790
+ /** The layers and the always-on size: the report's first lines. */
791
+ function summary(projectDir, resolved, plan, out) {
597
792
  const res = resolved.team ?? resolved.full;
598
793
  const deps = res.packages.filter((p) => p.layer === 'dependencies');
599
794
  const describe = (name, version) => `${name} ${version}`;
@@ -615,60 +810,31 @@ export function status(cwd, out) {
615
810
  if (own)
616
811
  projectParts.push(`harness/ (plugin ${own.plugin})`);
617
812
  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) {
813
+ if (resolved.team && plan?.committed) {
622
814
  const changes = [...new Set(localRuleChanges(resolved.team, resolved.full).map(({ id }) => id))];
623
815
  if (changes.length > 0)
624
816
  out.log(`✏️ changed here ${changes.join(', ')} (by added harnesses; see CLAUDE.local.md)`);
625
817
  const agents = plan.committed.agentsMd;
626
- const bytes = Buffer.byteLength(agents);
627
818
  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}`);
819
+ out.log(`📏 always-on Codex ${kib(Buffer.byteLength(agents))} of 32 KiB · Claude Code ${claudeLines} lines`);
635
820
  }
636
821
  const telemetry = readTelemetryState(projectDir);
637
822
  if (telemetry.config) {
638
823
  out.log(`📡 telemetry ${telemetry.send !== undefined ? `${[...telemetry.events].join(', ')} → ${describeSend(telemetry.send)}` : telemetry.off}`);
639
824
  }
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
825
  }
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
826
  /**
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.
827
+ * The project's report, which `status`, `doctor` and the bare command in a project print (spec 10.5): the layers and
828
+ * sizes, then whether the repository is ready for harnesses, its own and a person's, then what waits for a person. It
829
+ * changes nothing, and each problem names the command that fixes it. Returns the number of failed checks.
667
830
  */
668
- export function doctor(cwd, out) {
831
+ function report(cwd, out) {
669
832
  const projectDir = findProjectDir(cwd);
670
833
  const usesHarnesspm = isFile(path.join(projectDir, CONFIG_FILE));
671
834
  const sync = syncCommand(projectDir);
835
+ const resolved = resolveAll(projectDir, { withAdded: true });
836
+ const { plan, report: waiting } = preview(projectDir, resolved);
837
+ summary(projectDir, resolved, plan, out);
672
838
  const groups = [];
673
839
  // Per-machine files never reach a commit.
674
840
  const local = checkLocalFiles(projectDir, telemetryFiles(projectDir), sync);
@@ -698,13 +864,9 @@ export function doctor(cwd, out) {
698
864
  groups.push(['➕ Harnesses of your own', own]);
699
865
  // Outputs are in place.
700
866
  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)
867
+ if (usesHarnesspm && !resolved.team)
706
868
  outputs.push({ level: 'warn', text: `The dependencies are not installed. Install them, then run \`${sync}\`.` });
707
- else {
869
+ else if (usesHarnesspm) {
708
870
  const forCheck = resolveAll(projectDir, { withAdded: false });
709
871
  const problems = checkPlan(projectDir, computePlan(forCheck.team, forCheck.full));
710
872
  for (const p of problems)
@@ -725,6 +887,9 @@ export function doctor(cwd, out) {
725
887
  outputs.push({ level: 'warn', text: `${plural(stale, 'per-machine output')} missing or out of date. Run \`${sync}\`.` });
726
888
  else if (total > 0)
727
889
  outputs.push({ level: 'ok', text: `${plural(total, 'per-machine output')} in place` });
890
+ // The repository's entries that any sync writes: not a person's step.
891
+ if (waiting.unwritten)
892
+ outputs.push({ level: 'warn', text: `${unwrittenList(waiting.unwritten)} are not written yet. Run \`${sync}\`.` });
728
893
  if (!plan.codexOurs)
729
894
  outputs.push({ level: 'warn', text: '.codex/ belongs to the repository, so harnesspm writes nothing there and Codex misses some units.' });
730
895
  const pkgJson = readJsonIfExists(path.join(projectDir, 'package.json'));
@@ -743,38 +908,36 @@ export function doctor(cwd, out) {
743
908
  const bytes = plan.committed !== undefined ? Buffer.byteLength(plan.committed.agentsMd) : 0;
744
909
  if (bytes > CODEX_LIMIT)
745
910
  outputs.push({ level: 'warn', text: `AGENTS.md is ${kib(bytes)}, over ${CODEX_OVER}. Move details into on-demand rules or docs.` });
911
+ else if (bytes > 28 * 1024)
912
+ outputs.push({ level: 'warn', text: "AGENTS.md is close to Codex's 32 KiB limit. Move details into on-demand rules or docs." });
746
913
  for (const miss of [...lateBlocks(projectDir, plan), ...codexMisses(projectDir, plan)])
747
914
  outputs.push({ level: 'warn', text: miss });
748
915
  }
749
916
  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]);
917
+ groups.push(['📝 Outputs', outputs]);
769
918
  for (const [title, findings] of groups) {
770
919
  out.log(title);
771
920
  for (const finding of findings)
772
921
  out.log(formatFinding(finding));
773
922
  }
923
+ // Each entry says how to turn it on: trust the package, approve a pinned version, or approve what an agent held back.
924
+ printWaiting(out, waitingLines(waiting, projectDir));
925
+ printWarnings(out, resolved.warnings);
774
926
  const failed = groups.flatMap(([, findings]) => findings).filter((f) => f.level === 'fail').length;
775
927
  out.log('');
776
928
  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;
929
+ return failed;
930
+ }
931
+ /**
932
+ * The bare command (spec 10.1): in a project that uses harnesspm, its report; elsewhere, what the folder is and the
933
+ * tasks for it, each with the one command that starts it.
934
+ */
935
+ export function start(cwd, out) {
936
+ if (isFile(path.join(findProjectDir(cwd), CONFIG_FILE)))
937
+ return status(cwd, out);
938
+ for (const line of startText(cwd))
939
+ out.log(line);
940
+ return 0;
778
941
  }
779
942
  /** The unit `id` of a resolution, with the rules that apply in `cwd`. */
780
943
  function findUnit(res, cwd, id) {
@@ -914,8 +1077,8 @@ export function toolCommand(projectDir) {
914
1077
  }
915
1078
  /** The project's install, from the caller's folder. */
916
1079
  function installCommand(projectDir) {
917
- const lock = LOCKFILES.find((file) => isFile(path.join(projectDir, file)));
918
- const install = lock !== undefined ? INSTALLS[lock] : 'npm install';
1080
+ const lock = lockfileOf(projectDir);
1081
+ const install = lock !== undefined ? MANAGERS[LOCKS[lock]].install : 'npm install';
919
1082
  return callerInside(projectDir) ? install : `cd ${fromCaller(projectDir)} && ${install}`;
920
1083
  }
921
1084
  /**
@@ -1031,6 +1194,7 @@ function helpView(cwd, out) {
1031
1194
  command: toolCommand(projectDir),
1032
1195
  ...(base !== undefined ? { base } : {}),
1033
1196
  trusted: (pkg) => trustOf(pkg, res, lock).trusted,
1197
+ trust: (pkg) => trustOf(pkg, res, lock),
1034
1198
  paths: {
1035
1199
  rule: (rule) => shown(existing(projectPaths.rule(rule), rule.source)),
1036
1200
  docsIndex: (pkg) => {
@@ -1057,18 +1221,14 @@ function helpIntro(view, out) {
1057
1221
  }
1058
1222
  const count = (n, word) => (n === 1 ? `1 ${word}` : `${n} ${word}s`);
1059
1223
  /**
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.
1224
+ * `help` in a project (spec 10.1): one line per package, across workspaces, with what it covers and the
1225
+ * `help <package>` command that prints the rest. Undefined outside a project that uses harnesspm.
1062
1226
  */
1063
- export function projectHelp(cwd, out, named) {
1227
+ export function projectHelp(cwd, out) {
1064
1228
  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
- }
1229
+ if (view === undefined)
1230
+ return undefined;
1070
1231
  const { res, command } = view;
1071
- out.log('');
1072
1232
  helpIntro(view, out);
1073
1233
  out.log('');
1074
1234
  const lines = res.packages
@@ -1089,10 +1249,16 @@ export function projectHelp(cwd, out, named) {
1089
1249
  return `- ${name}${covers !== '' ? ` — ${covers}` : ''}. ${parts.length > 0 ? `${parts.join(', ')}: ` : ''}\`${command} help ${helpTarget(pkg)}\``;
1090
1250
  });
1091
1251
  out.log(lines.length > 0 ? lines.join('\n') : 'No harness units yet.');
1252
+ out.log('');
1092
1253
  if (lines.length > 0)
1093
- out.log(`\nA tool's options: \`${command} help <tool>\`. Run a tool: \`${command} run <tool> [args]\`.`);
1254
+ out.log(`A tool's options: \`${command} help <tool>\`. Run a tool: \`${command} run <tool> [args]\`.`);
1255
+ out.log(`${EVERY_COMMAND}.`);
1094
1256
  return 0;
1095
1257
  }
1258
+ /** Where `help` says that a folder named with `-C` does not use harnesspm. */
1259
+ export function notAProject(cwd) {
1260
+ return `${fromCaller(findProjectDir(cwd))} does not use harnesspm: it has no ${CONFIG_FILE}.`;
1261
+ }
1096
1262
  /** How a rule becomes active, in words (spec 2.5). */
1097
1263
  function activationLine(rule, file) {
1098
1264
  if (rule.activation === 'always')
@@ -1113,12 +1279,14 @@ function ruleHelp(view, rule, level) {
1113
1279
  const body = demoteHeadings(ruleBodyWithoutTitle(rule), level - 1);
1114
1280
  return [head, about, ...(body !== '' ? [body] : [])].join('\n\n');
1115
1281
  }
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}.`;
1282
+ /** Why a package's tools are off, and the person's step that turns them on (spec 6.2). */
1283
+ function trustNote(view, pkg) {
1284
+ const { reason = 'not trusted', action = '' } = view.trust(pkg);
1285
+ return `${reason.charAt(0).toUpperCase()}${reason.slice(1)}, so they stay off in this project and \`run\` refuses them. ${action}`;
1118
1286
  }
1119
1287
  function toolLines(view, script) {
1120
1288
  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})`];
1289
+ const lines = [`- \`${view.command} run ${ref}${script.usage !== undefined && !script.usage.includes('\n') ? ` ${script.usage}` : ' [args]'}\`${script.description !== undefined ? ` — ${script.description}` : ''}${script.allow ? ' · no prompt' : ''} (${script.id})`];
1122
1290
  if (script.usage !== undefined && script.usage.includes('\n'))
1123
1291
  lines.push(...script.usage.split('\n').map((l) => ` ${l}`));
1124
1292
  return lines;
@@ -1145,10 +1313,10 @@ function packageHelp(view, pkg) {
1145
1313
  parts.push('## Docs', `- ${index} (${pkg.plugin}:docs)`);
1146
1314
  const scripts = res.scripts.filter((s) => s.pkg === pkg && s.description !== undefined);
1147
1315
  if (scripts.length > 0)
1148
- parts.push('## Tools', [...(trusted ? [] : [`⚠️ ${trustNote(pkg)}`]), ...scripts.flatMap((s) => toolLines(view, s))].join('\n'));
1316
+ parts.push('## Tools', [...(trusted ? [] : [`⚠️ ${trustNote(view, pkg)}`]), ...scripts.flatMap((s) => toolLines(view, s))].join('\n'));
1149
1317
  const servers = res.mcp.filter((m) => m.pkg === pkg);
1150
1318
  if (servers.length > 0)
1151
- parts.push('## MCP servers', [...(trusted ? [] : [`⚠️ ${trustNote(pkg)}`]), ...servers.map((m) => mcpLine(view, m))].join('\n'));
1319
+ parts.push('## MCP servers', [...(trusted ? [] : [`⚠️ ${trustNote(view, pkg)}`]), ...servers.map((m) => mcpLine(view, m))].join('\n'));
1152
1320
  const skills = res.skills.filter((k) => k.pkg === pkg);
1153
1321
  if (skills.length > 0) {
1154
1322
  const line = (skill) => {
@@ -1160,7 +1328,7 @@ function packageHelp(view, pkg) {
1160
1328
  }
1161
1329
  const hooks = res.hooks.filter((h) => h.pkg === pkg);
1162
1330
  if (hooks.length > 0)
1163
- parts.push('## Hooks', [...(trusted ? [] : [`⚠️ ${trustNote(pkg)}`]), ...hooks.map(hookLine)].join('\n'));
1331
+ parts.push('## Hooks', [...(trusted ? [] : [`⚠️ ${trustNote(view, pkg)}`]), ...hooks.map(hookLine)].join('\n'));
1164
1332
  if (parts.length === 1)
1165
1333
  parts.push('No harness units.');
1166
1334
  return parts.join('\n\n');
@@ -1180,9 +1348,11 @@ function scriptHelp(view, script) {
1180
1348
  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
1349
  if (script.answers !== undefined)
1182
1350
  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.`);
1351
+ if (script.allow)
1352
+ lines.push('Allow: runs without a prompt in a project that trusts its package.');
1183
1353
  lines.push(`Run: ${view.command} run ${ref} [args]`);
1184
1354
  if (!view.trusted(script.pkg))
1185
- lines.push('', `⚠️ ${trustNote(script.pkg)}`);
1355
+ lines.push('', `⚠️ ${trustNote(view, script.pkg)}`);
1186
1356
  return lines.join('\n');
1187
1357
  }
1188
1358
  /**
@@ -1192,7 +1362,7 @@ function scriptHelp(view, script) {
1192
1362
  export function targetHelp(cwd, target, out) {
1193
1363
  const view = helpView(cwd, out);
1194
1364
  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\`.`);
1365
+ throw new HarnessError(`No command "${target}", and ${fromCaller(findProjectDir(cwd))} does not use harnesspm, so it has no packages, rules or tools. ${EVERY_COMMAND}.`);
1196
1366
  const { res } = view;
1197
1367
  const pkg = res.packages.find((p) => p.name === target || p.plugin === target);
1198
1368
  const rules = pkg === undefined ? view.rules.filter((r) => r.id === target) : [];
@@ -1245,15 +1415,6 @@ export function approve(cwd, name, out) {
1245
1415
  }
1246
1416
  return sync(projectDir, out, { write: true });
1247
1417
  }
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
1418
  export function newUnit(cwd, kind, name, options, out) {
1258
1419
  const projectDir = findProjectDir(cwd);
1259
1420
  const show = (file) => (file.startsWith(projectDir + path.sep) ? relPosix(projectDir, file) : file);
@@ -1271,7 +1432,8 @@ export function newUnit(cwd, kind, name, options, out) {
1271
1432
  out.log(`Wrote in ${target.label}:`);
1272
1433
  for (const file of files)
1273
1434
  out.log(` ${show(file)}`);
1274
- out.log(nextAfterNew(projectDir, options.to !== undefined));
1435
+ for (const line of nextAfterNew(projectDir, options.to !== undefined))
1436
+ out.log(line);
1275
1437
  }
1276
1438
  sync(projectDir, out, { quiet: true, write: true });
1277
1439
  return 0;