harness-config-manager 0.1.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/LICENSE +21 -0
- package/README.md +1547 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +584 -0
- package/dist/cli.js.map +1 -0
- package/dist/commands/config.d.ts +7 -0
- package/dist/commands/config.js +49 -0
- package/dist/commands/config.js.map +1 -0
- package/dist/commands/context.d.ts +24 -0
- package/dist/commands/context.js +329 -0
- package/dist/commands/context.js.map +1 -0
- package/dist/commands/export.d.ts +19 -0
- package/dist/commands/export.js +116 -0
- package/dist/commands/export.js.map +1 -0
- package/dist/commands/import.d.ts +33 -0
- package/dist/commands/import.js +81 -0
- package/dist/commands/import.js.map +1 -0
- package/dist/commands/info.d.ts +19 -0
- package/dist/commands/info.js +235 -0
- package/dist/commands/info.js.map +1 -0
- package/dist/commands/init.d.ts +5 -0
- package/dist/commands/init.js +116 -0
- package/dist/commands/init.js.map +1 -0
- package/dist/commands/install.d.ts +119 -0
- package/dist/commands/install.js +533 -0
- package/dist/commands/install.js.map +1 -0
- package/dist/commands/list.d.ts +9 -0
- package/dist/commands/list.js +102 -0
- package/dist/commands/list.js.map +1 -0
- package/dist/commands/params.d.ts +58 -0
- package/dist/commands/params.js +366 -0
- package/dist/commands/params.js.map +1 -0
- package/dist/commands/refs.d.ts +60 -0
- package/dist/commands/refs.js +329 -0
- package/dist/commands/refs.js.map +1 -0
- package/dist/commands/registry.d.ts +18 -0
- package/dist/commands/registry.js +173 -0
- package/dist/commands/registry.js.map +1 -0
- package/dist/commands/status.d.ts +10 -0
- package/dist/commands/status.js +83 -0
- package/dist/commands/status.js.map +1 -0
- package/dist/commands/targets.d.ts +8 -0
- package/dist/commands/targets.js +61 -0
- package/dist/commands/targets.js.map +1 -0
- package/dist/commands/uninstall.d.ts +71 -0
- package/dist/commands/uninstall.js +322 -0
- package/dist/commands/uninstall.js.map +1 -0
- package/dist/commands/update.d.ts +66 -0
- package/dist/commands/update.js +384 -0
- package/dist/commands/update.js.map +1 -0
- package/dist/commands/validate.d.ts +3 -0
- package/dist/commands/validate.js +38 -0
- package/dist/commands/validate.js.map +1 -0
- package/dist/core/bundle.d.ts +49 -0
- package/dist/core/bundle.js +326 -0
- package/dist/core/bundle.js.map +1 -0
- package/dist/core/config.d.ts +65 -0
- package/dist/core/config.js +112 -0
- package/dist/core/config.js.map +1 -0
- package/dist/core/conflicts.d.ts +67 -0
- package/dist/core/conflicts.js +300 -0
- package/dist/core/conflicts.js.map +1 -0
- package/dist/core/context.d.ts +139 -0
- package/dist/core/context.js +432 -0
- package/dist/core/context.js.map +1 -0
- package/dist/core/deps.d.ts +62 -0
- package/dist/core/deps.js +339 -0
- package/dist/core/deps.js.map +1 -0
- package/dist/core/errors.d.ts +21 -0
- package/dist/core/errors.js +26 -0
- package/dist/core/errors.js.map +1 -0
- package/dist/core/executor.d.ts +9 -0
- package/dist/core/executor.js +139 -0
- package/dist/core/executor.js.map +1 -0
- package/dist/core/flavors.d.ts +128 -0
- package/dist/core/flavors.js +386 -0
- package/dist/core/flavors.js.map +1 -0
- package/dist/core/frontmatter.d.ts +6 -0
- package/dist/core/frontmatter.js +20 -0
- package/dist/core/frontmatter.js.map +1 -0
- package/dist/core/fsx.d.ts +40 -0
- package/dist/core/fsx.js +180 -0
- package/dist/core/fsx.js.map +1 -0
- package/dist/core/github.d.ts +37 -0
- package/dist/core/github.js +157 -0
- package/dist/core/github.js.map +1 -0
- package/dist/core/harnesses.d.ts +142 -0
- package/dist/core/harnesses.js +215 -0
- package/dist/core/harnesses.js.map +1 -0
- package/dist/core/hash.d.ts +12 -0
- package/dist/core/hash.js +34 -0
- package/dist/core/hash.js.map +1 -0
- package/dist/core/logger.d.ts +16 -0
- package/dist/core/logger.js +36 -0
- package/dist/core/logger.js.map +1 -0
- package/dist/core/overlap.d.ts +79 -0
- package/dist/core/overlap.js +155 -0
- package/dist/core/overlap.js.map +1 -0
- package/dist/core/parameters.d.ts +249 -0
- package/dist/core/parameters.js +944 -0
- package/dist/core/parameters.js.map +1 -0
- package/dist/core/paths.d.ts +20 -0
- package/dist/core/paths.js +35 -0
- package/dist/core/paths.js.map +1 -0
- package/dist/core/planner.d.ts +36 -0
- package/dist/core/planner.js +364 -0
- package/dist/core/planner.js.map +1 -0
- package/dist/core/prompt.d.ts +52 -0
- package/dist/core/prompt.js +197 -0
- package/dist/core/prompt.js.map +1 -0
- package/dist/core/refmap.d.ts +91 -0
- package/dist/core/refmap.js +331 -0
- package/dist/core/refmap.js.map +1 -0
- package/dist/core/refs.d.ts +297 -0
- package/dist/core/refs.js +801 -0
- package/dist/core/refs.js.map +1 -0
- package/dist/core/registry.d.ts +119 -0
- package/dist/core/registry.js +363 -0
- package/dist/core/registry.js.map +1 -0
- package/dist/core/rename.d.ts +36 -0
- package/dist/core/rename.js +74 -0
- package/dist/core/rename.js.map +1 -0
- package/dist/core/rollback.d.ts +38 -0
- package/dist/core/rollback.js +226 -0
- package/dist/core/rollback.js.map +1 -0
- package/dist/core/semver.d.ts +56 -0
- package/dist/core/semver.js +214 -0
- package/dist/core/semver.js.map +1 -0
- package/dist/core/state.d.ts +99 -0
- package/dist/core/state.js +196 -0
- package/dist/core/state.js.map +1 -0
- package/dist/core/store.d.ts +30 -0
- package/dist/core/store.js +54 -0
- package/dist/core/store.js.map +1 -0
- package/dist/core/types.d.ts +515 -0
- package/dist/core/types.js +49 -0
- package/dist/core/types.js.map +1 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.js +16 -0
- package/dist/index.js.map +1 -0
- package/dist/merge/blocks.d.ts +48 -0
- package/dist/merge/blocks.js +0 -0
- package/dist/merge/blocks.js.map +1 -0
- package/dist/merge/json-merge.d.ts +66 -0
- package/dist/merge/json-merge.js +176 -0
- package/dist/merge/json-merge.js.map +1 -0
- package/dist/merge/toml.d.ts +48 -0
- package/dist/merge/toml.js +118 -0
- package/dist/merge/toml.js.map +1 -0
- package/dist/targets/claude-code.d.ts +11 -0
- package/dist/targets/claude-code.js +94 -0
- package/dist/targets/claude-code.js.map +1 -0
- package/dist/targets/copilot.d.ts +13 -0
- package/dist/targets/copilot.js +126 -0
- package/dist/targets/copilot.js.map +1 -0
- package/dist/targets/index.d.ts +20 -0
- package/dist/targets/index.js +60 -0
- package/dist/targets/index.js.map +1 -0
- package/dist/targets/opencode.d.ts +32 -0
- package/dist/targets/opencode.js +172 -0
- package/dist/targets/opencode.js.map +1 -0
- package/dist/targets/pi.d.ts +42 -0
- package/dist/targets/pi.js +134 -0
- package/dist/targets/pi.js.map +1 -0
- package/dist/targets/reasonix.d.ts +27 -0
- package/dist/targets/reasonix.js +192 -0
- package/dist/targets/reasonix.js.map +1 -0
- package/dist/targets/shared.d.ts +33 -0
- package/dist/targets/shared.js +109 -0
- package/dist/targets/shared.js.map +1 -0
- package/dist/targets/types.d.ts +40 -0
- package/dist/targets/types.js +17 -0
- package/dist/targets/types.js.map +1 -0
- package/docs/authoring-bundles.md +828 -0
- package/package.json +74 -0
|
@@ -0,0 +1,801 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Finding the file references a bundle's own text makes, and deciding which of
|
|
3
|
+
* them point at nothing.
|
|
4
|
+
*
|
|
5
|
+
* A bundle is prose plus config, and both are full of paths: a SKILL.md that
|
|
6
|
+
* says to work through `./checklist.md`, a command that links to
|
|
7
|
+
* [the conventions](context/10-conventions.md), an MCP server whose args name a
|
|
8
|
+
* script under `assets/`. Rename the file and every one of those becomes a lie
|
|
9
|
+
* the agent will follow.
|
|
10
|
+
*
|
|
11
|
+
* The hard part is not finding paths. It is not finding the things that merely
|
|
12
|
+
* look like paths. Prose about files is still prose:
|
|
13
|
+
*
|
|
14
|
+
* A file will be created named `output.txt`.
|
|
15
|
+
* Identify the manifest (`package.json`) and read `tsconfig.json`.
|
|
16
|
+
*
|
|
17
|
+
* Not one of those is a reference to a file the bundle ships, and a checker
|
|
18
|
+
* that says otherwise is a checker nobody runs. Filename-shaped text is far too
|
|
19
|
+
* common in writing about software to be treated as a claim about the tree.
|
|
20
|
+
*
|
|
21
|
+
* So a reference has to be *written as one*, in one of two ways:
|
|
22
|
+
*
|
|
23
|
+
* declared the syntax says outright that its target is a path --
|
|
24
|
+
* [text](path), , a [id]: definition, a [[wikilink]],
|
|
25
|
+
* or an @path mention. Nobody writes a markdown link to a turn of
|
|
26
|
+
* phrase.
|
|
27
|
+
* relative written with an explicit `./` or `../`. That prefix is a
|
|
28
|
+
* deliberate act: `./output.txt` says "the file beside this one"
|
|
29
|
+
* where `output.txt` says only "a file called that".
|
|
30
|
+
*
|
|
31
|
+
* Everything else -- a bare filename or an implicit path in inline code or a
|
|
32
|
+
* config value -- is left alone unless `--all-paths` asks for it, which is the
|
|
33
|
+
* older, noisier behaviour kept for the bundles that were written against it.
|
|
34
|
+
*
|
|
35
|
+
* What a reference is relative to is still not stated anywhere, so resolution
|
|
36
|
+
* tries both roots: `./checklist.md` next to a SKILL.md means the sibling;
|
|
37
|
+
* `skills/audit/checklist.md` in a command means the same file, from the bundle
|
|
38
|
+
* root.
|
|
39
|
+
*
|
|
40
|
+
* Under `--all-paths`, references also carry a confidence, and it decides how
|
|
41
|
+
* loud the report is:
|
|
42
|
+
*
|
|
43
|
+
* strong declared, explicitly relative, or holding a separator. Always
|
|
44
|
+
* reported.
|
|
45
|
+
* weak a bare filename in inline code or a config value. Reported only
|
|
46
|
+
* when something similar exists in the tree, which is also exactly
|
|
47
|
+
* when we have a fix to offer. `--strict` reports these regardless.
|
|
48
|
+
*
|
|
49
|
+
* @see refmap.ts for what happens to these references at install time.
|
|
50
|
+
*/
|
|
51
|
+
import path from 'node:path';
|
|
52
|
+
import { fs, isDirectory, listFiles, pathExists, toPosix } from './fsx.js';
|
|
53
|
+
import { findManifest } from './bundle.js';
|
|
54
|
+
export const REF_SYNTAXES = [
|
|
55
|
+
'link',
|
|
56
|
+
'image',
|
|
57
|
+
'definition',
|
|
58
|
+
'wikilink',
|
|
59
|
+
'code',
|
|
60
|
+
'mention',
|
|
61
|
+
'config',
|
|
62
|
+
];
|
|
63
|
+
/**
|
|
64
|
+
* The syntaxes whose target is a path by construction.
|
|
65
|
+
*
|
|
66
|
+
* `[the rules](rules/typescript.md)` cannot be a turn of phrase the way
|
|
67
|
+
* `` `rules.md` `` can: markdown has already said the thing in the parentheses
|
|
68
|
+
* is somewhere to go. The same holds for a wikilink and for the `@file`
|
|
69
|
+
* convention several harnesses read as "open this". These are checked as
|
|
70
|
+
* written, without needing a `./` in front of them.
|
|
71
|
+
*/
|
|
72
|
+
export const DECLARED_SYNTAXES = new Set([
|
|
73
|
+
'link',
|
|
74
|
+
'image',
|
|
75
|
+
'definition',
|
|
76
|
+
'wikilink',
|
|
77
|
+
'mention',
|
|
78
|
+
]);
|
|
79
|
+
/** What `--links` narrows to: the syntaxes that are a link of some kind. */
|
|
80
|
+
export const LINK_SYNTAXES = new Set([
|
|
81
|
+
'link',
|
|
82
|
+
'image',
|
|
83
|
+
'definition',
|
|
84
|
+
'wikilink',
|
|
85
|
+
]);
|
|
86
|
+
/**
|
|
87
|
+
* The scope a scan was asked for, as the rules extraction follows.
|
|
88
|
+
*
|
|
89
|
+
* `--strict` is a louder `--all-paths` rather than a scope of its own: it
|
|
90
|
+
* changes which of the found references get *reported*, not which get found.
|
|
91
|
+
*/
|
|
92
|
+
export function refPolicy(scope = {}) {
|
|
93
|
+
const permissive = scope.allPaths === true || scope.strict === true;
|
|
94
|
+
return {
|
|
95
|
+
syntaxes: scope.links === true ? LINK_SYNTAXES : new Set(REF_SYNTAXES),
|
|
96
|
+
requireExplicitRelative: !permissive,
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* What the installer reads, which is not what the checker reads.
|
|
101
|
+
*
|
|
102
|
+
* Remapping rewrites references it can prove point at a bundle file (see
|
|
103
|
+
* refmap.ts), so a false positive costs nothing there -- an implicit
|
|
104
|
+
* `skills/audit/checklist.md` that resolves is repointed, and prose that only
|
|
105
|
+
* looks like a path resolves to nothing and is left alone. Wikilinks are the
|
|
106
|
+
* exception in the other direction: they are resolved by *name* rather than by
|
|
107
|
+
* path, so rewriting one into a relative path would break it.
|
|
108
|
+
*/
|
|
109
|
+
export const INSTALL_POLICY = {
|
|
110
|
+
syntaxes: new Set(REF_SYNTAXES.filter((syntax) => syntax !== 'wikilink')),
|
|
111
|
+
requireExplicitRelative: false,
|
|
112
|
+
};
|
|
113
|
+
// ---------------------------------------------------------------------------
|
|
114
|
+
// What we read, and what we refuse to treat as a path
|
|
115
|
+
// ---------------------------------------------------------------------------
|
|
116
|
+
const MARKDOWN = new Set(['.md', '.markdown', '.mdx']);
|
|
117
|
+
const CONFIG = new Set(['.json', '.yaml', '.yml', '.toml']);
|
|
118
|
+
const SKIP_DIRS = new Set(['.git', 'node_modules', '.hcm', 'dist', 'build', '.venv', '__pycache__']);
|
|
119
|
+
/**
|
|
120
|
+
* Extensions a reference in a bundle plausibly points at. Anything else in
|
|
121
|
+
* inline code is a command, an identifier or a version number -- `v1.2.3` and
|
|
122
|
+
* `foo.bar()` would otherwise both read as filenames.
|
|
123
|
+
*/
|
|
124
|
+
const REFERENCE_EXTENSIONS = new Set([
|
|
125
|
+
'md', 'markdown', 'mdx', 'txt', 'rst',
|
|
126
|
+
'json', 'yaml', 'yml', 'toml', 'ini', 'cfg', 'env',
|
|
127
|
+
'js', 'mjs', 'cjs', 'ts', 'tsx', 'jsx', 'py', 'rb', 'go', 'rs', 'java', 'sh', 'bash', 'ps1',
|
|
128
|
+
'sql', 'csv', 'tsv',
|
|
129
|
+
'png', 'jpg', 'jpeg', 'gif', 'svg', 'webp', 'pdf',
|
|
130
|
+
'html', 'css', 'tmpl', 'template', 'j2',
|
|
131
|
+
]);
|
|
132
|
+
/**
|
|
133
|
+
* Filenames that turn up in prose about a project rather than as references to
|
|
134
|
+
* files the bundle ships. Without this, every skill that mentions running an
|
|
135
|
+
* audit reports `package.json` as a broken reference.
|
|
136
|
+
*/
|
|
137
|
+
const AMBIENT_FILENAMES = new Set([
|
|
138
|
+
'package.json', 'package-lock.json', 'pnpm-lock.yaml', 'yarn.lock', 'bun.lockb',
|
|
139
|
+
'tsconfig.json', 'jsconfig.json', 'eslintrc.json', '.eslintrc.json', '.prettierrc',
|
|
140
|
+
'requirements.txt', 'pyproject.toml', 'poetry.lock', 'setup.py', 'setup.cfg', 'pipfile.lock',
|
|
141
|
+
'cargo.toml', 'cargo.lock', 'go.mod', 'go.sum', 'gemfile', 'gemfile.lock',
|
|
142
|
+
'dockerfile', 'docker-compose.yml', 'docker-compose.yaml', 'makefile',
|
|
143
|
+
'.gitignore', '.env', '.env.local', '.npmrc', '.editorconfig',
|
|
144
|
+
'readme.md', 'license', 'license.md', 'changelog.md', 'contributing.md',
|
|
145
|
+
// hcm's own vocabulary: these name a convention, not a file to point at.
|
|
146
|
+
'hcm.yaml', 'hcm.yml', 'hcm.json', 'claude.md', 'agents.md', 'reasonix.md',
|
|
147
|
+
'settings.json', 'mcp.json', '.mcp.json', 'opencode.json', 'reasonix.toml',
|
|
148
|
+
'copilot-instructions.md',
|
|
149
|
+
]);
|
|
150
|
+
const URL_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
|
|
151
|
+
// ---------------------------------------------------------------------------
|
|
152
|
+
// Scanning
|
|
153
|
+
// ---------------------------------------------------------------------------
|
|
154
|
+
/**
|
|
155
|
+
* Read every markdown file and config under `root`, extract the references, and
|
|
156
|
+
* work out which of them point at nothing.
|
|
157
|
+
*
|
|
158
|
+
* `root` is normally a bundle or a collection of bundles; it does not have to
|
|
159
|
+
* be either -- files outside any bundle are still read, they simply have no
|
|
160
|
+
* bundle root to resolve against.
|
|
161
|
+
*/
|
|
162
|
+
export async function scanReferences(root, options = {}) {
|
|
163
|
+
const absoluteRoot = path.resolve(root);
|
|
164
|
+
if (!(await isDirectory(absoluteRoot))) {
|
|
165
|
+
// A single file is a legitimate thing to check; treat its directory as the
|
|
166
|
+
// root so relative paths in the report still mean something.
|
|
167
|
+
const parent = path.dirname(absoluteRoot);
|
|
168
|
+
return scanFiles(parent, [absoluteRoot], options);
|
|
169
|
+
}
|
|
170
|
+
const files = (await listTree(absoluteRoot)).filter((file) => isScannable(file));
|
|
171
|
+
return scanFiles(absoluteRoot, files, options);
|
|
172
|
+
}
|
|
173
|
+
async function scanFiles(root, files, options) {
|
|
174
|
+
const bundles = await findBundleRoots(root);
|
|
175
|
+
const index = await buildFileIndex(root);
|
|
176
|
+
const policy = refPolicy(options);
|
|
177
|
+
const refs = [];
|
|
178
|
+
for (const file of files) {
|
|
179
|
+
const text = await fs.readFile(file, 'utf8').catch(() => undefined);
|
|
180
|
+
if (text === undefined)
|
|
181
|
+
continue;
|
|
182
|
+
const bundleRoot = bundleRootFor(file, bundles);
|
|
183
|
+
const found = extractRefs(file, text, policy);
|
|
184
|
+
for (const ref of found) {
|
|
185
|
+
refs.push({
|
|
186
|
+
...ref,
|
|
187
|
+
fileRelative: toPosix(path.relative(root, file)),
|
|
188
|
+
...(bundleRoot ? { bundleRoot } : {}),
|
|
189
|
+
...(await resolveRef(ref.ref, file, bundleRoot, { syntax: ref.syntax, index })),
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
const limit = options.suggestions ?? 3;
|
|
194
|
+
const broken = [];
|
|
195
|
+
for (const ref of refs) {
|
|
196
|
+
if (ref.target !== undefined)
|
|
197
|
+
continue;
|
|
198
|
+
const suggestions = suggestFixes(ref, index, limit);
|
|
199
|
+
// A weak reference with nothing like it in the tree is prose about a file
|
|
200
|
+
// this bundle does not ship -- reported only when asked for explicitly.
|
|
201
|
+
if (ref.confidence === 'weak' && suggestions.length === 0 && !options.strict)
|
|
202
|
+
continue;
|
|
203
|
+
broken.push({ ...ref, suggestions });
|
|
204
|
+
}
|
|
205
|
+
return {
|
|
206
|
+
root,
|
|
207
|
+
// The scope as it was *applied*, not as it was typed: `--strict` implies
|
|
208
|
+
// `--all-paths`, and a report that said otherwise would be describing a
|
|
209
|
+
// scan that did not happen.
|
|
210
|
+
scope: {
|
|
211
|
+
links: options.links === true,
|
|
212
|
+
allPaths: options.allPaths === true || options.strict === true,
|
|
213
|
+
strict: options.strict === true,
|
|
214
|
+
},
|
|
215
|
+
scanned: files,
|
|
216
|
+
bundles,
|
|
217
|
+
refs,
|
|
218
|
+
broken,
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
export function isScannable(file) {
|
|
222
|
+
const extension = path.extname(file).toLowerCase();
|
|
223
|
+
return MARKDOWN.has(extension) || CONFIG.has(extension);
|
|
224
|
+
}
|
|
225
|
+
async function listTree(root) {
|
|
226
|
+
const out = [];
|
|
227
|
+
async function walk(dir) {
|
|
228
|
+
let entries;
|
|
229
|
+
try {
|
|
230
|
+
entries = await fs.readdir(dir, { withFileTypes: true });
|
|
231
|
+
}
|
|
232
|
+
catch {
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
236
|
+
if (SKIP_DIRS.has(entry.name))
|
|
237
|
+
continue;
|
|
238
|
+
const full = path.join(dir, entry.name);
|
|
239
|
+
if (entry.isDirectory())
|
|
240
|
+
await walk(full);
|
|
241
|
+
else if (entry.isFile())
|
|
242
|
+
out.push(full);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
await walk(root);
|
|
246
|
+
return out;
|
|
247
|
+
}
|
|
248
|
+
/** Bundle roots at or under `root`, deepest first so lookup finds the innermost. */
|
|
249
|
+
async function findBundleRoots(root) {
|
|
250
|
+
const found = [];
|
|
251
|
+
async function walk(dir, depth) {
|
|
252
|
+
if (await findManifest(dir))
|
|
253
|
+
found.push(dir);
|
|
254
|
+
// Bundles do not nest, and a collection is one level deep -- but a scan
|
|
255
|
+
// root two levels above a bundle is an easy mistake, so allow a little.
|
|
256
|
+
if (depth >= 3)
|
|
257
|
+
return;
|
|
258
|
+
let entries;
|
|
259
|
+
try {
|
|
260
|
+
entries = await fs.readdir(dir, { withFileTypes: true });
|
|
261
|
+
}
|
|
262
|
+
catch {
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
265
|
+
for (const entry of entries) {
|
|
266
|
+
if (!entry.isDirectory() || SKIP_DIRS.has(entry.name) || entry.name.startsWith('.'))
|
|
267
|
+
continue;
|
|
268
|
+
await walk(path.join(dir, entry.name), depth + 1);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
await walk(root, 0);
|
|
272
|
+
return found.sort((a, b) => b.length - a.length);
|
|
273
|
+
}
|
|
274
|
+
function bundleRootFor(file, bundles) {
|
|
275
|
+
// Sorted deepest-first, so the first containing root is the innermost.
|
|
276
|
+
return bundles.find((bundle) => isInside(file, bundle));
|
|
277
|
+
}
|
|
278
|
+
function isInside(file, dir) {
|
|
279
|
+
const relative = path.relative(dir, file);
|
|
280
|
+
return relative !== '' && !relative.startsWith('..') && !path.isAbsolute(relative);
|
|
281
|
+
}
|
|
282
|
+
// ---------------------------------------------------------------------------
|
|
283
|
+
// Extraction
|
|
284
|
+
// ---------------------------------------------------------------------------
|
|
285
|
+
/**
|
|
286
|
+
* Every reference candidate in one file, with its offsets.
|
|
287
|
+
*
|
|
288
|
+
* `policy` decides what counts as one. It defaults to `INSTALL_POLICY` -- the
|
|
289
|
+
* permissive reading the installer needs -- so that a caller who has not
|
|
290
|
+
* thought about scope gets the same answer this always gave. `scanReferences`
|
|
291
|
+
* passes the checker's narrower policy explicitly.
|
|
292
|
+
*/
|
|
293
|
+
export function extractRefs(file, text, policy = INSTALL_POLICY) {
|
|
294
|
+
const extension = path.extname(file).toLowerCase();
|
|
295
|
+
const found = MARKDOWN.has(extension) ? extractFromMarkdown(text) : extractFromConfig(text);
|
|
296
|
+
return found
|
|
297
|
+
.filter((candidate) => policy.syntaxes.has(candidate.syntax))
|
|
298
|
+
.filter((candidate) => looksLikePath(candidate.ref, candidate.syntax))
|
|
299
|
+
.filter((candidate) => isInScope(candidate.ref, candidate.syntax, policy))
|
|
300
|
+
.map((candidate) => ({
|
|
301
|
+
file,
|
|
302
|
+
ref: candidate.ref,
|
|
303
|
+
syntax: candidate.syntax,
|
|
304
|
+
confidence: confidenceOf(candidate.ref, candidate.syntax),
|
|
305
|
+
line: lineOf(text, candidate.start),
|
|
306
|
+
start: candidate.start,
|
|
307
|
+
end: candidate.end,
|
|
308
|
+
}));
|
|
309
|
+
}
|
|
310
|
+
/**
|
|
311
|
+
* The rule that keeps prose out of the report.
|
|
312
|
+
*
|
|
313
|
+
* A declared reference is in scope whatever it says -- the syntax has already
|
|
314
|
+
* vouched for it. Anything else has to have been written as a path on purpose,
|
|
315
|
+
* and `./` or `../` is the only mark of that a bundle author can make. A bare
|
|
316
|
+
* `output.txt` in a sentence about creating a file is indistinguishable from a
|
|
317
|
+
* bare `output.txt` meant as a reference, so neither is treated as one.
|
|
318
|
+
*/
|
|
319
|
+
export function isInScope(ref, syntax, policy) {
|
|
320
|
+
if (!policy.requireExplicitRelative)
|
|
321
|
+
return true;
|
|
322
|
+
if (DECLARED_SYNTAXES.has(syntax))
|
|
323
|
+
return true;
|
|
324
|
+
return isExplicitlyRelative(ref);
|
|
325
|
+
}
|
|
326
|
+
/** `./here.md` and `../up/there.md`, and nothing else. */
|
|
327
|
+
export function isExplicitlyRelative(ref) {
|
|
328
|
+
return /^\.\.?\//.test(ref.trim());
|
|
329
|
+
}
|
|
330
|
+
/** `[start, end)` of every single-backtick inline code span. */
|
|
331
|
+
const INLINE_CODE = /(?<!`)`([^`\n]+)`(?!`)/g;
|
|
332
|
+
/**
|
|
333
|
+
* Markdown, minus the parts of it that are not prose.
|
|
334
|
+
*
|
|
335
|
+
* Fenced code blocks are stripped first: they are examples and shell sessions,
|
|
336
|
+
* and the paths in them belong to whatever the example is about, not to the
|
|
337
|
+
* bundle. Inline code is kept, because that is how the skills that ship with
|
|
338
|
+
* hcm point at their own supporting files.
|
|
339
|
+
*
|
|
340
|
+
* What inline code does *not* keep is a declared reference written inside it.
|
|
341
|
+
* Documentation about markdown is full of them --
|
|
342
|
+
*
|
|
343
|
+
* the syntax says its target is a path: `[text](path)`, `[[wikilink]]`
|
|
344
|
+
*
|
|
345
|
+
* -- and none of those is a link, in the sense that no reader will ever follow
|
|
346
|
+
* one. A backtick span is a display, so its contents are considered only as the
|
|
347
|
+
* one `code` candidate they visibly are.
|
|
348
|
+
*/
|
|
349
|
+
function extractFromMarkdown(text) {
|
|
350
|
+
const masked = maskFences(text);
|
|
351
|
+
const candidates = [];
|
|
352
|
+
const codeSpans = [...masked.matchAll(INLINE_CODE)].map((match) => ({
|
|
353
|
+
start: match.index,
|
|
354
|
+
end: match.index + match[0].length,
|
|
355
|
+
}));
|
|
356
|
+
const shown = (at) => codeSpans.some((span) => at > span.start && at < span.end);
|
|
357
|
+
//  and [text](target), with optional "title" after the target.
|
|
358
|
+
const link = /(!?)\[[^\]\n]*\]\(\s*([^)\s]+)(?:\s+"[^"]*")?\s*\)/g;
|
|
359
|
+
for (const match of masked.matchAll(link)) {
|
|
360
|
+
const whole = match[0];
|
|
361
|
+
const bang = match[1] === '!';
|
|
362
|
+
const target = match[2];
|
|
363
|
+
const offset = match.index + whole.indexOf(target, bang ? 2 : 1);
|
|
364
|
+
candidates.push({
|
|
365
|
+
ref: stripAnchor(target),
|
|
366
|
+
syntax: bang ? 'image' : 'link',
|
|
367
|
+
start: offset,
|
|
368
|
+
end: offset + stripAnchor(target).length,
|
|
369
|
+
});
|
|
370
|
+
}
|
|
371
|
+
// [[target]], [[target|alias]], [[target#heading]] -- the wiki convention.
|
|
372
|
+
// The alias and the heading are not part of the path; only the target is
|
|
373
|
+
// offset-recorded, so a fix rewrites the target and leaves the rest alone.
|
|
374
|
+
const wiki = /\[\[([^[\]\n]+)\]\]/g;
|
|
375
|
+
for (const match of masked.matchAll(wiki)) {
|
|
376
|
+
const inner = match[1];
|
|
377
|
+
const target = stripAnchor(inner.split('|')[0]).trim();
|
|
378
|
+
if (!target)
|
|
379
|
+
continue;
|
|
380
|
+
const offset = match.index + 2 + inner.indexOf(target);
|
|
381
|
+
candidates.push({ ref: target, syntax: 'wikilink', start: offset, end: offset + target.length });
|
|
382
|
+
}
|
|
383
|
+
// [id]: target -- a link definition, at the start of a line.
|
|
384
|
+
const definition = /^[ \t]{0,3}\[[^\]\n]+\]:[ \t]+(\S+)/gm;
|
|
385
|
+
for (const match of masked.matchAll(definition)) {
|
|
386
|
+
const target = match[1];
|
|
387
|
+
const offset = match.index + match[0].lastIndexOf(target);
|
|
388
|
+
candidates.push({
|
|
389
|
+
ref: stripAnchor(target),
|
|
390
|
+
syntax: 'definition',
|
|
391
|
+
start: offset,
|
|
392
|
+
end: offset + stripAnchor(target).length,
|
|
393
|
+
});
|
|
394
|
+
}
|
|
395
|
+
// `target` -- single-backtick inline code only; a double-backtick span is
|
|
396
|
+
// nearly always code containing a backtick, not a path.
|
|
397
|
+
for (const match of masked.matchAll(INLINE_CODE)) {
|
|
398
|
+
const inner = match[1].trim();
|
|
399
|
+
const offset = match.index + 1 + match[1].indexOf(inner);
|
|
400
|
+
candidates.push({ ref: inner, syntax: 'code', start: offset, end: offset + inner.length });
|
|
401
|
+
}
|
|
402
|
+
// @path/to/file -- the "read this file" convention several harnesses use.
|
|
403
|
+
const mention = /(^|[\s(])@([A-Za-z0-9._\-/]+\.[A-Za-z0-9]{1,8})/g;
|
|
404
|
+
for (const match of masked.matchAll(mention)) {
|
|
405
|
+
const target = match[2];
|
|
406
|
+
const offset = match.index + match[1].length + 1;
|
|
407
|
+
candidates.push({ ref: target, syntax: 'mention', start: offset, end: offset + target.length });
|
|
408
|
+
}
|
|
409
|
+
return candidates
|
|
410
|
+
.filter((candidate) => candidate.syntax === 'code' || !shown(candidate.start))
|
|
411
|
+
.sort((a, b) => a.start - b.start);
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* Configs, treated as text rather than parsed.
|
|
415
|
+
*
|
|
416
|
+
* Parsing would mean three parsers and a walk per format, and would still have
|
|
417
|
+
* to find the offset of the value to edit it in place. Every one of these
|
|
418
|
+
* formats quotes its strings, so the quoted spans are the values -- and a path
|
|
419
|
+
* that is not quoted is not a path in any of them.
|
|
420
|
+
*/
|
|
421
|
+
function extractFromConfig(text) {
|
|
422
|
+
const candidates = [];
|
|
423
|
+
const string = /"([^"\n\\]*)"|'([^'\n\\]*)'/g;
|
|
424
|
+
for (const match of text.matchAll(string)) {
|
|
425
|
+
const value = (match[1] ?? match[2]);
|
|
426
|
+
if (!value)
|
|
427
|
+
continue;
|
|
428
|
+
const offset = match.index + 1;
|
|
429
|
+
candidates.push({ ref: value, syntax: 'config', start: offset, end: offset + value.length });
|
|
430
|
+
}
|
|
431
|
+
return candidates;
|
|
432
|
+
}
|
|
433
|
+
/** Replace fenced code blocks with spaces, keeping every offset where it was. */
|
|
434
|
+
function maskFences(text) {
|
|
435
|
+
return text.replace(/^([ \t]*)(```+|~~~+)[^\n]*\n[\s\S]*?^[ \t]*\2[^\n]*$/gm, (block) => block.replace(/[^\n]/g, ' '));
|
|
436
|
+
}
|
|
437
|
+
function stripAnchor(target) {
|
|
438
|
+
const hash = target.indexOf('#');
|
|
439
|
+
return hash === -1 ? target : target.slice(0, hash);
|
|
440
|
+
}
|
|
441
|
+
function lineOf(text, offset) {
|
|
442
|
+
let line = 1;
|
|
443
|
+
for (let index = 0; index < offset && index < text.length; index += 1) {
|
|
444
|
+
if (text[index] === '\n')
|
|
445
|
+
line += 1;
|
|
446
|
+
}
|
|
447
|
+
return line;
|
|
448
|
+
}
|
|
449
|
+
// ---------------------------------------------------------------------------
|
|
450
|
+
// Is this a path at all?
|
|
451
|
+
// ---------------------------------------------------------------------------
|
|
452
|
+
/**
|
|
453
|
+
* The filter that keeps the report worth reading.
|
|
454
|
+
*
|
|
455
|
+
* A link's target is a path by construction, so only the obvious non-paths are
|
|
456
|
+
* dropped. Everything else has to look like one: a name with a plausible
|
|
457
|
+
* extension, no spaces, no shell in it, and not one of the filenames prose
|
|
458
|
+
* mentions about projects in general.
|
|
459
|
+
*/
|
|
460
|
+
export function looksLikePath(ref, syntax) {
|
|
461
|
+
const value = ref.trim();
|
|
462
|
+
if (!value)
|
|
463
|
+
return false;
|
|
464
|
+
// Not ours to check: URLs, mail links, anchors, absolute and home paths, and
|
|
465
|
+
// anything with a variable in it that only the harness can expand.
|
|
466
|
+
if (URL_SCHEME.test(value) && !value.startsWith('.'))
|
|
467
|
+
return false;
|
|
468
|
+
if (value.startsWith('#') || value.startsWith('/') || value.startsWith('~'))
|
|
469
|
+
return false;
|
|
470
|
+
if (/^[A-Za-z]:[\\/]/.test(value) || value.startsWith('\\'))
|
|
471
|
+
return false;
|
|
472
|
+
if (/[$%{}*?<>|"'`]/.test(value))
|
|
473
|
+
return false;
|
|
474
|
+
if (value.includes('\\'))
|
|
475
|
+
return false;
|
|
476
|
+
// A path rooted at a hidden directory is describing where something lands
|
|
477
|
+
// *after* installation -- `.claude/agents/x.md`, `.vscode/mcp.json` -- which
|
|
478
|
+
// is what a bundle's own README is full of. Bundles ship no hidden resource
|
|
479
|
+
// directories, so this can never be a reference into one. `.` and `..` are
|
|
480
|
+
// ordinary relative paths and stay.
|
|
481
|
+
const first = value.replace(/^\.\//, '').split('/')[0];
|
|
482
|
+
if (value.includes('/') && first.startsWith('.') && first !== '.' && first !== '..')
|
|
483
|
+
return false;
|
|
484
|
+
// A wikilink names a file rather than spelling a path to it: spaces are
|
|
485
|
+
// ordinary in one, and the extension is normally left off entirely.
|
|
486
|
+
if (syntax === 'wikilink')
|
|
487
|
+
return true;
|
|
488
|
+
const linkish = syntax === 'link' || syntax === 'image' || syntax === 'definition';
|
|
489
|
+
// A link may legitimately point at a directory, so it needs no extension.
|
|
490
|
+
if (linkish)
|
|
491
|
+
return !value.includes(' ');
|
|
492
|
+
// Anything else has to be a single token that ends in a known extension.
|
|
493
|
+
if (/\s/.test(value))
|
|
494
|
+
return false;
|
|
495
|
+
const extension = path.posix.extname(value).replace('.', '').toLowerCase();
|
|
496
|
+
if (!REFERENCE_EXTENSIONS.has(extension))
|
|
497
|
+
return false;
|
|
498
|
+
// `--json`, `-v`: flags that happen to end in something extension-shaped.
|
|
499
|
+
if (value.startsWith('-'))
|
|
500
|
+
return false;
|
|
501
|
+
const base = path.posix.basename(value).toLowerCase();
|
|
502
|
+
if (AMBIENT_FILENAMES.has(base) && !value.includes('/'))
|
|
503
|
+
return false;
|
|
504
|
+
return true;
|
|
505
|
+
}
|
|
506
|
+
/**
|
|
507
|
+
* Written as a reference, or merely shaped like one.
|
|
508
|
+
*
|
|
509
|
+
* Declared syntax says outright that it is a reference, and so does an explicit
|
|
510
|
+
* `./`. A separator is weaker evidence but still evidence: a bare
|
|
511
|
+
* `checklist.md` in a sentence might be prose, while `skills/audit/checklist.md`
|
|
512
|
+
* is nobody's turn of phrase.
|
|
513
|
+
*
|
|
514
|
+
* Only `--all-paths` can produce anything but `strong`, which is the point --
|
|
515
|
+
* the narrow scope admits nothing it is unsure about.
|
|
516
|
+
*/
|
|
517
|
+
function confidenceOf(ref, syntax) {
|
|
518
|
+
if (DECLARED_SYNTAXES.has(syntax))
|
|
519
|
+
return 'strong';
|
|
520
|
+
if (isExplicitlyRelative(ref))
|
|
521
|
+
return 'strong';
|
|
522
|
+
return ref.includes('/') ? 'strong' : 'weak';
|
|
523
|
+
}
|
|
524
|
+
/**
|
|
525
|
+
* Where a reference points, trying both roots a bundle author might have meant.
|
|
526
|
+
*
|
|
527
|
+
* The bundle root comes first: that is the convention `hcm` installs against
|
|
528
|
+
* (see refmap.ts), so a path that resolves both ways is read as the bundle-
|
|
529
|
+
* relative one. The file-relative fallback is what makes a skill's
|
|
530
|
+
* `./checklist.md` work, and what keeps every bundle written before this
|
|
531
|
+
* existed resolving as it always did.
|
|
532
|
+
*
|
|
533
|
+
* A wikilink is the exception, because it is a name and not a path. `[[release
|
|
534
|
+
* checklist]]` gets its extension guessed, and then, failing both roots, is
|
|
535
|
+
* looked up by name anywhere in the same bundle -- which is how every tool that
|
|
536
|
+
* reads wikilinks resolves them, and the only reading under which the common
|
|
537
|
+
* form of one resolves at all.
|
|
538
|
+
*/
|
|
539
|
+
export async function resolveRef(ref, file, bundleRoot, options = {}) {
|
|
540
|
+
const cleaned = stripAnchor(ref.trim()).replace(/^\.\//, '');
|
|
541
|
+
if (!cleaned)
|
|
542
|
+
return {};
|
|
543
|
+
const wiki = options.syntax === 'wikilink';
|
|
544
|
+
for (const candidate of wiki ? wikilinkCandidates(cleaned) : [cleaned]) {
|
|
545
|
+
const segments = candidate.split('/');
|
|
546
|
+
if (bundleRoot && !candidate.startsWith('..')) {
|
|
547
|
+
const fromBundle = path.resolve(bundleRoot, ...segments);
|
|
548
|
+
if (await pathExists(fromBundle))
|
|
549
|
+
return { target: fromBundle, via: 'bundle' };
|
|
550
|
+
}
|
|
551
|
+
const fromFile = path.resolve(path.dirname(file), ...segments);
|
|
552
|
+
if (await pathExists(fromFile))
|
|
553
|
+
return { target: fromFile, via: 'file' };
|
|
554
|
+
}
|
|
555
|
+
if (wiki && options.index) {
|
|
556
|
+
const named = findByName(cleaned, options.index, bundleRoot);
|
|
557
|
+
if (named)
|
|
558
|
+
return { target: named, via: 'name' };
|
|
559
|
+
}
|
|
560
|
+
return {};
|
|
561
|
+
}
|
|
562
|
+
/**
|
|
563
|
+
* The paths one wikilink might mean, likeliest first.
|
|
564
|
+
*
|
|
565
|
+
* `[[notes]]` is a markdown file called notes far more often than it is a
|
|
566
|
+
* directory called notes, so the extensions are tried before the bare name. A
|
|
567
|
+
* wikilink that already carries an extension is taken at its word.
|
|
568
|
+
*/
|
|
569
|
+
function wikilinkCandidates(value) {
|
|
570
|
+
const extension = path.posix.extname(value).replace('.', '').toLowerCase();
|
|
571
|
+
if (extension && REFERENCE_EXTENSIONS.has(extension))
|
|
572
|
+
return [value];
|
|
573
|
+
return [`${value}.md`, `${value}.markdown`, `${value}.mdx`, value];
|
|
574
|
+
}
|
|
575
|
+
/**
|
|
576
|
+
* A wikilink resolved the way wiki tools resolve one: by the name of the file,
|
|
577
|
+
* wherever it happens to sit.
|
|
578
|
+
*
|
|
579
|
+
* Confined to the bundle doing the referring. A wikilink reaching into a
|
|
580
|
+
* sibling bundle would not survive installation -- the two need not be
|
|
581
|
+
* installed together, and refmap.ts cannot rewrite a name into a path without
|
|
582
|
+
* destroying it -- so treating that as resolved would be a lie.
|
|
583
|
+
*/
|
|
584
|
+
function findByName(ref, index, bundleRoot) {
|
|
585
|
+
const wanted = stem(path.posix.basename(ref));
|
|
586
|
+
if (!wanted)
|
|
587
|
+
return undefined;
|
|
588
|
+
const matches = index.filter((entry) => stem(entry.base) === wanted && (bundleRoot === undefined || entry.bundleRoot === bundleRoot));
|
|
589
|
+
return matches[0]?.absolute;
|
|
590
|
+
}
|
|
591
|
+
/** Every file under the scan root, with the bits the ranking needs precomputed. */
|
|
592
|
+
async function buildFileIndex(root) {
|
|
593
|
+
const bundles = await findBundleRoots(root);
|
|
594
|
+
const files = (await listFiles(root)).filter((file) => !file.split(path.sep).some((segment) => SKIP_DIRS.has(segment)));
|
|
595
|
+
return files.map((absolute) => {
|
|
596
|
+
const bundleRoot = bundleRootFor(absolute, bundles);
|
|
597
|
+
return {
|
|
598
|
+
absolute,
|
|
599
|
+
relative: toPosix(path.relative(root, absolute)),
|
|
600
|
+
base: path.basename(absolute),
|
|
601
|
+
extension: path.extname(absolute).toLowerCase(),
|
|
602
|
+
...(bundleRoot ? { bundleRoot } : {}),
|
|
603
|
+
};
|
|
604
|
+
});
|
|
605
|
+
}
|
|
606
|
+
/**
|
|
607
|
+
* The files this reference most plausibly meant.
|
|
608
|
+
*
|
|
609
|
+
* Ranked on the name first -- a rename is what usually breaks a reference, and
|
|
610
|
+
* a renamed file keeps most of its name -- then nudged by the things that make
|
|
611
|
+
* one candidate likelier than another with the same name: the same extension,
|
|
612
|
+
* a matching parent directory, and being in the bundle doing the referring.
|
|
613
|
+
*/
|
|
614
|
+
export function suggestFixes(ref, index, limit = 3) {
|
|
615
|
+
const wanted = path.posix.basename(ref.ref.trim());
|
|
616
|
+
if (!wanted)
|
|
617
|
+
return [];
|
|
618
|
+
const wantedStem = stem(wanted);
|
|
619
|
+
const wantedExtension = path.posix.extname(wanted).toLowerCase();
|
|
620
|
+
const wantedParent = path.posix.basename(path.posix.dirname(ref.ref.trim()));
|
|
621
|
+
const scored = [];
|
|
622
|
+
for (const entry of index) {
|
|
623
|
+
if (entry.absolute === ref.file)
|
|
624
|
+
continue;
|
|
625
|
+
let score = similarity(wantedStem, stem(entry.base));
|
|
626
|
+
if (score < 0.3)
|
|
627
|
+
continue;
|
|
628
|
+
if (wantedExtension && entry.extension === wantedExtension)
|
|
629
|
+
score += 0.12;
|
|
630
|
+
else if (wantedExtension && entry.extension !== wantedExtension)
|
|
631
|
+
score -= 0.15;
|
|
632
|
+
if (wantedParent && path.basename(path.dirname(entry.absolute)) === wantedParent)
|
|
633
|
+
score += 0.1;
|
|
634
|
+
const crossBundle = ref.bundleRoot !== undefined && entry.bundleRoot !== ref.bundleRoot;
|
|
635
|
+
// A file in another bundle can be the answer -- a dependency's asset, say --
|
|
636
|
+
// but only once nothing in this bundle fits, and it cannot be remapped on
|
|
637
|
+
// install, so it never outranks a local candidate.
|
|
638
|
+
if (crossBundle)
|
|
639
|
+
score -= 0.25;
|
|
640
|
+
scored.push({
|
|
641
|
+
ref: suggestionPath(entry, ref),
|
|
642
|
+
target: entry.absolute,
|
|
643
|
+
score: Math.min(score, 1),
|
|
644
|
+
crossBundle,
|
|
645
|
+
});
|
|
646
|
+
}
|
|
647
|
+
return scored
|
|
648
|
+
.sort((a, b) =>
|
|
649
|
+
// Local before foreign, whatever the scores say: a file in another
|
|
650
|
+
// bundle may not be installed alongside this one, and cannot be
|
|
651
|
+
// remapped if it is. Only then by how well the name matches.
|
|
652
|
+
Number(a.crossBundle) - Number(b.crossBundle) ||
|
|
653
|
+
b.score - a.score ||
|
|
654
|
+
a.ref.localeCompare(b.ref))
|
|
655
|
+
.filter((suggestion) => suggestion.score >= 0.35)
|
|
656
|
+
.slice(0, limit);
|
|
657
|
+
}
|
|
658
|
+
/**
|
|
659
|
+
* How a suggestion should be written.
|
|
660
|
+
*
|
|
661
|
+
* In the same form it is replacing, or the fix would not be a fix.
|
|
662
|
+
*
|
|
663
|
+
* A wikilink takes the file's name without its extension, which is what a
|
|
664
|
+
* wikilink holds. A reference the author wrote `./like this` keeps its prefix:
|
|
665
|
+
* that prefix is what put it in scope in the first place, and a "fix" that
|
|
666
|
+
* quietly turned it into a bare path would drop it out of every later check.
|
|
667
|
+
* Everything else takes a bundle-relative path, the form `hcm` remaps on
|
|
668
|
+
* install -- or, for a file in another bundle, one relative to the referring
|
|
669
|
+
* file, which is a reference that will not survive installation; the report
|
|
670
|
+
* says so.
|
|
671
|
+
*/
|
|
672
|
+
function suggestionPath(entry, ref) {
|
|
673
|
+
if (ref.syntax === 'wikilink')
|
|
674
|
+
return path.basename(entry.absolute, path.extname(entry.absolute));
|
|
675
|
+
const fromFile = toPosix(path.relative(path.dirname(ref.file), entry.absolute));
|
|
676
|
+
if (isExplicitlyRelative(ref.ref))
|
|
677
|
+
return fromFile.startsWith('..') ? fromFile : `./${fromFile}`;
|
|
678
|
+
if (ref.bundleRoot && entry.bundleRoot === ref.bundleRoot) {
|
|
679
|
+
return toPosix(path.relative(ref.bundleRoot, entry.absolute));
|
|
680
|
+
}
|
|
681
|
+
return fromFile;
|
|
682
|
+
}
|
|
683
|
+
/** Filename without its extension, lowercased. */
|
|
684
|
+
function stem(name) {
|
|
685
|
+
const extension = path.posix.extname(name);
|
|
686
|
+
return (extension ? name.slice(0, -extension.length) : name).toLowerCase();
|
|
687
|
+
}
|
|
688
|
+
/**
|
|
689
|
+
* 0..1 over two filename stems.
|
|
690
|
+
*
|
|
691
|
+
* Three views, each of which catches renames the others miss, and the best of
|
|
692
|
+
* them wins. Averaging them instead would be worse than any one alone: a
|
|
693
|
+
* one-character typo scores 0.9 on edit distance and 0 on token overlap --
|
|
694
|
+
* filenames are usually a single token -- and blending those into 0.55 buries
|
|
695
|
+
* the likeliest fix there is.
|
|
696
|
+
*
|
|
697
|
+
* distance `conventions` -> `convetions`, a typo
|
|
698
|
+
* tokens `pull-requests` -> `requests-pull`, reordered
|
|
699
|
+
* containment `checklist` -> `audit-checklist`, qualified
|
|
700
|
+
*/
|
|
701
|
+
export function similarity(a, b) {
|
|
702
|
+
if (a === b)
|
|
703
|
+
return 1;
|
|
704
|
+
if (!a || !b)
|
|
705
|
+
return 0;
|
|
706
|
+
const byDistance = 1 - levenshtein(a, b) / Math.max(a.length, b.length);
|
|
707
|
+
const left = new Set(tokens(a));
|
|
708
|
+
const right = new Set(tokens(b));
|
|
709
|
+
const shared = [...left].filter((token) => right.has(token)).length;
|
|
710
|
+
const union = new Set([...left, ...right]).size;
|
|
711
|
+
const byTokens = union === 0 ? 0 : shared / union;
|
|
712
|
+
// Capped below an outright match, so a name that merely contains the other
|
|
713
|
+
// never beats the file actually called that.
|
|
714
|
+
const byContainment = a.includes(b) || b.includes(a) ? 0.75 : 0;
|
|
715
|
+
return Math.max(byDistance, byTokens, byContainment);
|
|
716
|
+
}
|
|
717
|
+
function tokens(value) {
|
|
718
|
+
return value.split(/[-_.\s/]+/).filter(Boolean);
|
|
719
|
+
}
|
|
720
|
+
function levenshtein(a, b) {
|
|
721
|
+
// One row at a time: these are filenames, but the index can be large.
|
|
722
|
+
let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
|
|
723
|
+
for (let i = 1; i <= a.length; i += 1) {
|
|
724
|
+
const current = [i];
|
|
725
|
+
for (let j = 1; j <= b.length; j += 1) {
|
|
726
|
+
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
|
|
727
|
+
current[j] = Math.min(current[j - 1] + 1, previous[j] + 1, previous[j - 1] + cost);
|
|
728
|
+
}
|
|
729
|
+
previous = current;
|
|
730
|
+
}
|
|
731
|
+
return previous[b.length];
|
|
732
|
+
}
|
|
733
|
+
/**
|
|
734
|
+
* Rewrite references in place.
|
|
735
|
+
*
|
|
736
|
+
* The offsets recorded at scan time are checked against what is on disk before
|
|
737
|
+
* anything is written -- the file may well have been edited while the JSON was
|
|
738
|
+
* open -- and fall back to a unique-occurrence search when they no longer line
|
|
739
|
+
* up. An occurrence that cannot be pinned down exactly is left alone and
|
|
740
|
+
* reported rather than guessed at.
|
|
741
|
+
*/
|
|
742
|
+
export async function applyRefEdits(edits, options = {}) {
|
|
743
|
+
const byFile = new Map();
|
|
744
|
+
for (const edit of edits) {
|
|
745
|
+
const list = byFile.get(edit.file) ?? [];
|
|
746
|
+
list.push(edit);
|
|
747
|
+
byFile.set(edit.file, list);
|
|
748
|
+
}
|
|
749
|
+
const outcomes = [];
|
|
750
|
+
for (const [file, fileEdits] of byFile) {
|
|
751
|
+
const text = await fs.readFile(file, 'utf8').catch(() => undefined);
|
|
752
|
+
if (text === undefined) {
|
|
753
|
+
for (const edit of fileEdits) {
|
|
754
|
+
outcomes.push({ ...describe(edit), applied: false, reason: 'file could not be read' });
|
|
755
|
+
}
|
|
756
|
+
continue;
|
|
757
|
+
}
|
|
758
|
+
const resolved = [];
|
|
759
|
+
for (const edit of fileEdits) {
|
|
760
|
+
const at = locate(text, edit);
|
|
761
|
+
if (at === undefined) {
|
|
762
|
+
outcomes.push({
|
|
763
|
+
...describe(edit),
|
|
764
|
+
applied: false,
|
|
765
|
+
reason: `"${edit.original}" no longer appears exactly once at that place`,
|
|
766
|
+
});
|
|
767
|
+
continue;
|
|
768
|
+
}
|
|
769
|
+
resolved.push({ edit, ...at });
|
|
770
|
+
}
|
|
771
|
+
if (resolved.length === 0)
|
|
772
|
+
continue;
|
|
773
|
+
// Back to front, so an earlier replacement cannot move a later offset.
|
|
774
|
+
let updated = text;
|
|
775
|
+
for (const item of resolved.sort((a, b) => b.start - a.start)) {
|
|
776
|
+
updated = updated.slice(0, item.start) + item.edit.replacement + updated.slice(item.end);
|
|
777
|
+
outcomes.push({ ...describe(item.edit), applied: true });
|
|
778
|
+
}
|
|
779
|
+
if (!options.dryRun && updated !== text)
|
|
780
|
+
await fs.writeFile(file, updated, 'utf8');
|
|
781
|
+
}
|
|
782
|
+
return outcomes;
|
|
783
|
+
}
|
|
784
|
+
function describe(edit) {
|
|
785
|
+
return { file: edit.file, original: edit.original, replacement: edit.replacement };
|
|
786
|
+
}
|
|
787
|
+
function locate(text, edit) {
|
|
788
|
+
const { original, start, end } = edit;
|
|
789
|
+
if (start !== undefined && end !== undefined && text.slice(start, end) === original) {
|
|
790
|
+
return { start, end };
|
|
791
|
+
}
|
|
792
|
+
const first = text.indexOf(original);
|
|
793
|
+
if (first === -1)
|
|
794
|
+
return undefined;
|
|
795
|
+
// Ambiguous without offsets: two identical references in one file, and no way
|
|
796
|
+
// to tell which one the entry meant.
|
|
797
|
+
if (text.indexOf(original, first + 1) !== -1)
|
|
798
|
+
return undefined;
|
|
799
|
+
return { start: first, end: first + original.length };
|
|
800
|
+
}
|
|
801
|
+
//# sourceMappingURL=refs.js.map
|