@harnesspm/cli 0.0.0-snapshot.412a718
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +259 -0
- package/LICENSE +21 -0
- package/README.md +70 -0
- 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 +218 -0
- package/dist/commands.d.ts +58 -0
- package/dist/commands.js +1299 -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 +75 -0
- package/dist/exec-outputs.js +425 -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/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 +149 -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 +181 -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 +40 -0
- package/harness/skills/harnesspm-improve/SKILL.md +38 -0
- package/package.json +73 -0
- package/schema/harnesspm.schema.json +58 -0
package/dist/outputs.js
ADDED
|
@@ -0,0 +1,875 @@
|
|
|
1
|
+
// Repository outputs (spec 4.2, 4.3, 4.6): a plan, then apply it or compare it.
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { spawnSync } from 'node:child_process';
|
|
4
|
+
import * as fs from 'node:fs';
|
|
5
|
+
import * as path from 'node:path';
|
|
6
|
+
import { caller, harnesspmHome } from './added.js';
|
|
7
|
+
import { applyEntries, desiredEntries, tomlTables, trustOf } from './exec-outputs.js';
|
|
8
|
+
import { WIDENING_SKILL_KEYS } from './exec-units.js';
|
|
9
|
+
import { claudeJsonFile } from './homes.js';
|
|
10
|
+
import { tryFrontmatter, withFrontmatter } from './frontmatter.js';
|
|
11
|
+
import { CONFIG_FILE } from './config.js';
|
|
12
|
+
import { buildLock, LOCK_FILE, patchDrift, readLock, sameLock, serializeLock } from './lock.js';
|
|
13
|
+
import { alwaysOnText, extractBlock, hasClaudeImport, removeBlock, renderBlock, renderSections, sectionsFor, tomlString, upsertBlock, withClaudeImport, workspacesSection, wrapBlock, } from './render.js';
|
|
14
|
+
import { describeMembers, localRuleChanges, rulesById, skillAuthor } from './resolve.js';
|
|
15
|
+
import { headings } from './sections.js';
|
|
16
|
+
import { AGENT_EVENTS, INDEX_FILE, describeSend, sameSend, telemetryState } from './telemetry.js';
|
|
17
|
+
import { NPX_ANY, NPX_BARE, excludeEntry, exists, gitExclude, gitIgnoreSource, gitKeeps, gitKeepsOut, hash, isDir, isFile, isInside, isSymlink, linkIfChanged, listDir, readText, readTextIfExists, realpath, relativeLinks, relPosix, remoteKey, runner, writeIfChanged, } from './util.js';
|
|
18
|
+
export const STATE_DIR = path.join('node_modules', '.harnesspm');
|
|
19
|
+
/** Where the dependencies' docs are copied to, at the project root and outside node_modules (spec 4.3, note 8). */
|
|
20
|
+
export const DOCS_DIR = path.join('.harnesspm', 'docs');
|
|
21
|
+
/** The exclude entry and the `.gitignore` line that keep the root `.harnesspm/` folder out of git and of formatters. */
|
|
22
|
+
export const DOCS_EXCLUDE = '/.harnesspm/';
|
|
23
|
+
/** What harnesspm asks git about: the folder of the copies, so that a pattern for some files, such as `*.txt`, does not answer for all. */
|
|
24
|
+
export const DOCS_PROBE = '.harnesspm/docs/';
|
|
25
|
+
export const RGIGNORE_EXCLUDE = '/.rgignore';
|
|
26
|
+
const RGIGNORE_MARKER = '# Generated by `harnesspm sync`. Do not edit.';
|
|
27
|
+
// ripgrep never enters a folder that git ignores or that is hidden, so the folder of the docs copies is let in,
|
|
28
|
+
// and its other children are kept out (spec 4.3, note 8).
|
|
29
|
+
const RGIGNORE_LINES = ['!/.harnesspm/', '/.harnesspm/*', '!/.harnesspm/docs/'];
|
|
30
|
+
const RGIGNORE = `${RGIGNORE_MARKER}\n# Lets search tools that read this file, such as ripgrep, into the copies of the harness docs in .harnesspm/docs/.\n${RGIGNORE_LINES.join('\n')}\n`;
|
|
31
|
+
/**
|
|
32
|
+
* harnesspm's sections in the exclude file (spec 4.1). A project below the git root keys them by its path, such as
|
|
33
|
+
* `harnesspm in docs-site/`, so that two projects in one repository never rewrite each other's entries.
|
|
34
|
+
*/
|
|
35
|
+
function sectionMarks(prefix) {
|
|
36
|
+
const name = prefix === '' ? 'harnesspm' : `harnesspm in ${prefix}`;
|
|
37
|
+
return {
|
|
38
|
+
team: [`# BEGIN ${name} (generated by \`harnesspm sync\`; per-machine outputs)`, `# END ${name}`],
|
|
39
|
+
added: [`# BEGIN ${name}: added harnesses (generated by \`harnesspm sync\`; per-machine outputs)`, `# END ${name}: added harnesses`],
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
const CODEX_MARKER = '# Generated by `harnesspm sync` for added harnesses. Do not edit.';
|
|
43
|
+
function repoSlug(projectDir) {
|
|
44
|
+
return `${path.basename(projectDir)}-${createHash('sha256').update(projectDir).digest('hex').slice(0, 8)}`;
|
|
45
|
+
}
|
|
46
|
+
function isTracked(projectDir, rel) {
|
|
47
|
+
return spawnSync('git', ['ls-files', '--error-unmatch', rel], { cwd: projectDir, encoding: 'utf8' }).status === 0;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* The CLAUDE.md that makes Claude Code read the AGENTS.md in `dir` (spec 4.3, note 7): `CLAUDE.md` gets `@AGENTS.md`,
|
|
51
|
+
* unless the folder's `.claude/CLAUDE.md` already imports `@../AGENTS.md`.
|
|
52
|
+
*/
|
|
53
|
+
export function claudeImport(dir) {
|
|
54
|
+
const file = path.join(dir, 'CLAUDE.md');
|
|
55
|
+
const existing = readTextIfExists(file);
|
|
56
|
+
const dotClaude = path.join(dir, '.claude', 'CLAUDE.md');
|
|
57
|
+
const dotText = readTextIfExists(dotClaude);
|
|
58
|
+
if (!hasClaudeImport(existing) && dotText !== undefined && hasClaudeImport(dotText, '@../AGENTS.md'))
|
|
59
|
+
return { dir, file: dotClaude, text: dotText };
|
|
60
|
+
return { dir, file, text: withClaudeImport(existing) };
|
|
61
|
+
}
|
|
62
|
+
/** Folders below the project with an AGENTS.md that git tracks, outside node_modules. */
|
|
63
|
+
function nestedAgentsDirs(projectDir) {
|
|
64
|
+
const result = spawnSync('git', ['ls-files', '-z', '--', ':(glob)**/AGENTS.md'], { cwd: projectDir, encoding: 'utf8' });
|
|
65
|
+
if (result.status !== 0)
|
|
66
|
+
return [];
|
|
67
|
+
return result.stdout
|
|
68
|
+
.split('\0')
|
|
69
|
+
.filter((rel) => rel !== '' && rel !== 'AGENTS.md' && !rel.split('/').includes('node_modules'))
|
|
70
|
+
.map((rel) => path.join(projectDir, path.dirname(rel)))
|
|
71
|
+
.filter((dir) => isFile(path.join(dir, 'AGENTS.md')))
|
|
72
|
+
.sort();
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* The generated docs index (spec 2.7). A page with invalid frontmatter is listed without it, with a warning that names
|
|
76
|
+
* the page by `label`. `display` gives the path the index links to, such as the page's copy.
|
|
77
|
+
*/
|
|
78
|
+
function docsIndexText(dir, display, warnings, label = display) {
|
|
79
|
+
const lines = ['# Docs', ''];
|
|
80
|
+
for (const page of docsPages(dir)) {
|
|
81
|
+
const { data, body, error } = tryFrontmatter(readText(page), label(page));
|
|
82
|
+
if (error !== undefined) {
|
|
83
|
+
const warning = `${error}. The docs index lists the page by its heading or file name.`;
|
|
84
|
+
if (!warnings.includes(warning))
|
|
85
|
+
warnings.push(warning);
|
|
86
|
+
}
|
|
87
|
+
const first = headings(body.split('\n')).find((h) => h.level === 1);
|
|
88
|
+
const title = typeof data['title'] === 'string' ? data['title'] : (first?.text ?? path.basename(page).replace(/\.mdx?$/, ''));
|
|
89
|
+
const description = typeof data['description'] === 'string' ? `: ${data['description']}` : '';
|
|
90
|
+
lines.push(`- [${title}](${display(page)})${description}`);
|
|
91
|
+
}
|
|
92
|
+
return `${lines.join('\n')}\n`;
|
|
93
|
+
}
|
|
94
|
+
/** The pages of a docs folder (spec 2.7): `.md` and `.mdx` files, a linked one too, without the ones git ignores. */
|
|
95
|
+
function docsPages(dir) {
|
|
96
|
+
const pages = [];
|
|
97
|
+
const keeps = gitKeeps(dir);
|
|
98
|
+
const walk = (current) => {
|
|
99
|
+
for (const entry of fs.readdirSync(current, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
100
|
+
const full = path.join(current, entry.name);
|
|
101
|
+
if (entry.isDirectory())
|
|
102
|
+
walk(full);
|
|
103
|
+
else if (/\.mdx?$/.test(entry.name) && keeps(relPosix(dir, full)))
|
|
104
|
+
pages.push(full);
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
walk(dir);
|
|
108
|
+
return pages;
|
|
109
|
+
}
|
|
110
|
+
const isRepoAdded = (pkg) => pkg.layer === 'added' && (pkg.scope === 'local' || pkg.entry === true);
|
|
111
|
+
export const isUserLevel = (pkg) => pkg.layer === 'added' && pkg.scope === 'user' && !pkg.entry;
|
|
112
|
+
/**
|
|
113
|
+
* Paths that outputs show: stable package paths for dependencies, project-relative paths inside the
|
|
114
|
+
* project, absolute paths elsewhere. Generated docs indexes are added to `generated`. `absolute` shows every path
|
|
115
|
+
* in full, for user-level files: an agent reads them from any folder (spec 4.3, note 4).
|
|
116
|
+
*/
|
|
117
|
+
export function pathTools(res, generatedRoot, generated, warnings, options = {}) {
|
|
118
|
+
const projectDir = res.projectDir;
|
|
119
|
+
const show = (abs) => (!options.absolute && abs.startsWith(projectDir + path.sep) ? relPosix(projectDir, abs) : abs);
|
|
120
|
+
/** A dependency's file at its stable path under `node_modules/.harnesspm/pkgs/` (spec 4.3), or undefined for any other file. */
|
|
121
|
+
const stablePath = (file) => {
|
|
122
|
+
let best;
|
|
123
|
+
for (const pkg of res.packages) {
|
|
124
|
+
if (pkg.layer !== 'dependencies')
|
|
125
|
+
continue;
|
|
126
|
+
if ((file === pkg.dir || file.startsWith(pkg.dir + path.sep)) && (!best || pkg.dir.length > best.dir.length))
|
|
127
|
+
best = pkg;
|
|
128
|
+
}
|
|
129
|
+
return best ? path.join(projectDir, STATE_DIR, 'pkgs', best.name, path.relative(best.dir, file)) : undefined;
|
|
130
|
+
};
|
|
131
|
+
const display = (file) => {
|
|
132
|
+
const stable = stablePath(file);
|
|
133
|
+
return stable !== undefined ? relPosix(projectDir, stable) : show(file);
|
|
134
|
+
};
|
|
135
|
+
const generatedRule = (rule) => {
|
|
136
|
+
const dir = path.join(generatedRoot(rule.pkg), 'rules', rule.pkg.plugin);
|
|
137
|
+
return path.join(rule.variant ? path.join(dir, '.workspaces', hash(JSON.stringify([...rule.members].sort()))) : dir, `${rule.name}.md`);
|
|
138
|
+
};
|
|
139
|
+
/**
|
|
140
|
+
* Where a dependency's docs are copied to, so that search tools find them (spec 4.3, note 8). Every dependency's,
|
|
141
|
+
* a workspace package's too: the committed pointer then never depends on how a package manager installed it.
|
|
142
|
+
*/
|
|
143
|
+
const docsCopy = (pkg) => pkg.layer === 'dependencies' && res.docs.some((d) => d.pkg === pkg) ? path.join(projectDir, DOCS_DIR, pkg.plugin) : undefined;
|
|
144
|
+
const paths = {
|
|
145
|
+
rule: (rule) => (rule.patches.length > 0 ? show(generatedRule(rule)) : display(rule.source)),
|
|
146
|
+
docsIndex: (pkg) => {
|
|
147
|
+
const docs = res.docs.find((d) => d.pkg === pkg);
|
|
148
|
+
if (!docs)
|
|
149
|
+
return undefined;
|
|
150
|
+
const llms = path.join(docs.dir, 'llms.txt');
|
|
151
|
+
const copy = docsCopy(pkg);
|
|
152
|
+
if (copy !== undefined) {
|
|
153
|
+
// A package's own llms.txt is copied with its pages. A generated one lists the copies.
|
|
154
|
+
const index = path.join(copy, 'llms.txt');
|
|
155
|
+
// A warning names the package's page, which its owner fixes, not the copy.
|
|
156
|
+
if (!isFile(llms))
|
|
157
|
+
generated.set(index, docsIndexText(docs.dir, (file) => show(path.join(copy, path.relative(docs.dir, file))), warnings, display));
|
|
158
|
+
return show(index);
|
|
159
|
+
}
|
|
160
|
+
if (isFile(llms))
|
|
161
|
+
return display(llms);
|
|
162
|
+
const file = path.join(generatedRoot(pkg), 'docs', pkg.plugin, 'llms.txt');
|
|
163
|
+
generated.set(file, docsIndexText(docs.dir, display, warnings));
|
|
164
|
+
return show(file);
|
|
165
|
+
},
|
|
166
|
+
};
|
|
167
|
+
return { show, display, stablePath, generatedRule, docsCopy, paths };
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* The files of a docs copy, absolute path → text: the pages the index lists, and the package's own `llms.txt` (spec 4.3, note 8).
|
|
171
|
+
* A link that leaves the docs folder, such as `../README.md`, would lead nowhere in the copy, so it points at the
|
|
172
|
+
* file in the installed package instead. The page keeps that link for the package's own readers, such as its website.
|
|
173
|
+
*/
|
|
174
|
+
function docsCopyFiles(docsDir, copy, stablePath) {
|
|
175
|
+
const files = new Map();
|
|
176
|
+
const add = (source, rel) => {
|
|
177
|
+
const copied = path.join(copy, rel);
|
|
178
|
+
const text = readText(source);
|
|
179
|
+
let out = '';
|
|
180
|
+
let last = 0;
|
|
181
|
+
for (const { link, index } of relativeLinks(text)) {
|
|
182
|
+
let target;
|
|
183
|
+
try {
|
|
184
|
+
target = path.resolve(path.dirname(path.join(docsDir, rel)), decodeURI(link));
|
|
185
|
+
}
|
|
186
|
+
catch {
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
const stable = isInside(docsDir, target) || !fs.existsSync(target) ? undefined : stablePath(target);
|
|
190
|
+
if (stable === undefined)
|
|
191
|
+
continue;
|
|
192
|
+
out += text.slice(last, index) + encodeURI(relPosix(path.dirname(copied), stable));
|
|
193
|
+
last = index + link.length;
|
|
194
|
+
}
|
|
195
|
+
files.set(copied, out + text.slice(last));
|
|
196
|
+
};
|
|
197
|
+
for (const page of docsPages(docsDir))
|
|
198
|
+
add(page, path.relative(docsDir, page));
|
|
199
|
+
const llms = path.join(docsDir, 'llms.txt');
|
|
200
|
+
if (isFile(llms))
|
|
201
|
+
add(llms, 'llms.txt');
|
|
202
|
+
return files;
|
|
203
|
+
}
|
|
204
|
+
/** The changes that added harnesses make to the repository's rules (spec 4.3, note 4). */
|
|
205
|
+
function changesSection(team, full, rulePath) {
|
|
206
|
+
const added = new Set(full.packages.filter((p) => p.layer === 'added').map((p) => p.name));
|
|
207
|
+
const lines = [];
|
|
208
|
+
const texts = [];
|
|
209
|
+
for (const { id, changed, members } of localRuleChanges(team, full)) {
|
|
210
|
+
const where = team.workspaces.length > 0 && members.size !== team.workspaces.length + 1 ? ` in ${describeMembers(members)}` : '';
|
|
211
|
+
if (!changed) {
|
|
212
|
+
const by = full.excludedUnits.find((u) => u.id === id)?.by;
|
|
213
|
+
if (by !== undefined && added.has(by))
|
|
214
|
+
lines.push(`- Ignore the rule ${id} in AGENTS.md${where}: ${by} turns it off on this machine.`);
|
|
215
|
+
continue;
|
|
216
|
+
}
|
|
217
|
+
const by = [changed.replacedBy?.by, ...changed.patches.map((p) => p.by)].filter((b) => b !== undefined && added.has(b));
|
|
218
|
+
const who = [...new Set(by)].join(', ');
|
|
219
|
+
if (changed.activation === 'always')
|
|
220
|
+
texts.push(alwaysOnText(changed, `${id}, changed by ${who} on this machine; follow this text${where}`));
|
|
221
|
+
else
|
|
222
|
+
lines.push(`- Instead of the rule ${id} in AGENTS.md${where}, read ${rulePath(changed)} (changed by ${who})`);
|
|
223
|
+
}
|
|
224
|
+
if (lines.length === 0 && texts.length === 0)
|
|
225
|
+
return undefined;
|
|
226
|
+
return ["## Changes to this repository's rules", ...texts, ...(lines.length > 0 ? [lines.join('\n')] : [])].join('\n\n');
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* A skill from an untrusted package without the SKILL.md keys that widen what the agent may do (spec 6.1): a generated
|
|
230
|
+
* SKILL.md, with the rest of the skill's folder linked in. `author` is the package whose files the skill uses. Returns
|
|
231
|
+
* the generated folder, `undefined` when the skill has none of those keys, or `null` when its frontmatter can't be read,
|
|
232
|
+
* so the skill is left out.
|
|
233
|
+
*/
|
|
234
|
+
function narrowedSkill(skill, author, dir, stable, generated, links, warnings) {
|
|
235
|
+
const file = path.join(skill.dir, 'SKILL.md');
|
|
236
|
+
const parsed = tryFrontmatter(readTextIfExists(file) ?? '', file);
|
|
237
|
+
if (parsed.error !== undefined) {
|
|
238
|
+
warnings.push(`${skill.id}: left out, because its frontmatter can't be read (${parsed.error}) and ${author.name} is not trusted`);
|
|
239
|
+
return null;
|
|
240
|
+
}
|
|
241
|
+
const widening = WIDENING_SKILL_KEYS.filter((key) => key in parsed.data);
|
|
242
|
+
if (widening.length === 0)
|
|
243
|
+
return undefined;
|
|
244
|
+
for (const key of widening)
|
|
245
|
+
warnings.push(`${skill.id}: "${key}" is left out, because ${author.name} is not trusted`);
|
|
246
|
+
const data = Object.fromEntries(Object.entries(parsed.data).filter(([key]) => !widening.includes(key)));
|
|
247
|
+
const keys = widening.map((key) => `"${key}"`).join(' and ');
|
|
248
|
+
const note = `<!-- Generated by harnesspm from ${skill.id} without ${keys}, because ${author.name} is not trusted. -->`;
|
|
249
|
+
generated.set(path.join(dir, 'SKILL.md'), withFrontmatter(data, `${note}\n\n${parsed.body.replace(/^\n+/, '')}`));
|
|
250
|
+
for (const entry of listDir(skill.dir))
|
|
251
|
+
if (entry !== 'SKILL.md')
|
|
252
|
+
links.set(path.join(dir, entry), stable(path.join(skill.dir, entry)));
|
|
253
|
+
return dir;
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* `team` is the dependency and project layers alone, for committed outputs. `full` adds the added
|
|
257
|
+
* harnesses, for per-machine outputs. Without `team`, only the outputs of added harnesses change.
|
|
258
|
+
*/
|
|
259
|
+
export function computePlan(team, full, options = {}) {
|
|
260
|
+
const projectDir = full.projectDir;
|
|
261
|
+
const warnings = [];
|
|
262
|
+
const generated = new Map();
|
|
263
|
+
const links = new Map();
|
|
264
|
+
const teamExcludes = new Set([`/${STATE_DIR.split(path.sep).join('/')}/`]);
|
|
265
|
+
const addedExcludes = new Set();
|
|
266
|
+
const teamGen = path.join(projectDir, STATE_DIR);
|
|
267
|
+
const addedGen = path.join(harnesspmHome(), 'generated', repoSlug(projectDir));
|
|
268
|
+
const tools = pathTools(full, (pkg) => (pkg.layer === 'added' ? addedGen : teamGen), generated, warnings);
|
|
269
|
+
if (team)
|
|
270
|
+
for (const pkg of full.packages)
|
|
271
|
+
if (pkg.layer === 'dependencies')
|
|
272
|
+
links.set(path.join(projectDir, STATE_DIR, 'pkgs', pkg.name), pkg.dir);
|
|
273
|
+
const stable = (file) => path.resolve(projectDir, tools.display(file));
|
|
274
|
+
const seenRoots = new Set();
|
|
275
|
+
const roots = [path.join(projectDir, '.claude', 'skills'), path.join(projectDir, '.agents', 'skills')].filter((root) => {
|
|
276
|
+
const real = isDir(root) ? realpath(root) : root;
|
|
277
|
+
if (seenRoots.has(real))
|
|
278
|
+
return false;
|
|
279
|
+
seenRoots.add(real);
|
|
280
|
+
return true;
|
|
281
|
+
});
|
|
282
|
+
const addLink = (linkPath, target, into) => {
|
|
283
|
+
if (exists(linkPath) && !isSymlink(linkPath)) {
|
|
284
|
+
warnings.push(`${relPosix(projectDir, linkPath)} exists and is not a harnesspm link; left as it is`);
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
links.set(linkPath, target);
|
|
288
|
+
into.add(`/${relPosix(projectDir, linkPath)}`);
|
|
289
|
+
};
|
|
290
|
+
const teamPatched = new Set(team?.rules.filter((rule) => rule.patches.length > 0).map(tools.generatedRule));
|
|
291
|
+
// Generated rule files: patched rules that agents read from a file, with this machine's text.
|
|
292
|
+
for (const rule of full.rules) {
|
|
293
|
+
if (rule.activation === 'always' || isUserLevel(rule.pkg))
|
|
294
|
+
continue;
|
|
295
|
+
if (rule.pkg.layer !== 'added' && !team)
|
|
296
|
+
continue;
|
|
297
|
+
const file = tools.generatedRule(rule);
|
|
298
|
+
if (rule.patches.length > 0 || teamPatched.has(file))
|
|
299
|
+
generated.set(file, rule.text);
|
|
300
|
+
}
|
|
301
|
+
// File-scoped team rules also get a native Claude Code rule (spec 4.3, note 3).
|
|
302
|
+
if (team) {
|
|
303
|
+
for (const variants of rulesById(full.rules).values()) {
|
|
304
|
+
const rule = variants[0];
|
|
305
|
+
if (rule.activation !== 'file' || rule.pkg.layer === 'added')
|
|
306
|
+
continue;
|
|
307
|
+
// A repository-wide native rule cannot carry different text for different workspaces.
|
|
308
|
+
if (variants.some((other) => other.text !== rule.text))
|
|
309
|
+
continue;
|
|
310
|
+
const changed = rule.text !== readText(rule.original);
|
|
311
|
+
const members = new Set(variants.flatMap((other) => [...other.members]));
|
|
312
|
+
if (changed && full.workspaces.some((ws) => !members.has(ws.key)))
|
|
313
|
+
continue;
|
|
314
|
+
const target = changed ? tools.generatedRule(rule) : stable(rule.source);
|
|
315
|
+
if (changed)
|
|
316
|
+
generated.set(target, rule.text);
|
|
317
|
+
addLink(path.join(projectDir, '.claude', 'rules', 'harnesspm', rule.pkg.plugin, `${rule.name}.md`), target, teamExcludes);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
let committed;
|
|
321
|
+
const blockUnits = new Map();
|
|
322
|
+
const docsCopies = new Map();
|
|
323
|
+
let rgignore;
|
|
324
|
+
let lock = readLock(projectDir);
|
|
325
|
+
let telemetryHeld;
|
|
326
|
+
if (team) {
|
|
327
|
+
const previous = lock;
|
|
328
|
+
// A model run keeps the handler a person recorded, and may only remove it (spec 14.5).
|
|
329
|
+
const wanted = team.config.telemetry?.send;
|
|
330
|
+
const before = previous?.telemetry?.send;
|
|
331
|
+
let record = wanted;
|
|
332
|
+
if (wanted !== undefined && options.widen === false && !sameSend(wanted, before)) {
|
|
333
|
+
record = before;
|
|
334
|
+
telemetryHeld = `telemetry handler: ${describeSend(wanted)}`;
|
|
335
|
+
}
|
|
336
|
+
lock = buildLock(team, previous, record);
|
|
337
|
+
warnings.push(...patchDrift(previous, lock));
|
|
338
|
+
const teamGenerated = new Map();
|
|
339
|
+
const teamLock = lock;
|
|
340
|
+
const teamTools = pathTools(team, () => teamGen, teamGenerated, warnings);
|
|
341
|
+
// Copies of the dependencies' docs, with an .rgignore that lets search tools into them (spec 4.3, note 8).
|
|
342
|
+
for (const docs of team.docs) {
|
|
343
|
+
const copy = teamTools.docsCopy(docs.pkg);
|
|
344
|
+
if (copy === undefined)
|
|
345
|
+
continue;
|
|
346
|
+
for (const [file, text] of docsCopyFiles(docs.dir, copy, teamTools.stablePath))
|
|
347
|
+
teamGenerated.set(file, text);
|
|
348
|
+
docsCopies.set(docs.pkg, copy);
|
|
349
|
+
}
|
|
350
|
+
const rgFile = path.join(projectDir, '.rgignore');
|
|
351
|
+
const rgText = readTextIfExists(rgFile);
|
|
352
|
+
const rgOurs = () => (rgText ?? RGIGNORE_MARKER).startsWith(RGIGNORE_MARKER) && !isTracked(projectDir, '.rgignore');
|
|
353
|
+
if (docsCopies.size > 0) {
|
|
354
|
+
teamExcludes.add(DOCS_EXCLUDE);
|
|
355
|
+
// Formatters such as Prettier read .gitignore but not .git/info/exclude, so only a .gitignore keeps the copies out
|
|
356
|
+
// of them. Git names a .gitignore by its path in the repository, and a global excludes file by its absolute path.
|
|
357
|
+
const source = gitIgnoreSource(projectDir, DOCS_PROBE);
|
|
358
|
+
if (source !== undefined && (source === null || path.isAbsolute(source) || path.basename(source) !== '.gitignore')) {
|
|
359
|
+
warnings.push(`.gitignore does not ignore .harnesspm/, so formatters such as Prettier, which skip only what .gitignore lists, check the docs copies in .harnesspm/docs/. ${docsIgnoreAdvice(projectDir)}`);
|
|
360
|
+
}
|
|
361
|
+
if (rgOurs()) {
|
|
362
|
+
rgignore = RGIGNORE;
|
|
363
|
+
teamExcludes.add(RGIGNORE_EXCLUDE);
|
|
364
|
+
}
|
|
365
|
+
else if (!RGIGNORE_LINES.every((line) => rgText.split('\n').includes(line))) {
|
|
366
|
+
warnings.push(`.rgignore is not harnesspm's, so search tools skip the docs copies in .harnesspm/docs/. To let them in, add these lines to it, in this order: ${RGIGNORE_LINES.join(', ')}`);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
else if (rgText !== undefined && rgOurs())
|
|
370
|
+
rgignore = null;
|
|
371
|
+
for (const rule of team.rules) {
|
|
372
|
+
if (rule.activation !== 'always' && rule.patches.length > 0)
|
|
373
|
+
teamGenerated.set(teamTools.generatedRule(rule), rule.text);
|
|
374
|
+
}
|
|
375
|
+
// One command form inside the project and outside it, where `-C` is the only difference (spec 4.6, 10.1).
|
|
376
|
+
const prefix = (pkg) => (trustOf(pkg, team, teamLock).trusted ? NPX_ANY : undefined);
|
|
377
|
+
// The root block holds what the root reaches and what every workspace shares (spec 3.6, 4.5).
|
|
378
|
+
const keys = team.workspaces.map((ws) => ws.key);
|
|
379
|
+
const shared = (pkg) => pkg.members.has('') || (keys.length > 0 && keys.every((k) => pkg.members.has(k)));
|
|
380
|
+
const rootRules = [];
|
|
381
|
+
const workspaceRules = new Map(keys.map((key) => [key, []]));
|
|
382
|
+
for (const variants of rulesById(team.rules).values()) {
|
|
383
|
+
const first = variants[0];
|
|
384
|
+
if (shared(first.pkg) && variants.every((rule) => rule.text === first.text))
|
|
385
|
+
rootRules.push(first);
|
|
386
|
+
else
|
|
387
|
+
for (const rule of variants)
|
|
388
|
+
for (const key of rule.members)
|
|
389
|
+
workspaceRules.get(key)?.push(rule);
|
|
390
|
+
}
|
|
391
|
+
const workspaces = [];
|
|
392
|
+
const withBlocks = [];
|
|
393
|
+
for (const ws of team.workspaces) {
|
|
394
|
+
// Paths in a workspace's block are relative to its folder.
|
|
395
|
+
const toWs = (p) => (path.isAbsolute(p) ? p : relPosix(ws.dir, path.join(projectDir, p)));
|
|
396
|
+
const wsPaths = {
|
|
397
|
+
rule: (rule) => toWs(teamTools.paths.rule(rule)),
|
|
398
|
+
docsIndex: (pkg) => {
|
|
399
|
+
const index = teamTools.paths.docsIndex(pkg);
|
|
400
|
+
return index === undefined ? undefined : toWs(index);
|
|
401
|
+
},
|
|
402
|
+
};
|
|
403
|
+
const rules = workspaceRules.get(ws.key);
|
|
404
|
+
const includeOtherUnits = (pkg) => !shared(pkg) && pkg.members.has(ws.key);
|
|
405
|
+
const units = renderSections(sectionsFor(team, team.packages, wsPaths, prefix, { compact: true, rules, includeOtherUnits }), wsPaths, { compact: true });
|
|
406
|
+
const nested = keys.some((key) => key.startsWith(`${ws.key}/`));
|
|
407
|
+
const content = units !== '' && nested
|
|
408
|
+
? `This block applies to this workspace. For files in a nested workspace, follow the harness rules for that workspace.\n\n${units}`
|
|
409
|
+
: units;
|
|
410
|
+
const agentsFile = path.join(ws.dir, 'AGENTS.md');
|
|
411
|
+
const existing = readTextIfExists(agentsFile);
|
|
412
|
+
const agentsMd = content !== '' ? upsertBlock(existing, wrapBlock(content, true)) : extractBlock(existing) !== undefined ? removeBlock(existing) : existing;
|
|
413
|
+
workspaces.push({ dir: ws.dir, agentsMd });
|
|
414
|
+
if (content === '')
|
|
415
|
+
continue;
|
|
416
|
+
withBlocks.push(ws.key);
|
|
417
|
+
// Telemetry maps a load of this file to the always-on rules its block holds (spec 14.4).
|
|
418
|
+
const always = rules.filter((r) => r.activation === 'always').map((r) => r.id);
|
|
419
|
+
if (always.length > 0)
|
|
420
|
+
blockUnits.set(path.join(realOrSame(ws.dir), 'AGENTS.md'), always);
|
|
421
|
+
}
|
|
422
|
+
const rootContent = [workspacesSection(withBlocks), renderSections(sectionsFor(team, team.packages, teamTools.paths, prefix, { compact: true, rules: rootRules, includeOtherUnits: shared }), teamTools.paths, { compact: true })]
|
|
423
|
+
.filter((part) => part !== undefined && part !== '')
|
|
424
|
+
.join('\n\n');
|
|
425
|
+
const block = rootContent !== '' ? wrapBlock(rootContent, true) : wrapBlock('No harness units yet.');
|
|
426
|
+
for (const [file, content] of teamGenerated)
|
|
427
|
+
if (!generated.has(file))
|
|
428
|
+
generated.set(file, content);
|
|
429
|
+
// The root CLAUDE.md silences every nested AGENTS.md in Claude Code, so each one gets its own import (spec 4.3, note 7).
|
|
430
|
+
const claudeDirs = new Set([projectDir, ...workspaces.filter((ws) => ws.agentsMd !== undefined).map((ws) => ws.dir), ...nestedAgentsDirs(projectDir)]);
|
|
431
|
+
committed = {
|
|
432
|
+
agentsMd: upsertBlock(readTextIfExists(path.join(projectDir, 'AGENTS.md')), block),
|
|
433
|
+
lock: serializeLock(lock),
|
|
434
|
+
workspaces,
|
|
435
|
+
claudeMds: [...claudeDirs].map(claudeImport),
|
|
436
|
+
};
|
|
437
|
+
}
|
|
438
|
+
// Added harnesses with local scope, and every harness's entry for this repository (spec 4.3).
|
|
439
|
+
let content = renderSections(sectionsFor(full, full.packages.filter(isRepoAdded), tools.paths, () => NPX_ANY), tools.paths);
|
|
440
|
+
const changes = team ? changesSection(team, full, (rule) => tools.paths.rule(rule)) : undefined;
|
|
441
|
+
if (changes !== undefined)
|
|
442
|
+
content = content !== '' ? `${content}\n\n${changes}` : changes;
|
|
443
|
+
const localFile = path.join(projectDir, 'CLAUDE.local.md');
|
|
444
|
+
let localMd;
|
|
445
|
+
if (content !== '' && isTracked(projectDir, 'CLAUDE.local.md')) {
|
|
446
|
+
warnings.push('CLAUDE.local.md is tracked by git, so harnesspm does not write added harnesses into it');
|
|
447
|
+
localMd = readTextIfExists(localFile);
|
|
448
|
+
}
|
|
449
|
+
else if (content !== '') {
|
|
450
|
+
// CLAUDE.local.md counts as a CLAUDE.md: without one, Claude Code would stop reading AGENTS.md (spec 4.3, note 1).
|
|
451
|
+
const needsImport = !isFile(path.join(projectDir, 'CLAUDE.md')) && isFile(path.join(projectDir, 'AGENTS.md'));
|
|
452
|
+
localMd = upsertBlock(readTextIfExists(localFile), wrapBlock(content));
|
|
453
|
+
if (needsImport && !hasClaudeImport(localMd))
|
|
454
|
+
localMd = `@AGENTS.md\n\n${localMd}`;
|
|
455
|
+
addedExcludes.add('/CLAUDE.local.md');
|
|
456
|
+
}
|
|
457
|
+
else {
|
|
458
|
+
// Remove only harnesspm's own block. A file without one stays as it is.
|
|
459
|
+
const existing = readTextIfExists(localFile);
|
|
460
|
+
localMd = extractBlock(existing) === undefined ? existing : removeBlock(existing, /^\s*(@AGENTS\.md)?\s*$/);
|
|
461
|
+
}
|
|
462
|
+
// Codex files are per machine unless the repository commits its own .codex/ (spec 4.3, note 2).
|
|
463
|
+
const codexFile = path.join(projectDir, '.codex', 'config.toml');
|
|
464
|
+
const codexTracked = ['.codex/config.toml', '.codex/hooks.json', '.codex/rules'].some((rel) => isTracked(projectDir, rel));
|
|
465
|
+
const codexOurs = !codexTracked && (readTextIfExists(codexFile) ?? CODEX_MARKER).startsWith(CODEX_MARKER);
|
|
466
|
+
if (!codexOurs)
|
|
467
|
+
warnings.push('.codex/ belongs to the repository, so harnesspm writes nothing there and Codex misses some units. See `harnesspm status`.');
|
|
468
|
+
const claudeOurs = !isTracked(projectDir, '.claude/settings.local.json');
|
|
469
|
+
if (!claudeOurs)
|
|
470
|
+
warnings.push('.claude/settings.local.json is tracked by git, so harnesspm writes no hooks or permissions there');
|
|
471
|
+
// Executable units and sub-agents (spec 4.3, chapter 5), with trust (spec 6.2).
|
|
472
|
+
const trust = (pkg) => trustOf(pkg, full, lock);
|
|
473
|
+
// Skills are linked as they are, except an untrusted package's skill that widens what the agent may do (spec 6.1).
|
|
474
|
+
// A replaced skill's files come from the package that replaced it, so its trust decides.
|
|
475
|
+
const skillsGen = path.join(teamGen, 'skills');
|
|
476
|
+
for (const skill of full.skills) {
|
|
477
|
+
if (isUserLevel(skill.pkg))
|
|
478
|
+
continue;
|
|
479
|
+
const added = skill.pkg.layer === 'added';
|
|
480
|
+
if (!added && !team)
|
|
481
|
+
continue;
|
|
482
|
+
let target = added ? skill.dir : stable(skill.dir);
|
|
483
|
+
const author = skillAuthor(skill);
|
|
484
|
+
if (author !== undefined && !trust(author).trusted) {
|
|
485
|
+
const copy = narrowedSkill(skill, author, path.join(skillsGen, skill.pkg.plugin, skill.name), stable, generated, links, warnings);
|
|
486
|
+
if (copy === null)
|
|
487
|
+
continue;
|
|
488
|
+
if (copy !== undefined)
|
|
489
|
+
target = copy;
|
|
490
|
+
}
|
|
491
|
+
for (const root of roots)
|
|
492
|
+
addLink(path.join(root, skill.name), target, added ? addedExcludes : teamExcludes);
|
|
493
|
+
}
|
|
494
|
+
const agentDirs = { claudeAgents: path.join(projectDir, '.claude', 'agents'), codexAgents: path.join(projectDir, '.codex', 'agents') };
|
|
495
|
+
// Hooks and MCP servers start the project's installed CLI file with node when it has one (spec 5.2).
|
|
496
|
+
const teamRunner = runner(projectDir, NPX_ANY);
|
|
497
|
+
const addedRunner = runner(projectDir, NPX_ANY);
|
|
498
|
+
// Allow rules match the tool lines, `npx -y @harnesspm/cli run <unit>`, and until 1.0 the bare `npx harnesspm run <unit>` that some packages' text still types (spec 5.4).
|
|
499
|
+
const teamExec = team ? desiredEntries(full, new Set(full.packages.filter((p) => p.layer !== 'added')), trust, { ...agentDirs, npx: () => [NPX_ANY, NPX_BARE], runner: () => teamRunner }) : undefined;
|
|
500
|
+
const addedExec = desiredEntries(full, new Set(full.packages.filter(isRepoAdded)), trust, { ...agentDirs, npx: () => [NPX_ANY], runner: () => addedRunner });
|
|
501
|
+
warnings.push(...(teamExec?.warnings ?? []), ...addedExec.warnings);
|
|
502
|
+
// Telemetry's agent events (spec 14.4): harnesspm's own hooks, when the recorded handler and this machine allow them.
|
|
503
|
+
let telemetryIndex;
|
|
504
|
+
if (team && teamExec) {
|
|
505
|
+
const state = telemetryState(projectDir, team.config.telemetry, lock?.telemetry?.send);
|
|
506
|
+
const events = AGENT_EVENTS.filter((e) => state.events.has(e));
|
|
507
|
+
if (events.length > 0) {
|
|
508
|
+
teamExec.claude.hooks.push(...telemetryHooks(teamRunner.shell, 'claude', events));
|
|
509
|
+
teamExec.codex.hooks.push(...telemetryHooks(teamRunner.shell, 'codex', events));
|
|
510
|
+
const index = telemetryIndexFor(team, tools.generatedRule, (pkg) => path.join(teamGen, 'docs', pkg.plugin, 'llms.txt'), docsCopies, blockUnits);
|
|
511
|
+
telemetryIndex = `${JSON.stringify(index, null, 2)}\n`;
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
return {
|
|
515
|
+
...(committed ? { committed } : {}),
|
|
516
|
+
generated,
|
|
517
|
+
// teamGen/docs holds generated indexes, and the copies a version before 0.14 wrote there, which a sync removes.
|
|
518
|
+
generatedRoots: [...(team ? [path.join(teamGen, 'rules'), path.join(teamGen, 'docs'), path.join(projectDir, DOCS_DIR), skillsGen] : []), addedGen],
|
|
519
|
+
links,
|
|
520
|
+
...(rgignore !== undefined ? { rgignore } : {}),
|
|
521
|
+
...(team ? { teamExcludes: [...teamExcludes].sort() } : {}),
|
|
522
|
+
addedExcludes: [...addedExcludes].sort(),
|
|
523
|
+
localMd,
|
|
524
|
+
codexInstructions: content,
|
|
525
|
+
codexOurs,
|
|
526
|
+
claudeOurs,
|
|
527
|
+
exec: { ...(teamExec ? { team: teamExec } : {}), added: addedExec },
|
|
528
|
+
...(telemetryIndex !== undefined ? { telemetryIndex } : {}),
|
|
529
|
+
...(telemetryHeld !== undefined ? { telemetryHeld } : {}),
|
|
530
|
+
warnings,
|
|
531
|
+
};
|
|
532
|
+
}
|
|
533
|
+
/**
|
|
534
|
+
* Claude Code: reads, skills, file-scoped rules and workspace blocks it loads by itself, sessions. Codex: sessions only
|
|
535
|
+
* (spec 14.4). `prefix` is the runner, the installed CLI file when there is one, because npx costs about 0.4 s per call.
|
|
536
|
+
*/
|
|
537
|
+
function telemetryHooks(prefix, agent, events) {
|
|
538
|
+
const command = `${prefix} track --agent ${agent}`;
|
|
539
|
+
const hook = (event, matcher) => ({ event, ...(matcher !== undefined ? { matcher } : {}), command, timeout: 10, async: true });
|
|
540
|
+
const hooks = [];
|
|
541
|
+
if (agent === 'claude') {
|
|
542
|
+
const tools = [...(events.includes('read') ? ['Read'] : []), ...(events.includes('skill') ? ['Skill'] : [])];
|
|
543
|
+
if (tools.length > 0)
|
|
544
|
+
hooks.push(hook('PostToolUse', tools.join('|')));
|
|
545
|
+
// `nested_traversal` and `include`: a workspace's CLAUDE.md, and the AGENTS.md it imports (spec 4.5).
|
|
546
|
+
if (events.includes('read'))
|
|
547
|
+
hooks.push(hook('InstructionsLoaded', 'path_glob_match|nested_traversal|include'));
|
|
548
|
+
}
|
|
549
|
+
if (events.includes('session'))
|
|
550
|
+
hooks.push(hook('SessionStart'));
|
|
551
|
+
return hooks;
|
|
552
|
+
}
|
|
553
|
+
const realOrSame = (p) => {
|
|
554
|
+
try {
|
|
555
|
+
return realpath(p);
|
|
556
|
+
}
|
|
557
|
+
catch {
|
|
558
|
+
return p;
|
|
559
|
+
}
|
|
560
|
+
};
|
|
561
|
+
/**
|
|
562
|
+
* Maps the files and folders agents read to the units of the dependency and project layers (spec 14.4). `blocks` maps
|
|
563
|
+
* each workspace's AGENTS.md to the always-on rules in its managed block.
|
|
564
|
+
*/
|
|
565
|
+
function telemetryIndexFor(res, generatedRule, generatedDocsIndex, docsCopies, blocks) {
|
|
566
|
+
const team = (pkg) => pkg.layer !== 'added';
|
|
567
|
+
const repository = remoteKey(res.projectDir);
|
|
568
|
+
const index = {
|
|
569
|
+
project: res.projectName,
|
|
570
|
+
// Empty when there is no remote, so no event asks git again.
|
|
571
|
+
repository: repository ?? '',
|
|
572
|
+
workspaces: res.workspaces.map((ws) => ws.key),
|
|
573
|
+
packages: {},
|
|
574
|
+
files: {},
|
|
575
|
+
dirs: {},
|
|
576
|
+
skills: {},
|
|
577
|
+
blocks: Object.fromEntries(blocks),
|
|
578
|
+
};
|
|
579
|
+
for (const pkg of res.packages.filter(team))
|
|
580
|
+
index.packages[pkg.plugin] = { package: pkg.name, version: pkg.version };
|
|
581
|
+
for (const rule of res.rules.filter((r) => team(r.pkg))) {
|
|
582
|
+
for (const file of [rule.original, rule.source, generatedRule(rule)])
|
|
583
|
+
index.files[realOrSame(file)] = rule.id;
|
|
584
|
+
}
|
|
585
|
+
for (const docs of res.docs.filter((d) => team(d.pkg))) {
|
|
586
|
+
index.dirs[realOrSame(docs.dir)] = docs.id;
|
|
587
|
+
index.files[realOrSame(generatedDocsIndex(docs.pkg))] = docs.id;
|
|
588
|
+
// The copy may not exist yet, so its real path comes from the project's.
|
|
589
|
+
const copy = docsCopies.get(docs.pkg);
|
|
590
|
+
if (copy !== undefined)
|
|
591
|
+
index.dirs[path.join(realOrSame(res.projectDir), path.relative(res.projectDir, copy))] = docs.id;
|
|
592
|
+
}
|
|
593
|
+
for (const skill of res.skills.filter((s) => team(s.pkg))) {
|
|
594
|
+
index.dirs[realOrSame(skill.dir)] = skill.id;
|
|
595
|
+
index.skills[skill.name] = skill.id;
|
|
596
|
+
}
|
|
597
|
+
return index;
|
|
598
|
+
}
|
|
599
|
+
function sectionRange(lines, marks) {
|
|
600
|
+
const start = lines.indexOf(marks[0]);
|
|
601
|
+
if (start < 0)
|
|
602
|
+
return undefined;
|
|
603
|
+
const end = lines.indexOf(marks[1], start);
|
|
604
|
+
return end < 0 ? undefined : [start, end];
|
|
605
|
+
}
|
|
606
|
+
/** A section's entries, as paths from the project folder such as `/CLAUDE.local.md`. Entries start at the git root, so `prefix` is cut off. */
|
|
607
|
+
function readSection(text, marks, prefix) {
|
|
608
|
+
const lines = (text ?? '').split('\n');
|
|
609
|
+
const range = sectionRange(lines, marks);
|
|
610
|
+
const anchor = excludeEntry(prefix, '');
|
|
611
|
+
return range ? lines.slice(range[0] + 1, range[1]).filter((l) => l.startsWith(anchor)).map((l) => `/${l.slice(anchor.length)}`) : [];
|
|
612
|
+
}
|
|
613
|
+
/**
|
|
614
|
+
* The sections of a project's entries. harnesspm 0.9 and earlier wrote a project below the git root into the root's
|
|
615
|
+
* team section, from the project's folder, so its patterns missed its files. That section is `legacy` when the root does
|
|
616
|
+
* not use harnesspm: no other project writes it then. Read from the project's folder, it lists the project's last entries.
|
|
617
|
+
*/
|
|
618
|
+
function projectSections(prefix, root) {
|
|
619
|
+
const marks = sectionMarks(prefix);
|
|
620
|
+
return prefix !== '' && !isFile(path.join(root, CONFIG_FILE)) ? { marks, legacy: sectionMarks('').team } : { marks };
|
|
621
|
+
}
|
|
622
|
+
/** The per-machine paths that harnesspm's last sync listed in .git/info/exclude, from the project folder, such as `/CLAUDE.local.md`. */
|
|
623
|
+
export function excludedBySync(projectDir) {
|
|
624
|
+
const exclude = gitExclude(projectDir);
|
|
625
|
+
if (!exclude)
|
|
626
|
+
return [];
|
|
627
|
+
const text = readTextIfExists(exclude.file);
|
|
628
|
+
const { marks, legacy } = projectSections(exclude.prefix, exclude.root);
|
|
629
|
+
return [...readSection(text, marks.team, exclude.prefix), ...readSection(text, marks.added, exclude.prefix), ...(legacy ? readSection(text, legacy, '') : [])];
|
|
630
|
+
}
|
|
631
|
+
/** Replaces a section with `entries`, paths from the project folder, anchored at the git root by `prefix`. No entries remove it. */
|
|
632
|
+
function writeSection(text, marks, entries, prefix) {
|
|
633
|
+
const lines = (text ?? '').split('\n');
|
|
634
|
+
const range = sectionRange(lines, marks);
|
|
635
|
+
const section = entries.length > 0 ? [marks[0], ...entries.map((entry) => excludeEntry(prefix, entry)), marks[1]] : [];
|
|
636
|
+
if (range)
|
|
637
|
+
lines.splice(range[0], range[1] - range[0] + 1, ...section);
|
|
638
|
+
else if (section.length > 0) {
|
|
639
|
+
while (lines.length > 0 && lines[lines.length - 1] === '')
|
|
640
|
+
lines.pop();
|
|
641
|
+
if (lines.length > 0)
|
|
642
|
+
lines.push('');
|
|
643
|
+
lines.push(...section);
|
|
644
|
+
}
|
|
645
|
+
while (lines.length > 0 && lines[lines.length - 1] === '')
|
|
646
|
+
lines.pop();
|
|
647
|
+
return lines.length > 0 ? `${lines.join('\n')}\n` : '';
|
|
648
|
+
}
|
|
649
|
+
function unlinkAndPrune(target, stopAt) {
|
|
650
|
+
fs.unlinkSync(target);
|
|
651
|
+
for (let dir = path.dirname(target); dir.startsWith(stopAt + path.sep); dir = path.dirname(dir)) {
|
|
652
|
+
try {
|
|
653
|
+
fs.rmdirSync(dir);
|
|
654
|
+
}
|
|
655
|
+
catch {
|
|
656
|
+
break;
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
/**
|
|
661
|
+
* The per-machine record of the entries harnesspm wrote for this project (spec 4.7): in the clone's git folder, or,
|
|
662
|
+
* in a folder that is not a git repository, in ~/.harnesspm/state/, so sync never creates a `.git` folder there.
|
|
663
|
+
* A project below the git root has its own, such as `harnesspm/docs-site/state.json`, so that two projects in one
|
|
664
|
+
* repository never take each other's entries for their own.
|
|
665
|
+
*/
|
|
666
|
+
export function repoStateFile(projectDir) {
|
|
667
|
+
const result = spawnSync('git', ['rev-parse', '--show-prefix', '--git-path', 'harnesspm'], { cwd: projectDir, encoding: 'utf8' });
|
|
668
|
+
if (result.status !== 0)
|
|
669
|
+
return path.join(harnesspmHome(), 'state', `${repoSlug(projectDir)}.json`);
|
|
670
|
+
const [prefix = '', p = ''] = result.stdout.split('\n');
|
|
671
|
+
return path.join(path.isAbsolute(p) ? p : path.join(projectDir, p), ...prefix.split('/').filter(Boolean), 'state.json');
|
|
672
|
+
}
|
|
673
|
+
export function repoTargets(projectDir, plan) {
|
|
674
|
+
return {
|
|
675
|
+
claudeSettings: path.join(projectDir, '.claude', 'settings.local.json'),
|
|
676
|
+
claudeJson: claudeJsonFile(),
|
|
677
|
+
claudeProject: projectDir,
|
|
678
|
+
codexHooks: path.join(projectDir, '.codex', 'hooks.json'),
|
|
679
|
+
codexRules: path.join(projectDir, '.codex', 'rules', 'harnesspm.rules'),
|
|
680
|
+
stateFile: repoStateFile(projectDir),
|
|
681
|
+
writeClaude: plan.claudeOurs,
|
|
682
|
+
writeCodex: plan.codexOurs,
|
|
683
|
+
};
|
|
684
|
+
}
|
|
685
|
+
/** Writes or removes the `.rgignore` that lets search tools into the docs copies (spec 4.3). */
|
|
686
|
+
export function writeRgignore(projectDir, plan) {
|
|
687
|
+
const file = path.join(projectDir, '.rgignore');
|
|
688
|
+
if (plan.rgignore === null)
|
|
689
|
+
fs.rmSync(file, { force: true });
|
|
690
|
+
else if (plan.rgignore !== undefined)
|
|
691
|
+
writeIfChanged(file, plan.rgignore);
|
|
692
|
+
}
|
|
693
|
+
/** Where the `/.harnesspm/` line goes: the .gitignore of the project folder, named when it is below the git root. */
|
|
694
|
+
export function docsIgnoreAdvice(projectDir) {
|
|
695
|
+
const prefix = gitExclude(projectDir)?.prefix ?? '';
|
|
696
|
+
return `Add this line to ${prefix === '' ? '.gitignore' : `the .gitignore in ${prefix}`}: ${DOCS_EXCLUDE}`;
|
|
697
|
+
}
|
|
698
|
+
/** Adds `entries` to the project's section of .git/info/exclude and keeps the entries a sync wrote there. */
|
|
699
|
+
export function addExcludes(projectDir, entries) {
|
|
700
|
+
const exclude = gitExclude(projectDir);
|
|
701
|
+
if (!exclude || entries.length === 0)
|
|
702
|
+
return;
|
|
703
|
+
const { marks } = projectSections(exclude.prefix, exclude.root);
|
|
704
|
+
const before = readTextIfExists(exclude.file);
|
|
705
|
+
const current = readSection(before, marks.team, exclude.prefix);
|
|
706
|
+
if (entries.every((entry) => current.includes(entry)))
|
|
707
|
+
return;
|
|
708
|
+
writeIfChanged(exclude.file, writeSection(before, marks.team, [...new Set([...current, ...entries])].sort(), exclude.prefix));
|
|
709
|
+
}
|
|
710
|
+
/**
|
|
711
|
+
* Writes the plan. Returns the project-relative paths that changed and the entries held back.
|
|
712
|
+
* `committed: false` writes only the per-machine outputs, as a sync with `CI=true` does (spec 6.4).
|
|
713
|
+
* `reviewed: true` lets a model run write the repository's entries, because they are as a person reviewed them (spec
|
|
714
|
+
* 6.2, rule 4). Entries of added harnesses still wait for a person.
|
|
715
|
+
*/
|
|
716
|
+
export function applyPlan(projectDir, plan, options = {}) {
|
|
717
|
+
const changed = [];
|
|
718
|
+
const held = [];
|
|
719
|
+
let teamHeld = false;
|
|
720
|
+
const note = (file, did) => {
|
|
721
|
+
if (did)
|
|
722
|
+
changed.push(relPosix(projectDir, file));
|
|
723
|
+
};
|
|
724
|
+
for (const root of plan.generatedRoots)
|
|
725
|
+
fs.rmSync(root, { recursive: true, force: true });
|
|
726
|
+
// The docs copies and the .rgignore wait for .git/info/exclude below, so that a sync that cannot write it leaves
|
|
727
|
+
// nothing a commit would take.
|
|
728
|
+
const docsRoot = path.join(projectDir, DOCS_DIR);
|
|
729
|
+
const copies = [...plan.generated].filter(([file]) => isInside(docsRoot, file));
|
|
730
|
+
for (const [file, content] of plan.generated)
|
|
731
|
+
if (!isInside(docsRoot, file))
|
|
732
|
+
writeIfChanged(file, content);
|
|
733
|
+
for (const [linkPath, target] of plan.links)
|
|
734
|
+
note(linkPath, linkIfChanged(linkPath, target));
|
|
735
|
+
// Executable entries in shared files, before the excludes so that every written file is listed.
|
|
736
|
+
const person = caller() !== 'model';
|
|
737
|
+
const targets = repoTargets(projectDir, plan);
|
|
738
|
+
const teamExcludes = plan.teamExcludes ? [...plan.teamExcludes] : undefined;
|
|
739
|
+
const addedExcludes = [...plan.addedExcludes];
|
|
740
|
+
let codexMcp = {};
|
|
741
|
+
for (const [group, entries, into] of [['team', plan.exec.team, teamExcludes], ['added', plan.exec.added, addedExcludes]]) {
|
|
742
|
+
if (!entries)
|
|
743
|
+
continue;
|
|
744
|
+
const applied = applyEntries(group, entries, targets, person || (group === 'team' && options.reviewed === true));
|
|
745
|
+
for (const file of applied.changed)
|
|
746
|
+
changed.push(file.startsWith(projectDir + path.sep) ? relPosix(projectDir, file) : file);
|
|
747
|
+
held.push(...applied.held);
|
|
748
|
+
if (group === 'team' && applied.held.length > 0)
|
|
749
|
+
teamHeld = true;
|
|
750
|
+
codexMcp = applied.codexMcp;
|
|
751
|
+
for (const file of applied.files)
|
|
752
|
+
if (file.startsWith(projectDir + path.sep))
|
|
753
|
+
into?.push(`/${relPosix(projectDir, file)}`);
|
|
754
|
+
}
|
|
755
|
+
// .codex/config.toml: developer_instructions and MCP servers.
|
|
756
|
+
const codexFile = path.join(projectDir, '.codex', 'config.toml');
|
|
757
|
+
if (plan.codexOurs) {
|
|
758
|
+
const parts = [
|
|
759
|
+
...(plan.codexInstructions !== '' ? [`developer_instructions = ${tomlString(plan.codexInstructions)}`] : []),
|
|
760
|
+
...(Object.keys(codexMcp).length > 0 ? [tomlTables('mcp_servers', codexMcp)] : []),
|
|
761
|
+
];
|
|
762
|
+
if (parts.length > 0) {
|
|
763
|
+
note(codexFile, writeIfChanged(codexFile, `${CODEX_MARKER}\n${parts.join('\n\n')}\n`));
|
|
764
|
+
addedExcludes.push('/.codex/config.toml');
|
|
765
|
+
}
|
|
766
|
+
else if (isFile(codexFile)) {
|
|
767
|
+
fs.rmSync(codexFile);
|
|
768
|
+
changed.push('.codex/config.toml');
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
for (const dir of [path.join(projectDir, '.codex', 'rules'), path.join(projectDir, '.codex', 'agents'), path.join(projectDir, '.codex'), path.join(projectDir, '.claude', 'agents')]) {
|
|
772
|
+
try {
|
|
773
|
+
fs.rmdirSync(dir);
|
|
774
|
+
}
|
|
775
|
+
catch {
|
|
776
|
+
// Not empty, or not there.
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
const exclude = gitExclude(projectDir);
|
|
780
|
+
if (exclude) {
|
|
781
|
+
const { prefix } = exclude;
|
|
782
|
+
const { marks, legacy } = projectSections(prefix, exclude.root);
|
|
783
|
+
const before = readTextIfExists(exclude.file);
|
|
784
|
+
// harnesspm.local.json is never committed, also when a person writes it by hand for an opt-out (spec 14.6).
|
|
785
|
+
if (isFile(path.join(projectDir, 'harnesspm.local.json')) && !(before ?? '').split('\n').includes(excludeEntry(prefix, 'harnesspm.local.json')))
|
|
786
|
+
addedExcludes.push('/harnesspm.local.json');
|
|
787
|
+
const prevTeam = [...readSection(before, marks.team, prefix), ...(legacy ? readSection(before, legacy, '') : [])];
|
|
788
|
+
const prevAdded = readSection(before, marks.added, prefix);
|
|
789
|
+
const keep = new Set([...(teamExcludes ?? prevTeam), ...addedExcludes]);
|
|
790
|
+
// Remove links from the last sync that this sync no longer writes.
|
|
791
|
+
for (const entry of new Set([...prevTeam, ...prevAdded])) {
|
|
792
|
+
const target = path.join(projectDir, entry);
|
|
793
|
+
if (keep.has(entry) || !isSymlink(target))
|
|
794
|
+
continue;
|
|
795
|
+
unlinkAndPrune(target, projectDir);
|
|
796
|
+
changed.push(entry.slice(1));
|
|
797
|
+
}
|
|
798
|
+
let text = before;
|
|
799
|
+
const sorted = (list) => [...new Set(list)].sort();
|
|
800
|
+
if (teamExcludes) {
|
|
801
|
+
// The project's own section takes over the entries an older harnesspm wrote into the root's.
|
|
802
|
+
if (legacy)
|
|
803
|
+
text = writeSection(text, legacy, [], '');
|
|
804
|
+
text = writeSection(text, marks.team, sorted(teamExcludes), prefix);
|
|
805
|
+
}
|
|
806
|
+
text = writeSection(text, marks.added, sorted(addedExcludes), prefix);
|
|
807
|
+
writeIfChanged(exclude.file, text);
|
|
808
|
+
}
|
|
809
|
+
// Only where git ignores them, as fetch does: a .gitignore pattern can bring the folder back (spec 4.3, note 8).
|
|
810
|
+
if (copies.length === 0 || gitKeepsOut(projectDir, DOCS_PROBE)) {
|
|
811
|
+
for (const [file, content] of copies)
|
|
812
|
+
writeIfChanged(file, content);
|
|
813
|
+
writeRgignore(projectDir, plan);
|
|
814
|
+
}
|
|
815
|
+
if (plan.committed && options.committed !== false) {
|
|
816
|
+
note(path.join(projectDir, 'AGENTS.md'), writeIfChanged(path.join(projectDir, 'AGENTS.md'), plan.committed.agentsMd));
|
|
817
|
+
note(path.join(projectDir, LOCK_FILE), writeIfChanged(path.join(projectDir, LOCK_FILE), plan.committed.lock));
|
|
818
|
+
for (const ws of plan.committed.workspaces) {
|
|
819
|
+
const agentsFile = path.join(ws.dir, 'AGENTS.md');
|
|
820
|
+
if (ws.agentsMd !== undefined)
|
|
821
|
+
note(agentsFile, writeIfChanged(agentsFile, ws.agentsMd));
|
|
822
|
+
else if (isFile(agentsFile)) {
|
|
823
|
+
fs.rmSync(agentsFile);
|
|
824
|
+
changed.push(relPosix(projectDir, agentsFile));
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
for (const claude of plan.committed.claudeMds)
|
|
828
|
+
note(claude.file, writeIfChanged(claude.file, claude.text));
|
|
829
|
+
}
|
|
830
|
+
// The index of harnesspm's agent hooks, only when the team layers were resolved.
|
|
831
|
+
if (plan.committed) {
|
|
832
|
+
const indexFile = path.join(projectDir, INDEX_FILE);
|
|
833
|
+
if (plan.telemetryIndex !== undefined)
|
|
834
|
+
writeIfChanged(indexFile, plan.telemetryIndex);
|
|
835
|
+
else
|
|
836
|
+
fs.rmSync(indexFile, { force: true });
|
|
837
|
+
}
|
|
838
|
+
const localFile = path.join(projectDir, 'CLAUDE.local.md');
|
|
839
|
+
if (plan.localMd !== undefined)
|
|
840
|
+
note(localFile, writeIfChanged(localFile, plan.localMd));
|
|
841
|
+
else if (isFile(localFile)) {
|
|
842
|
+
fs.rmSync(localFile);
|
|
843
|
+
changed.push('CLAUDE.local.md');
|
|
844
|
+
}
|
|
845
|
+
return { changed, held, teamHeld };
|
|
846
|
+
}
|
|
847
|
+
/** Compares the committed outputs with the plan (spec 6.4). Returns the differences. */
|
|
848
|
+
export function checkPlan(projectDir, plan) {
|
|
849
|
+
if (!plan.committed)
|
|
850
|
+
return ['the dependencies are not installed, so the committed outputs cannot be checked'];
|
|
851
|
+
const problems = [];
|
|
852
|
+
const agents = readTextIfExists(path.join(projectDir, 'AGENTS.md'));
|
|
853
|
+
if (extractBlock(agents) !== extractBlock(plan.committed.agentsMd))
|
|
854
|
+
problems.push('AGENTS.md: the harnesspm block is out of date');
|
|
855
|
+
if (!sameLock(readTextIfExists(path.join(projectDir, LOCK_FILE)), plan.committed.lock))
|
|
856
|
+
problems.push(`${LOCK_FILE} is out of date`);
|
|
857
|
+
for (const ws of plan.committed.workspaces) {
|
|
858
|
+
const rel = relPosix(projectDir, path.join(ws.dir, 'AGENTS.md'));
|
|
859
|
+
if (extractBlock(readTextIfExists(path.join(ws.dir, 'AGENTS.md'))) !== extractBlock(ws.agentsMd))
|
|
860
|
+
problems.push(`${rel}: the harnesspm block is out of date`);
|
|
861
|
+
}
|
|
862
|
+
for (const claude of plan.committed.claudeMds) {
|
|
863
|
+
if (readTextIfExists(claude.file) === claude.text)
|
|
864
|
+
continue;
|
|
865
|
+
const agents = relPosix(projectDir, path.join(claude.dir, 'AGENTS.md'));
|
|
866
|
+
problems.push(`${relPosix(projectDir, claude.file)}: the @AGENTS.md line is missing, so Claude Code does not read ${agents}`);
|
|
867
|
+
}
|
|
868
|
+
const lock = JSON.parse(plan.committed.lock);
|
|
869
|
+
for (const [name, entry] of Object.entries(lock.packages)) {
|
|
870
|
+
if (entry.approved !== undefined && entry.approved !== entry.version) {
|
|
871
|
+
problems.push(`${name} ${entry.version} is pinned and not approved (approved: ${entry.approved}). Run \`${NPX_ANY} approve ${name}\`.`);
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
return problems;
|
|
875
|
+
}
|