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