buddy-agent-harness 0.18.0 → 0.20.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/.claude-plugin/plugin.json +3 -2
- package/.codex-plugin/plugin.json +1 -1
- package/.cursor-plugin/plugin.json +1 -1
- package/README.md +2 -0
- package/dist/cli.mjs +11747 -11505
- package/dist/index.d.mts +22 -147
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +623 -1212
- package/dist/index.mjs.map +1 -1
- package/dist/skill-scripts/doctor.mjs +185 -183
- package/dist/skill-scripts/init.mjs +185 -183
- package/dist/skill-scripts/mcp.mjs +185 -183
- package/llms.txt +7 -9
- package/package.json +3 -3
- package/plugin.json +2 -1
- package/skills/doctor-buddy-agent-harness/SKILL.md +1 -1
- package/skills/doctor-buddy-agent-harness/references/global-instructions.md +4 -1
- package/skills/doctor-buddy-agent-harness/references/harnesses/claude-code.md +1 -1
- package/skills/doctor-buddy-agent-harness/references/harnesses/codex.md +1 -1
- package/skills/doctor-buddy-agent-harness/references/harnesses/copilot-cli.md +1 -1
- package/skills/doctor-buddy-agent-harness/scripts/doctor.mjs +185 -183
- package/skills/enhance/SKILL.md +2 -1
- package/skills/enhance/scripts/doctor.mjs +185 -183
- package/skills/init-buddy-agent-harness/SKILL.md +1 -1
- package/skills/init-buddy-agent-harness/scripts/doctor.mjs +185 -183
- package/skills/init-buddy-agent-harness/scripts/init.mjs +185 -183
- package/skills/repair/SKILL.md +2 -2
- package/skills/repair/scripts/doctor.mjs +185 -183
- package/skills/repair/scripts/mcp.mjs +185 -183
- package/src/cli.ts +1 -1
- package/src/dep-plugins/dep-plugins.ts +1 -15
- package/src/dep-plugins/resolve.ts +3 -31
- package/src/diagnose-bridges/diagnose-bridges.ts +1 -1
- package/src/diagnose-bridges/diagnose-global-instructions.ts +29 -11
- package/src/diagnose-bridges/doctor-guidance.ts +25 -2
- package/src/diagnose-bridges/doctor.command.ts +2 -2
- package/src/governance-overrides/governance-overrides.ts +6 -6
- package/src/harness-registry/harness-registry.ts +7 -0
- package/src/index.ts +29 -20
- package/src/initialize-harnesses/init.command.ts +1 -1
- package/src/initialize-harnesses/initialize-harnesses.ts +1 -2
- package/src/references/references.ts +28 -0
- package/src/skill-scripts/launchers.ts +0 -1
- package/dist/skill-scripts/reference.mjs +0 -486
- package/skills/reference/README.md +0 -53
- package/skills/reference/SKILL.md +0 -82
- package/skills/reference/references/create.md +0 -67
- package/skills/reference/references/load.md +0 -59
- package/skills/reference/scripts/reference.mjs +0 -486
- package/src/references/create-reference.ts +0 -57
- package/src/references/harness-layers.ts +0 -150
- package/src/references/reference-catalog.ts +0 -130
- package/src/references/reference-document.ts +0 -226
- package/src/references/reference-invocation.ts +0 -25
- package/src/references/reference-layers.ts +0 -171
- package/src/references/reference.command.ts +0 -487
- package/src/references/resolve-reference.ts +0 -258
- package/src/skill-scripts/reference.ts +0 -7
package/dist/index.mjs
CHANGED
|
@@ -1,16 +1,562 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { declaredDependencies, deprecatedManagedGovernancesDir as deprecatedManagedGovernancesDir$1, listReferences, listReferences as listReferences$1, managedGovernancesDir as managedGovernancesDir$1, managedReferencesDir, packageDir, parseReferenceName, projectReferenceLayers, projectReferencesDir, referenceLayers as referenceLayers$1, referenceNames, resolveReference, searchReferences, skillsDirectories } from "@cyberuni/agent-harness";
|
|
2
2
|
import { cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, readlinkSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
|
|
3
3
|
import { cli, command, exitCodes, z } from "clibuilder";
|
|
4
4
|
import { homedir, platform } from "node:os";
|
|
5
|
-
import { basename, dirname, join, posix, relative, resolve, sep
|
|
6
|
-
import { encode } from "@toon-format/toon";
|
|
7
|
-
import { detectHarness, enabledPlugins, installedPlugins, managedPolicyLocations, skillsDirectories } from "@cyberuni/agent-harness";
|
|
5
|
+
import { basename, dirname, join, posix, relative, resolve, sep } from "node:path";
|
|
8
6
|
import { parse, stringify } from "smol-toml";
|
|
9
|
-
import {
|
|
7
|
+
import { createReferenceCommand } from "@cyberuni/agent-harness/commands";
|
|
10
8
|
import { fileURLToPath } from "node:url";
|
|
11
9
|
import { execFileSync } from "node:child_process";
|
|
12
10
|
import { parseTOML } from "toml-eslint-parser";
|
|
13
11
|
import { findNodeAtLocation, parseTree } from "jsonc-parser";
|
|
12
|
+
//#region ../../node_modules/.pnpm/@toon-format+toon@4.1.1/node_modules/@toon-format/toon/dist/index.mjs
|
|
13
|
+
const NULL_LITERAL = "null";
|
|
14
|
+
const DELIMITERS = {
|
|
15
|
+
comma: ",",
|
|
16
|
+
tab: " ",
|
|
17
|
+
pipe: "|"
|
|
18
|
+
};
|
|
19
|
+
const DEFAULT_DELIMITER = DELIMITERS.comma;
|
|
20
|
+
/**
|
|
21
|
+
* Escapes special characters in a string for encoding.
|
|
22
|
+
*
|
|
23
|
+
* @remarks
|
|
24
|
+
* Control characters outside `\n`, `\r`, `\t`, `\\`, and `"` are emitted as `\uXXXX`.
|
|
25
|
+
*/
|
|
26
|
+
function escapeString(value) {
|
|
27
|
+
return value.replace(/\\/g, `\\\\`).replace(/"/g, `\\"`).replace(/\n/g, `\\n`).replace(/\r/g, `\\r`).replace(/\t/g, `\\t`).replace(/[\u0000-\u001F]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
|
|
28
|
+
}
|
|
29
|
+
function isBooleanOrNullLiteral(token) {
|
|
30
|
+
return token === "true" || token === "false" || token === "null";
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Assigns an own data property without invoking inherited accessors.
|
|
34
|
+
*
|
|
35
|
+
* @remarks
|
|
36
|
+
* Plain assignment of `__proto__` would hit the `Object.prototype` setter and
|
|
37
|
+
* corrupt the prototype chain; `defineProperty` avoids that but is markedly
|
|
38
|
+
* slower, so every other key takes plain assignment.
|
|
39
|
+
*/
|
|
40
|
+
function setOwnProperty(target, key, value) {
|
|
41
|
+
if (key === "__proto__") {
|
|
42
|
+
Object.defineProperty(target, key, {
|
|
43
|
+
value,
|
|
44
|
+
enumerable: true,
|
|
45
|
+
writable: true,
|
|
46
|
+
configurable: true
|
|
47
|
+
});
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
target[key] = value;
|
|
51
|
+
}
|
|
52
|
+
const COMMENT_LINE_PATTERN = new RegExp(`(?:^?|\\n) *#`);
|
|
53
|
+
/**
|
|
54
|
+
* Pre-formatted string that the encoder emits verbatim at a primitive value
|
|
55
|
+
* position, bypassing quoting, escaping, and number/keyword detection.
|
|
56
|
+
*
|
|
57
|
+
* Returned from a replacer for an object or array value, it is ignored and
|
|
58
|
+
* the container is encoded normally.
|
|
59
|
+
*/
|
|
60
|
+
var RawString = class {
|
|
61
|
+
constructor(value) {
|
|
62
|
+
if (COMMENT_LINE_PATTERN.test(value)) throw new TypeError(`Raw string must not contain a line starting with "#": ${JSON.stringify(value)}`);
|
|
63
|
+
this.value = value;
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
function isRawString(value) {
|
|
67
|
+
return value instanceof RawString;
|
|
68
|
+
}
|
|
69
|
+
const SURROGATE_PATTERN = /[\uD800-\uDFFF]/;
|
|
70
|
+
function normalizeValue(value) {
|
|
71
|
+
if (value === null) return null;
|
|
72
|
+
if (isRawString(value)) return value;
|
|
73
|
+
if (typeof value === "object" && value !== null && "toJSON" in value && typeof value.toJSON === "function") {
|
|
74
|
+
const next = value.toJSON();
|
|
75
|
+
if (next !== value) return normalizeValue(next);
|
|
76
|
+
}
|
|
77
|
+
if (typeof value === "string") {
|
|
78
|
+
assertNoLoneSurrogate(value, "string value");
|
|
79
|
+
return value;
|
|
80
|
+
}
|
|
81
|
+
if (typeof value === "boolean") return value;
|
|
82
|
+
if (typeof value === "number") {
|
|
83
|
+
if (Object.is(value, -0)) return 0;
|
|
84
|
+
if (!Number.isFinite(value)) return null;
|
|
85
|
+
return value;
|
|
86
|
+
}
|
|
87
|
+
if (typeof value === "bigint") {
|
|
88
|
+
if (value >= Number.MIN_SAFE_INTEGER && value <= Number.MAX_SAFE_INTEGER) return Number(value);
|
|
89
|
+
return value.toString();
|
|
90
|
+
}
|
|
91
|
+
if (value instanceof Date) return value.toISOString();
|
|
92
|
+
if (Array.isArray(value)) return value.map(normalizeValue);
|
|
93
|
+
if (value instanceof Set) return Array.from(value).map(normalizeValue);
|
|
94
|
+
if (value instanceof Map) return Object.fromEntries(Array.from(value, ([k, v]) => [String(k), normalizeValue(v)]));
|
|
95
|
+
if (isPlainObject(value)) {
|
|
96
|
+
const encodedValues = {};
|
|
97
|
+
for (const key in value) if (Object.hasOwn(value, key)) {
|
|
98
|
+
assertNoLoneSurrogate(key, "object key");
|
|
99
|
+
setOwnProperty(encodedValues, key, normalizeValue(value[key]));
|
|
100
|
+
}
|
|
101
|
+
return encodedValues;
|
|
102
|
+
}
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
function assertNoLoneSurrogate(value, context) {
|
|
106
|
+
if (!SURROGATE_PATTERN.test(value)) return;
|
|
107
|
+
for (let index = 0; index < value.length; index++) {
|
|
108
|
+
const code = value.charCodeAt(index);
|
|
109
|
+
if (code < 55296 || code > 57343) continue;
|
|
110
|
+
const isHighSurrogate = code <= 56319;
|
|
111
|
+
const next = value.charCodeAt(index + 1);
|
|
112
|
+
if (isHighSurrogate && next >= 56320 && next <= 57343) {
|
|
113
|
+
index++;
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
throw new TypeError(`Cannot encode ${context} containing an unpaired surrogate U+${code.toString(16).toUpperCase()} at index ${index}`);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
function isJsonPrimitive(value) {
|
|
120
|
+
return value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
|
|
121
|
+
}
|
|
122
|
+
function isEncodablePrimitive(value) {
|
|
123
|
+
return isJsonPrimitive(value) || isRawString(value);
|
|
124
|
+
}
|
|
125
|
+
function isJsonArray(value) {
|
|
126
|
+
return Array.isArray(value);
|
|
127
|
+
}
|
|
128
|
+
function isJsonObject(value) {
|
|
129
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) && !isRawString(value);
|
|
130
|
+
}
|
|
131
|
+
function isEmptyObject(value) {
|
|
132
|
+
return Object.keys(value).length === 0;
|
|
133
|
+
}
|
|
134
|
+
function isPlainObject(value) {
|
|
135
|
+
if (value === null || typeof value !== "object") return false;
|
|
136
|
+
const prototype = Object.getPrototypeOf(value);
|
|
137
|
+
return prototype === null || prototype === Object.prototype;
|
|
138
|
+
}
|
|
139
|
+
function isArrayOfPrimitives(value) {
|
|
140
|
+
return value.length === 0 || value.every((item) => isEncodablePrimitive(item));
|
|
141
|
+
}
|
|
142
|
+
function isArrayOfArrays(value) {
|
|
143
|
+
return value.length === 0 || value.every((item) => isJsonArray(item));
|
|
144
|
+
}
|
|
145
|
+
function isArrayOfObjects(value) {
|
|
146
|
+
return value.length === 0 || value.every((item) => isJsonObject(item));
|
|
147
|
+
}
|
|
148
|
+
const NUMERIC_LIKE_PATTERN = /^[+-]?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i;
|
|
149
|
+
/** Narrows an arbitrary delimiter option, shared by the library and the CLI so both report it alike. */
|
|
150
|
+
function assertValidDelimiter(delimiter) {
|
|
151
|
+
if (!Object.values(DELIMITERS).includes(delimiter)) throw new TypeError(`Invalid delimiter ${JSON.stringify(delimiter)}. Valid delimiters are: comma (,), tab (\\t), pipe (|)`);
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Checks if a key can be used without quotes.
|
|
155
|
+
*
|
|
156
|
+
* @remarks
|
|
157
|
+
* Valid unquoted keys must start with a letter or underscore,
|
|
158
|
+
* followed by letters, digits, underscores, or dots.
|
|
159
|
+
*/
|
|
160
|
+
function isValidUnquotedKey(key) {
|
|
161
|
+
return /^[A-Z_][\w.]*$/i.test(key);
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Determines if a string value can be safely encoded without quotes.
|
|
165
|
+
*
|
|
166
|
+
* @remarks
|
|
167
|
+
* A string needs quoting if it:
|
|
168
|
+
* - Is empty
|
|
169
|
+
* - Has leading or trailing whitespace
|
|
170
|
+
* - Could be confused with a literal (boolean, null, number)
|
|
171
|
+
* - Contains structural characters (colons, brackets, braces)
|
|
172
|
+
* - Contains quotes or backslashes (need escaping)
|
|
173
|
+
* - Contains control characters (newlines, tabs, etc.)
|
|
174
|
+
* - Contains the active delimiter
|
|
175
|
+
* - Starts with a list marker (hyphen)
|
|
176
|
+
* - Starts with a comment marker (#)
|
|
177
|
+
*/
|
|
178
|
+
function isSafeUnquoted(value, delimiter = DEFAULT_DELIMITER) {
|
|
179
|
+
if (!value) return false;
|
|
180
|
+
if (/^[ \t]|[ \t]$/.test(value)) return false;
|
|
181
|
+
if (isBooleanOrNullLiteral(value) || isNumericLike(value)) return false;
|
|
182
|
+
if (value.includes(":")) return false;
|
|
183
|
+
if (value.includes("\"") || value.includes("\\")) return false;
|
|
184
|
+
if (/[[\]{}]/.test(value)) return false;
|
|
185
|
+
if (/[\u0000-\u001F]/.test(value)) return false;
|
|
186
|
+
if (value.includes(delimiter)) return false;
|
|
187
|
+
if (value.startsWith("-")) return false;
|
|
188
|
+
if (value.startsWith("#")) return false;
|
|
189
|
+
return true;
|
|
190
|
+
}
|
|
191
|
+
function isNumericLike(value) {
|
|
192
|
+
return NUMERIC_LIKE_PATTERN.test(value);
|
|
193
|
+
}
|
|
194
|
+
function encodePrimitive(value, delimiter) {
|
|
195
|
+
if (isRawString(value)) return value.value;
|
|
196
|
+
if (value === null) return NULL_LITERAL;
|
|
197
|
+
if (typeof value === "boolean") return String(value);
|
|
198
|
+
if (typeof value === "number") return String(value);
|
|
199
|
+
return encodeStringLiteral(value, delimiter);
|
|
200
|
+
}
|
|
201
|
+
function encodeStringLiteral(value, delimiter = DEFAULT_DELIMITER) {
|
|
202
|
+
if (isSafeUnquoted(value, delimiter)) return value;
|
|
203
|
+
return `"${escapeString(value)}"`;
|
|
204
|
+
}
|
|
205
|
+
function encodeKey(key) {
|
|
206
|
+
if (isValidUnquotedKey(key)) return key;
|
|
207
|
+
return `"${escapeString(key)}"`;
|
|
208
|
+
}
|
|
209
|
+
function encodeAndJoinPrimitives(values, delimiter = DEFAULT_DELIMITER) {
|
|
210
|
+
return values.map((v) => encodePrimitive(v, delimiter)).join(delimiter);
|
|
211
|
+
}
|
|
212
|
+
function formatHeader(length, options) {
|
|
213
|
+
const key = options?.key;
|
|
214
|
+
const fields = options?.fields;
|
|
215
|
+
const delimiter = options?.delimiter ?? ",";
|
|
216
|
+
let header = "";
|
|
217
|
+
if (key != null) header += encodeKey(key);
|
|
218
|
+
header += `[${length}${options?.keyed ? ":" : ""}${delimiter !== DEFAULT_DELIMITER ? delimiter : ""}]`;
|
|
219
|
+
if (fields) header += `{${formatFieldSegment(fields, delimiter)}}`;
|
|
220
|
+
header += ":";
|
|
221
|
+
return header;
|
|
222
|
+
}
|
|
223
|
+
function formatFieldSegment(fields, delimiter) {
|
|
224
|
+
return fields.map((field) => encodeKey(field.name) + (field.children ? `{${formatFieldSegment(field.children, delimiter)}}` : "")).join(delimiter);
|
|
225
|
+
}
|
|
226
|
+
/** Classifies rows into a tabular field list, or undefined when they are not uniformly tabular. */
|
|
227
|
+
function extractTabularFields(rows) {
|
|
228
|
+
if (rows.length === 0) return;
|
|
229
|
+
const firstKeys = Object.keys(rows[0]);
|
|
230
|
+
if (firstKeys.length === 0) return;
|
|
231
|
+
for (const row of rows) {
|
|
232
|
+
if (Object.keys(row).length !== firstKeys.length) return;
|
|
233
|
+
for (const key of firstKeys) if (!Object.hasOwn(row, key)) return;
|
|
234
|
+
}
|
|
235
|
+
const fieldNodes = [];
|
|
236
|
+
for (const key of firstKeys) {
|
|
237
|
+
const fieldNode = classifyColumn(key, rows.map((row) => row[key]));
|
|
238
|
+
if (!fieldNode) return;
|
|
239
|
+
fieldNodes.push(fieldNode);
|
|
240
|
+
}
|
|
241
|
+
return fieldNodes;
|
|
242
|
+
}
|
|
243
|
+
/** Classifies an object's values as a keyed tabular field list (>=2 uniform non-empty object entries), or undefined. */
|
|
244
|
+
function extractKeyedTabularFields(value) {
|
|
245
|
+
const entryValues = Object.values(value);
|
|
246
|
+
if (entryValues.length < 2) return;
|
|
247
|
+
if (!entryValues.every((entryValue) => isJsonObject(entryValue) && !isEmptyObject(entryValue))) return;
|
|
248
|
+
return extractTabularFields(entryValues);
|
|
249
|
+
}
|
|
250
|
+
/** Reads one row's leaf cells in the field order `extractTabularFields` produced. */
|
|
251
|
+
function collectRowLeaves(row, fields) {
|
|
252
|
+
const leaves = [];
|
|
253
|
+
collectLeafValues(row, fields, leaves);
|
|
254
|
+
return leaves;
|
|
255
|
+
}
|
|
256
|
+
function classifyColumn(name, values) {
|
|
257
|
+
if (values.every((value) => isEncodablePrimitive(value))) return { name };
|
|
258
|
+
if (!values.every((value) => isJsonObject(value) && !isEmptyObject(value))) return;
|
|
259
|
+
const children = extractTabularFields(values);
|
|
260
|
+
if (!children) return;
|
|
261
|
+
return {
|
|
262
|
+
name,
|
|
263
|
+
children
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
function collectLeafValues(row, fields, leaves) {
|
|
267
|
+
for (const field of fields) {
|
|
268
|
+
const value = row[field.name];
|
|
269
|
+
if (field.children) collectLeafValues(value, field.children, leaves);
|
|
270
|
+
else leaves.push(value);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
function* encodeJsonValue(value, options, depth) {
|
|
274
|
+
if (isEncodablePrimitive(value)) {
|
|
275
|
+
const encodedPrimitive = encodePrimitive(value, options.delimiter);
|
|
276
|
+
if (encodedPrimitive !== "") yield encodedPrimitive;
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
if (isJsonArray(value)) yield* encodeArrayLines(void 0, value, depth, options);
|
|
280
|
+
else if (isJsonObject(value)) {
|
|
281
|
+
const keyedFields = extractKeyedTabularFields(value);
|
|
282
|
+
if (keyedFields) {
|
|
283
|
+
yield* encodeKeyedObjectLines(void 0, value, keyedFields, depth, options);
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
yield* encodeObjectLines(value, depth, options);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
function* encodeObjectLines(value, depth, options) {
|
|
290
|
+
for (const [key, val] of Object.entries(value)) yield* encodeKeyValuePairLines(key, val, depth, options);
|
|
291
|
+
}
|
|
292
|
+
function* encodeKeyValuePairLines(key, value, depth, options) {
|
|
293
|
+
const encodedKey = encodeKey(key);
|
|
294
|
+
if (isEncodablePrimitive(value)) yield indentedLine(depth, `${encodedKey}: ${encodePrimitive(value, options.delimiter)}`, options.indentSize);
|
|
295
|
+
else if (isJsonArray(value)) yield* encodeArrayLines(key, value, depth, options);
|
|
296
|
+
else if (isJsonObject(value)) {
|
|
297
|
+
const keyedFields = extractKeyedTabularFields(value);
|
|
298
|
+
if (keyedFields) {
|
|
299
|
+
yield* encodeKeyedObjectLines(key, value, keyedFields, depth, options);
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
yield indentedLine(depth, `${encodedKey}:`, options.indentSize);
|
|
303
|
+
if (!isEmptyObject(value)) yield* encodeObjectLines(value, depth + 1, options);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
function* encodeKeyedObjectLines(key, value, fields, depth, options) {
|
|
307
|
+
const entries = Object.entries(value);
|
|
308
|
+
yield indentedLine(depth, formatHeader(entries.length, {
|
|
309
|
+
key,
|
|
310
|
+
fields,
|
|
311
|
+
delimiter: options.delimiter,
|
|
312
|
+
keyed: true
|
|
313
|
+
}), options.indentSize);
|
|
314
|
+
yield* encodeKeyedEntryRowsLines(entries, fields, depth + 1, options);
|
|
315
|
+
}
|
|
316
|
+
function* encodeKeyedEntryRowsLines(entries, fields, depth, options) {
|
|
317
|
+
for (const [entryKey, entryValue] of entries) {
|
|
318
|
+
const leaves = collectRowLeaves(entryValue, fields);
|
|
319
|
+
yield indentedLine(depth, `${encodeKey(entryKey)}: ${encodeAndJoinPrimitives(leaves, options.delimiter)}`, options.indentSize);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
function* encodeArrayLines(key, value, depth, options) {
|
|
323
|
+
if (value.length === 0) {
|
|
324
|
+
yield indentedLine(depth, key != null ? `${encodeKey(key)}: []` : "[]", options.indentSize);
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
if (isArrayOfPrimitives(value)) {
|
|
328
|
+
yield indentedLine(depth, encodeInlineArrayLine(value, options.delimiter, key), options.indentSize);
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
if (isArrayOfArrays(value)) {
|
|
332
|
+
if (value.every((arr) => isArrayOfPrimitives(arr))) {
|
|
333
|
+
yield* encodeArrayOfArraysAsListItemsLines(key, value, depth, options);
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
if (isArrayOfObjects(value)) {
|
|
338
|
+
const fields = extractTabularFields(value);
|
|
339
|
+
if (fields) yield* encodeArrayOfObjectsAsTabularLines(key, value, fields, depth, options);
|
|
340
|
+
else yield* encodeMixedArrayAsListItemsLines(key, value, depth, options);
|
|
341
|
+
return;
|
|
342
|
+
}
|
|
343
|
+
yield* encodeMixedArrayAsListItemsLines(key, value, depth, options);
|
|
344
|
+
}
|
|
345
|
+
function* encodeArrayOfArraysAsListItemsLines(prefix, values, depth, options) {
|
|
346
|
+
yield indentedLine(depth, formatHeader(values.length, {
|
|
347
|
+
key: prefix,
|
|
348
|
+
delimiter: options.delimiter
|
|
349
|
+
}), options.indentSize);
|
|
350
|
+
for (const arr of values) if (isArrayOfPrimitives(arr)) {
|
|
351
|
+
const arrayLine = encodeInlineArrayLine(arr, options.delimiter);
|
|
352
|
+
yield indentedListItem(depth + 1, arrayLine, options.indentSize);
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
function encodeInlineArrayLine(values, delimiter, prefix) {
|
|
356
|
+
const header = formatHeader(values.length, {
|
|
357
|
+
key: prefix,
|
|
358
|
+
delimiter
|
|
359
|
+
});
|
|
360
|
+
const joinedValue = encodeAndJoinPrimitives(values, delimiter);
|
|
361
|
+
if (values.length === 0) return header;
|
|
362
|
+
return `${header} ${joinedValue}`;
|
|
363
|
+
}
|
|
364
|
+
function* encodeArrayOfObjectsAsTabularLines(prefix, rows, fields, depth, options) {
|
|
365
|
+
yield indentedLine(depth, formatHeader(rows.length, {
|
|
366
|
+
key: prefix,
|
|
367
|
+
fields,
|
|
368
|
+
delimiter: options.delimiter
|
|
369
|
+
}), options.indentSize);
|
|
370
|
+
yield* writeTabularRowsLines(rows, fields, depth + 1, options);
|
|
371
|
+
}
|
|
372
|
+
function* writeTabularRowsLines(rows, fields, depth, options) {
|
|
373
|
+
for (const row of rows) yield indentedLine(depth, encodeAndJoinPrimitives(collectRowLeaves(row, fields), options.delimiter), options.indentSize);
|
|
374
|
+
}
|
|
375
|
+
function* encodeMixedArrayAsListItemsLines(prefix, items, depth, options) {
|
|
376
|
+
yield indentedLine(depth, formatHeader(items.length, {
|
|
377
|
+
key: prefix,
|
|
378
|
+
delimiter: options.delimiter
|
|
379
|
+
}), options.indentSize);
|
|
380
|
+
for (const item of items) yield* encodeListItemValueLines(item, depth + 1, options);
|
|
381
|
+
}
|
|
382
|
+
function* encodeObjectAsListItemLines(obj, depth, options) {
|
|
383
|
+
if (isEmptyObject(obj)) {
|
|
384
|
+
yield indentedLine(depth, "-", options.indentSize);
|
|
385
|
+
return;
|
|
386
|
+
}
|
|
387
|
+
const entries = Object.entries(obj);
|
|
388
|
+
const [firstKey, firstValue] = entries[0];
|
|
389
|
+
const restEntries = entries.slice(1);
|
|
390
|
+
if (isJsonArray(firstValue) && isArrayOfObjects(firstValue)) {
|
|
391
|
+
const fields = extractTabularFields(firstValue);
|
|
392
|
+
if (fields) {
|
|
393
|
+
yield indentedListItem(depth, formatHeader(firstValue.length, {
|
|
394
|
+
key: firstKey,
|
|
395
|
+
fields,
|
|
396
|
+
delimiter: options.delimiter
|
|
397
|
+
}), options.indentSize);
|
|
398
|
+
yield* writeTabularRowsLines(firstValue, fields, depth + 2, options);
|
|
399
|
+
if (restEntries.length > 0) yield* encodeObjectLines(Object.fromEntries(restEntries), depth + 1, options);
|
|
400
|
+
return;
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
if (isJsonObject(firstValue)) {
|
|
404
|
+
const keyedFields = extractKeyedTabularFields(firstValue);
|
|
405
|
+
if (keyedFields) {
|
|
406
|
+
const keyedEntries = Object.entries(firstValue);
|
|
407
|
+
yield indentedListItem(depth, formatHeader(keyedEntries.length, {
|
|
408
|
+
key: firstKey,
|
|
409
|
+
fields: keyedFields,
|
|
410
|
+
delimiter: options.delimiter,
|
|
411
|
+
keyed: true
|
|
412
|
+
}), options.indentSize);
|
|
413
|
+
yield* encodeKeyedEntryRowsLines(keyedEntries, keyedFields, depth + 2, options);
|
|
414
|
+
if (restEntries.length > 0) yield* encodeObjectLines(Object.fromEntries(restEntries), depth + 1, options);
|
|
415
|
+
return;
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
const encodedKey = encodeKey(firstKey);
|
|
419
|
+
if (isEncodablePrimitive(firstValue)) yield indentedListItem(depth, `${encodedKey}: ${encodePrimitive(firstValue, options.delimiter)}`, options.indentSize);
|
|
420
|
+
else if (isJsonArray(firstValue)) if (firstValue.length === 0) yield indentedListItem(depth, `${encodedKey}: []`, options.indentSize);
|
|
421
|
+
else if (isArrayOfPrimitives(firstValue)) yield indentedListItem(depth, `${encodedKey}${encodeInlineArrayLine(firstValue, options.delimiter)}`, options.indentSize);
|
|
422
|
+
else {
|
|
423
|
+
yield indentedListItem(depth, `${encodedKey}${formatHeader(firstValue.length, { delimiter: options.delimiter })}`, options.indentSize);
|
|
424
|
+
for (const item of firstValue) yield* encodeListItemValueLines(item, depth + 2, options);
|
|
425
|
+
}
|
|
426
|
+
else if (isJsonObject(firstValue)) {
|
|
427
|
+
yield indentedListItem(depth, `${encodedKey}:`, options.indentSize);
|
|
428
|
+
if (!isEmptyObject(firstValue)) yield* encodeObjectLines(firstValue, depth + 2, options);
|
|
429
|
+
}
|
|
430
|
+
if (restEntries.length > 0) yield* encodeObjectLines(Object.fromEntries(restEntries), depth + 1, options);
|
|
431
|
+
}
|
|
432
|
+
function* encodeListItemValueLines(value, depth, options) {
|
|
433
|
+
if (isEncodablePrimitive(value)) yield indentedListItem(depth, encodePrimitive(value, options.delimiter), options.indentSize);
|
|
434
|
+
else if (isJsonArray(value)) if (isArrayOfPrimitives(value)) yield indentedListItem(depth, encodeInlineArrayLine(value, options.delimiter), options.indentSize);
|
|
435
|
+
else {
|
|
436
|
+
yield indentedListItem(depth, formatHeader(value.length, { delimiter: options.delimiter }), options.indentSize);
|
|
437
|
+
for (const item of value) yield* encodeListItemValueLines(item, depth + 1, options);
|
|
438
|
+
}
|
|
439
|
+
else if (isJsonObject(value)) yield* encodeObjectAsListItemLines(value, depth, options);
|
|
440
|
+
}
|
|
441
|
+
function indentedLine(depth, content, indentSize) {
|
|
442
|
+
return " ".repeat(indentSize * depth) + content;
|
|
443
|
+
}
|
|
444
|
+
function indentedListItem(depth, content, indentSize) {
|
|
445
|
+
return indentedLine(depth, "- " + content, indentSize);
|
|
446
|
+
}
|
|
447
|
+
/**
|
|
448
|
+
* Applies a replacer function to a `JsonValue` and all its descendants.
|
|
449
|
+
*
|
|
450
|
+
* The replacer is called for the root (key='', path=[]), every object property
|
|
451
|
+
* (key = property name), and every array element (key = string index).
|
|
452
|
+
*/
|
|
453
|
+
function applyReplacer(root, replacer) {
|
|
454
|
+
const replacedRoot = replacer("", root, []);
|
|
455
|
+
if (replacedRoot === void 0) return transformChildren(root, replacer, []);
|
|
456
|
+
return transformReplaced(root, replacedRoot, replacer, []);
|
|
457
|
+
}
|
|
458
|
+
/**
|
|
459
|
+
* Resolves a replacer's (non-`undefined`) return value at a single position.
|
|
460
|
+
*
|
|
461
|
+
* A `RawString` only stands in for a primitive: returned for an object or
|
|
462
|
+
* array value, it is ignored and the original container is traversed normally.
|
|
463
|
+
*/
|
|
464
|
+
function transformReplaced(original, replaced, replacer, path) {
|
|
465
|
+
if (isRawString(replaced) && !isEncodablePrimitive(original)) return transformChildren(original, replacer, path);
|
|
466
|
+
return transformChildren(normalizeValue(replaced), replacer, path);
|
|
467
|
+
}
|
|
468
|
+
function transformChildren(value, replacer, path) {
|
|
469
|
+
if (isJsonObject(value)) return transformObject(value, replacer, path);
|
|
470
|
+
if (isJsonArray(value)) return transformArray(value, replacer, path);
|
|
471
|
+
return value;
|
|
472
|
+
}
|
|
473
|
+
function transformObject(obj, replacer, path) {
|
|
474
|
+
const result = {};
|
|
475
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
476
|
+
const childPath = [...path, key];
|
|
477
|
+
const replacedValue = replacer(key, value, childPath);
|
|
478
|
+
if (replacedValue === void 0) continue;
|
|
479
|
+
setOwnProperty(result, key, transformReplaced(value, replacedValue, replacer, childPath));
|
|
480
|
+
}
|
|
481
|
+
return result;
|
|
482
|
+
}
|
|
483
|
+
function transformArray(arr, replacer, path) {
|
|
484
|
+
const result = [];
|
|
485
|
+
for (let i = 0; i < arr.length; i++) {
|
|
486
|
+
const value = arr[i];
|
|
487
|
+
const childPath = [...path, i];
|
|
488
|
+
const replacedValue = replacer(String(i), value, childPath);
|
|
489
|
+
if (replacedValue === void 0) continue;
|
|
490
|
+
result.push(transformReplaced(value, replacedValue, replacer, childPath));
|
|
491
|
+
}
|
|
492
|
+
return result;
|
|
493
|
+
}
|
|
494
|
+
/**
|
|
495
|
+
* Encodes a JavaScript value into TOON format string.
|
|
496
|
+
*
|
|
497
|
+
* @param input Any JavaScript value (objects, arrays, primitives)
|
|
498
|
+
* @param options Optional encoding configuration
|
|
499
|
+
* @returns TOON formatted string
|
|
500
|
+
*
|
|
501
|
+
* @example
|
|
502
|
+
* ```ts
|
|
503
|
+
* encode({ name: 'Ada', age: 30 })
|
|
504
|
+
* // name: Ada
|
|
505
|
+
* // age: 30
|
|
506
|
+
*
|
|
507
|
+
* encode({ users: [{ id: 1 }, { id: 2 }] })
|
|
508
|
+
* // users[2]{id}:
|
|
509
|
+
* // 1
|
|
510
|
+
* // 2
|
|
511
|
+
*
|
|
512
|
+
* encode({ tags: [] })
|
|
513
|
+
* // tags: []
|
|
514
|
+
*
|
|
515
|
+
* encode(data, { indentSize: 4 })
|
|
516
|
+
* ```
|
|
517
|
+
*/
|
|
518
|
+
function encode(input, options) {
|
|
519
|
+
return Array.from(encodeLines(input, options)).join("\n");
|
|
520
|
+
}
|
|
521
|
+
/**
|
|
522
|
+
* Encodes a JavaScript value into TOON format as a sequence of lines.
|
|
523
|
+
*
|
|
524
|
+
* This function yields TOON lines one at a time without building the full string,
|
|
525
|
+
* making it suitable for streaming large outputs to files, HTTP responses, or process stdout.
|
|
526
|
+
*
|
|
527
|
+
* @param input Any JavaScript value (objects, arrays, primitives)
|
|
528
|
+
* @param options Optional encoding configuration
|
|
529
|
+
* @returns Iterable of TOON lines (without trailing newlines)
|
|
530
|
+
*
|
|
531
|
+
* @example
|
|
532
|
+
* ```ts
|
|
533
|
+
* // Stream to stdout
|
|
534
|
+
* for (const line of encodeLines({ name: 'Ada', age: 30 })) {
|
|
535
|
+
* console.log(line)
|
|
536
|
+
* }
|
|
537
|
+
*
|
|
538
|
+
* // Collect to array
|
|
539
|
+
* const lines = Array.from(encodeLines(data))
|
|
540
|
+
*
|
|
541
|
+
* // Equivalent to encode()
|
|
542
|
+
* const toonString = Array.from(encodeLines(data, options)).join('\n')
|
|
543
|
+
* ```
|
|
544
|
+
*/
|
|
545
|
+
function encodeLines(input, options) {
|
|
546
|
+
const normalizedValue = normalizeValue(input);
|
|
547
|
+
const resolvedOptions = resolveOptions(options);
|
|
548
|
+
return encodeJsonValue(resolvedOptions.replacer ? applyReplacer(normalizedValue, resolvedOptions.replacer) : normalizedValue, resolvedOptions, 0);
|
|
549
|
+
}
|
|
550
|
+
function resolveOptions(options) {
|
|
551
|
+
const delimiter = options?.delimiter ?? DEFAULT_DELIMITER;
|
|
552
|
+
assertValidDelimiter(delimiter);
|
|
553
|
+
return {
|
|
554
|
+
indentSize: options?.indentSize ?? options?.indent ?? 2,
|
|
555
|
+
delimiter,
|
|
556
|
+
replacer: options?.replacer
|
|
557
|
+
};
|
|
558
|
+
}
|
|
559
|
+
//#endregion
|
|
14
560
|
//#region src/is-record/is-record.ts
|
|
15
561
|
function isRecord(value) {
|
|
16
562
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
@@ -97,21 +643,6 @@ function marketplaceName(packageName) {
|
|
|
97
643
|
return packageName.replace(/^@/, "").replace(/\//g, "-").replace(/[^a-zA-Z0-9-_.]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "") || "agent-plugins";
|
|
98
644
|
}
|
|
99
645
|
/**
|
|
100
|
-
* Includes `devDependencies` — a plugin can supply a project's testing or release workflow.
|
|
101
|
-
* Transitive dependencies are excluded; see `resolve.ts`.
|
|
102
|
-
*/
|
|
103
|
-
function declaredDependencies(manifest) {
|
|
104
|
-
if (!manifest || typeof manifest !== "object") return [];
|
|
105
|
-
const record = manifest;
|
|
106
|
-
const names = /* @__PURE__ */ new Set();
|
|
107
|
-
for (const field of ["dependencies", "devDependencies"]) {
|
|
108
|
-
const group = record[field];
|
|
109
|
-
if (!group || typeof group !== "object") continue;
|
|
110
|
-
for (const name of Object.keys(group)) names.add(name);
|
|
111
|
-
}
|
|
112
|
-
return [...names].sort();
|
|
113
|
-
}
|
|
114
|
-
/**
|
|
115
646
|
* Derived in full every run, never merged with what's on disk. Entries are sorted so unchanged
|
|
116
647
|
* inputs serialize identically, which `--check` relies on.
|
|
117
648
|
*/
|
|
@@ -144,36 +675,13 @@ function serializeCatalog(catalog) {
|
|
|
144
675
|
}
|
|
145
676
|
//#endregion
|
|
146
677
|
//#region src/dep-plugins/resolve.ts
|
|
147
|
-
function readJson$
|
|
678
|
+
function readJson$1(path) {
|
|
148
679
|
try {
|
|
149
680
|
return JSON.parse(readFileSync(path, "utf8"));
|
|
150
681
|
} catch {
|
|
151
682
|
return;
|
|
152
683
|
}
|
|
153
684
|
}
|
|
154
|
-
function ancestorCandidates(startDir, pkg) {
|
|
155
|
-
const segments = pkg.split("/");
|
|
156
|
-
const candidates = [];
|
|
157
|
-
let dir = startDir;
|
|
158
|
-
for (;;) {
|
|
159
|
-
candidates.push(join(dir, "node_modules", ...segments));
|
|
160
|
-
const parent = dirname(dir);
|
|
161
|
-
if (parent === dir) break;
|
|
162
|
-
dir = parent;
|
|
163
|
-
}
|
|
164
|
-
return candidates;
|
|
165
|
-
}
|
|
166
|
-
/**
|
|
167
|
-
* Anchored at the declaring manifest (required for pnpm's isolation), then falls back to a
|
|
168
|
-
* `node_modules` walk — an `exports` map without a `./package.json` entry blocks the first.
|
|
169
|
-
*/
|
|
170
|
-
function packageDir(pkg, fromManifest) {
|
|
171
|
-
try {
|
|
172
|
-
const require = createRequire(fromManifest);
|
|
173
|
-
return dirname(require.resolve(`${pkg}/package.json`));
|
|
174
|
-
} catch {}
|
|
175
|
-
for (const candidate of ancestorCandidates(dirname(fromManifest), pkg)) if (existsSync(join(candidate, "package.json"))) return candidate;
|
|
176
|
-
}
|
|
177
685
|
/** A manifest lives at the package root — the Agent Plugins Specification's pinned location. */
|
|
178
686
|
function readDepPlugin(pkg, fromManifest) {
|
|
179
687
|
const dir = packageDir(pkg, fromManifest);
|
|
@@ -182,7 +690,7 @@ function readDepPlugin(pkg, fromManifest) {
|
|
|
182
690
|
package: pkg,
|
|
183
691
|
reason: "unresolved"
|
|
184
692
|
};
|
|
185
|
-
const manifest = readJson$
|
|
693
|
+
const manifest = readJson$1(join(dir, "plugin.json"));
|
|
186
694
|
if (!manifest || typeof manifest !== "object") return {
|
|
187
695
|
ok: false,
|
|
188
696
|
package: pkg,
|
|
@@ -195,7 +703,7 @@ function readDepPlugin(pkg, fromManifest) {
|
|
|
195
703
|
package: pkg,
|
|
196
704
|
reason: "unnamed"
|
|
197
705
|
};
|
|
198
|
-
const installed = readJson$
|
|
706
|
+
const installed = readJson$1(join(dir, "package.json"));
|
|
199
707
|
const version = typeof installed?.version === "string" ? installed.version : void 0;
|
|
200
708
|
if (!version) return {
|
|
201
709
|
ok: false,
|
|
@@ -288,7 +796,7 @@ function writeCatalog(root, catalog) {
|
|
|
288
796
|
//#endregion
|
|
289
797
|
//#region src/dep-plugins/harness-plugins.ts
|
|
290
798
|
const COPILOT_LIMITATION = "Copilot CLI rejects an npm marketplace source, so it cannot install from this catalog. It needs a path-sourced catalog, which cannot reach node_modules from a subdirectory.";
|
|
291
|
-
function readJson
|
|
799
|
+
function readJson(path) {
|
|
292
800
|
try {
|
|
293
801
|
return JSON.parse(readFileSync(path, "utf8"));
|
|
294
802
|
} catch {
|
|
@@ -306,7 +814,7 @@ function claudeConfigDir(home, env = process.env) {
|
|
|
306
814
|
return env["CLAUDE_CONFIG_DIR"] || join(home, ".claude");
|
|
307
815
|
}
|
|
308
816
|
function readClaudeState(configDir) {
|
|
309
|
-
const installedFile = readJson
|
|
817
|
+
const installedFile = readJson(join(configDir, "plugins", "installed_plugins.json"));
|
|
310
818
|
const installed = [];
|
|
311
819
|
for (const [id, entries] of Object.entries(installedFile?.plugins ?? {})) {
|
|
312
820
|
if (!Array.isArray(entries)) continue;
|
|
@@ -329,7 +837,7 @@ function readClaudeState(configDir) {
|
|
|
329
837
|
});
|
|
330
838
|
}
|
|
331
839
|
}
|
|
332
|
-
const knownFile = readJson
|
|
840
|
+
const knownFile = readJson(join(configDir, "plugins", "known_marketplaces.json"));
|
|
333
841
|
const marketplaces = [];
|
|
334
842
|
for (const [name, value] of Object.entries(knownFile ?? {})) marketplaces.push({
|
|
335
843
|
name,
|
|
@@ -622,6 +1130,7 @@ const harnessRegistry = [
|
|
|
622
1130
|
detect: ".claude",
|
|
623
1131
|
...skillsProjection("claude-code", "user"),
|
|
624
1132
|
relocatedBy: "CLAUDE_CONFIG_DIR",
|
|
1133
|
+
emptyRelocatesToStart: true,
|
|
625
1134
|
instructionBridge: {
|
|
626
1135
|
kind: "import",
|
|
627
1136
|
path: ".claude/CLAUDE.md",
|
|
@@ -1031,6 +1540,14 @@ const globalInstructionTable = {
|
|
|
1031
1540
|
instruction: `${handOver} move what ${file} says into ${globalFile} and remove it`
|
|
1032
1541
|
}),
|
|
1033
1542
|
skillRepair: () => "hand the user the move of what that file says into the global file, and its removal; write nothing yourself"
|
|
1543
|
+
},
|
|
1544
|
+
"global-instructions-emptied": {
|
|
1545
|
+
detail: "the variable is set but empty, which this harness reads as the directory it starts in rather than as unset — its user-scope file is whichever one sits there, not the one in its own folder",
|
|
1546
|
+
repair: ({ file }) => ({
|
|
1547
|
+
command: "",
|
|
1548
|
+
instruction: `${handOver} unset ${file.slice(1)} where your shell sets it, or set it to the folder you meant`
|
|
1549
|
+
}),
|
|
1550
|
+
skillRepair: () => "hand the user the step of unsetting that variable; write nothing yourself"
|
|
1034
1551
|
}
|
|
1035
1552
|
};
|
|
1036
1553
|
const globalInstructionRepairs = repairsOf(globalInstructionTable);
|
|
@@ -2110,506 +2627,10 @@ function diagnoseNonstandard({ root, cli }) {
|
|
|
2110
2627
|
return findings.sort((left, right) => left.path.localeCompare(right.path));
|
|
2111
2628
|
}
|
|
2112
2629
|
//#endregion
|
|
2113
|
-
//#region src/references/reference-document.ts
|
|
2114
|
-
const mergeModes = [
|
|
2115
|
-
"first-wins",
|
|
2116
|
-
"combine",
|
|
2117
|
-
"merge-sections"
|
|
2118
|
-
];
|
|
2119
|
-
const frontmatterPattern = /^---[ \t]*\r?\n([\s\S]*?)\r?\n(?:---|\.\.\.)[ \t]*(?:\r?\n|$)/;
|
|
2120
|
-
/** Frontmatter that is not a YAML mapping is dropped with a warning, never passed off as body text. */
|
|
2121
|
-
function parseDocument(raw, warn) {
|
|
2122
|
-
const match = frontmatterPattern.exec(raw);
|
|
2123
|
-
if (!match) return {
|
|
2124
|
-
metadata: {},
|
|
2125
|
-
body: raw
|
|
2126
|
-
};
|
|
2127
|
-
const body = raw.slice(match[0].length);
|
|
2128
|
-
try {
|
|
2129
|
-
const value = parse$1(match[1]);
|
|
2130
|
-
if (value === null || value === void 0) return {
|
|
2131
|
-
metadata: {},
|
|
2132
|
-
body
|
|
2133
|
-
};
|
|
2134
|
-
if (isRecord(value)) return {
|
|
2135
|
-
metadata: value,
|
|
2136
|
-
body
|
|
2137
|
-
};
|
|
2138
|
-
} catch {}
|
|
2139
|
-
warn("frontmatter is not a YAML mapping; it is ignored");
|
|
2140
|
-
return {
|
|
2141
|
-
metadata: {},
|
|
2142
|
-
body
|
|
2143
|
-
};
|
|
2144
|
-
}
|
|
2145
|
-
function readMergeMode(metadata, warn) {
|
|
2146
|
-
const value = metadata["merge"];
|
|
2147
|
-
if (value === void 0) return "first-wins";
|
|
2148
|
-
if (mergeModes.includes(value)) return value;
|
|
2149
|
-
warn(`unknown merge mode "${String(value)}"; read as first-wins`);
|
|
2150
|
-
return "first-wins";
|
|
2151
|
-
}
|
|
2152
|
-
const mergeCommentPattern = /^\s*<!--\s*merge:\s*([\w-]*)\s*-->\s*$/;
|
|
2153
|
-
const headingPattern = /^ {0,3}(#{1,6})(?:[ \t]+(.*?))?(?:[ \t]+#+)?[ \t]*$/;
|
|
2154
|
-
const fenceOpenPattern = /^ {0,3}(`{3,}|~{3,})/;
|
|
2155
|
-
/**
|
|
2156
|
-
* Tracks fenced code blocks line by line — a `#` or a merge comment inside one is body text, and the
|
|
2157
|
-
* one thing a Markdown-unaware split gets wrong.
|
|
2158
|
-
*/
|
|
2159
|
-
function fenceTracker() {
|
|
2160
|
-
let fence;
|
|
2161
|
-
return (line) => {
|
|
2162
|
-
if (fence) {
|
|
2163
|
-
if (new RegExp(`^ {0,3}${fence[0] === "`" ? "`" : "~"}{${fence.length},}\\s*$`).test(line)) fence = void 0;
|
|
2164
|
-
return true;
|
|
2165
|
-
}
|
|
2166
|
-
const open = fenceOpenPattern.exec(line);
|
|
2167
|
-
if (open) {
|
|
2168
|
-
fence = open[1];
|
|
2169
|
-
return true;
|
|
2170
|
-
}
|
|
2171
|
-
return false;
|
|
2172
|
-
};
|
|
2173
|
-
}
|
|
2174
|
-
function stripMergeComments(body) {
|
|
2175
|
-
const inFence = fenceTracker();
|
|
2176
|
-
return body.split("\n").filter((line) => inFence(line) || !mergeCommentPattern.test(line)).join("\n");
|
|
2177
|
-
}
|
|
2178
|
-
/** Each heading with a single `#` outside a code fence, as written. */
|
|
2179
|
-
function titleHeadings(body) {
|
|
2180
|
-
const inFence = fenceTracker();
|
|
2181
|
-
return body.split("\n").filter((line) => !inFence(line) && headingPattern.exec(line)?.[1] === "#");
|
|
2182
|
-
}
|
|
2183
|
-
function sectionKey(title) {
|
|
2184
|
-
return title.trim().replace(/\s+/g, " ").toLowerCase();
|
|
2185
|
-
}
|
|
2186
|
-
function displayHeading(section) {
|
|
2187
|
-
return `${"#".repeat(section.level)} ${section.title}`;
|
|
2188
|
-
}
|
|
2189
|
-
function parseSections(body, warn) {
|
|
2190
|
-
const tree = {
|
|
2191
|
-
preamble: [],
|
|
2192
|
-
children: []
|
|
2193
|
-
};
|
|
2194
|
-
const stack = [];
|
|
2195
|
-
const inFence = fenceTracker();
|
|
2196
|
-
let awaitingOp;
|
|
2197
|
-
for (const line of body.split("\n")) {
|
|
2198
|
-
const current = stack.at(-1);
|
|
2199
|
-
const fenced = inFence(line);
|
|
2200
|
-
const heading = fenced ? null : headingPattern.exec(line);
|
|
2201
|
-
if (heading) {
|
|
2202
|
-
const level = heading[1].length;
|
|
2203
|
-
const section = {
|
|
2204
|
-
level,
|
|
2205
|
-
title: (heading[2] ?? "").trim(),
|
|
2206
|
-
heading: line.trimEnd(),
|
|
2207
|
-
op: "replace",
|
|
2208
|
-
body: [],
|
|
2209
|
-
children: []
|
|
2210
|
-
};
|
|
2211
|
-
while ((stack.at(-1)?.level ?? 0) >= level) stack.pop();
|
|
2212
|
-
(stack.at(-1)?.children ?? tree.children).push(section);
|
|
2213
|
-
stack.push(section);
|
|
2214
|
-
awaitingOp = section;
|
|
2215
|
-
continue;
|
|
2216
|
-
}
|
|
2217
|
-
if (awaitingOp && !fenced) {
|
|
2218
|
-
if (!line.trim()) continue;
|
|
2219
|
-
const comment = mergeCommentPattern.exec(line);
|
|
2220
|
-
if (comment) {
|
|
2221
|
-
const op = comment[1];
|
|
2222
|
-
if (op === "replace" || op === "combine" || op === "remove") awaitingOp.op = op;
|
|
2223
|
-
else warn(`unknown section merge "${op}" under "${displayHeading(awaitingOp)}"; read as replace`);
|
|
2224
|
-
awaitingOp = void 0;
|
|
2225
|
-
continue;
|
|
2226
|
-
}
|
|
2227
|
-
}
|
|
2228
|
-
awaitingOp = void 0;
|
|
2229
|
-
(current?.body ?? tree.preamble).push(line);
|
|
2230
|
-
}
|
|
2231
|
-
return tree;
|
|
2232
|
-
}
|
|
2233
|
-
function trimBlank(lines) {
|
|
2234
|
-
let start = 0;
|
|
2235
|
-
let end = lines.length;
|
|
2236
|
-
while (start < end && !lines[start].trim()) start++;
|
|
2237
|
-
while (end > start && !lines[end - 1].trim()) end--;
|
|
2238
|
-
return lines.slice(start, end);
|
|
2239
|
-
}
|
|
2240
|
-
function warnDuplicates(sections, path, where, warn) {
|
|
2241
|
-
const seen = /* @__PURE__ */ new Set();
|
|
2242
|
-
for (const section of sections) {
|
|
2243
|
-
const key = sectionKey(section.title);
|
|
2244
|
-
if (seen.has(key)) warn(`heading path "${path}${displayHeading(section)}" appears more than once in ${where}; the first is matched`);
|
|
2245
|
-
seen.add(key);
|
|
2246
|
-
}
|
|
2247
|
-
}
|
|
2248
|
-
function warnUnmatched(section, path, where, warn) {
|
|
2249
|
-
warn(`"<!-- merge: ${section.op} -->" on "${path}${displayHeading(section)}" in ${where} matches no section below`);
|
|
2250
|
-
}
|
|
2251
|
-
/** A section placed without merging has nothing below its subsections, so their merge comments match nothing. */
|
|
2252
|
-
function place(section, path, where, warn) {
|
|
2253
|
-
const childPath = `${path}${displayHeading(section)} > `;
|
|
2254
|
-
const children = section.children.flatMap((child) => {
|
|
2255
|
-
if (child.op !== "replace") warnUnmatched(child, childPath, where, warn);
|
|
2256
|
-
return child.op === "remove" ? [] : [place(child, childPath, where, warn)];
|
|
2257
|
-
});
|
|
2258
|
-
return {
|
|
2259
|
-
...section,
|
|
2260
|
-
children
|
|
2261
|
-
};
|
|
2262
|
-
}
|
|
2263
|
-
function mergeChildren(base, overlay, path, where, warn) {
|
|
2264
|
-
warnDuplicates(base, path, "the layers below", warn);
|
|
2265
|
-
warnDuplicates(overlay, path, where, warn);
|
|
2266
|
-
const slots = [...base];
|
|
2267
|
-
const appended = [];
|
|
2268
|
-
const matched = /* @__PURE__ */ new Set();
|
|
2269
|
-
for (const section of overlay) {
|
|
2270
|
-
const key = sectionKey(section.title);
|
|
2271
|
-
const index = base.findIndex((candidate, i) => !matched.has(i) && sectionKey(candidate.title) === key);
|
|
2272
|
-
if (index === -1) {
|
|
2273
|
-
if (section.op !== "replace") warnUnmatched(section, path, where, warn);
|
|
2274
|
-
if (section.op !== "remove") appended.push(place(section, path, where, warn));
|
|
2275
|
-
continue;
|
|
2276
|
-
}
|
|
2277
|
-
for (let i = 0; i < base.length; i++) if (sectionKey(base[i].title) === key) matched.add(i);
|
|
2278
|
-
const target = base[index];
|
|
2279
|
-
if (section.op === "remove") slots[index] = void 0;
|
|
2280
|
-
else if (section.op === "combine") {
|
|
2281
|
-
const baseBody = trimBlank(target.body);
|
|
2282
|
-
const overlayBody = trimBlank(section.body);
|
|
2283
|
-
slots[index] = {
|
|
2284
|
-
...target,
|
|
2285
|
-
body: baseBody.length && overlayBody.length ? [
|
|
2286
|
-
...baseBody,
|
|
2287
|
-
"",
|
|
2288
|
-
...overlayBody
|
|
2289
|
-
] : [...baseBody, ...overlayBody],
|
|
2290
|
-
children: mergeChildren(target.children, section.children, `${path}${displayHeading(target)} > `, where, warn)
|
|
2291
|
-
};
|
|
2292
|
-
} else slots[index] = place(section, path, where, warn);
|
|
2293
|
-
}
|
|
2294
|
-
return [...slots.filter((slot) => slot !== void 0), ...appended];
|
|
2295
|
-
}
|
|
2296
|
-
/** `where` names the overlay in warnings, so a person can find the heading it is about. */
|
|
2297
|
-
function mergeSections(base, overlay, where, warn) {
|
|
2298
|
-
const overlayPreamble = trimBlank(overlay.preamble);
|
|
2299
|
-
return {
|
|
2300
|
-
preamble: overlayPreamble.length ? overlayPreamble : base.preamble,
|
|
2301
|
-
children: mergeChildren(base.children, overlay.children, "", where, warn)
|
|
2302
|
-
};
|
|
2303
|
-
}
|
|
2304
|
-
function renderSections(tree) {
|
|
2305
|
-
const blocks = [];
|
|
2306
|
-
const preamble = trimBlank(tree.preamble);
|
|
2307
|
-
if (preamble.length) blocks.push(preamble.join("\n"));
|
|
2308
|
-
const visit = (section) => {
|
|
2309
|
-
const body = trimBlank(section.body);
|
|
2310
|
-
blocks.push(body.length ? `${section.heading}\n\n${body.join("\n")}` : section.heading);
|
|
2311
|
-
for (const child of section.children) visit(child);
|
|
2312
|
-
};
|
|
2313
|
-
for (const section of tree.children) visit(section);
|
|
2314
|
-
return `${blocks.join("\n\n")}\n`;
|
|
2315
|
-
}
|
|
2316
|
-
//#endregion
|
|
2317
|
-
//#region src/references/resolve-reference.ts
|
|
2318
|
-
const namePattern$1 = /^[a-z0-9]+(?:[-.][a-z0-9]+)*$/i;
|
|
2319
|
-
const pluginPattern = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/i;
|
|
2320
|
-
/**
|
|
2321
|
-
* Rejects rather than sanitizes — silently answering a different question is how untrusted input
|
|
2322
|
-
* reads a file outside the layer. The plugin qualifier is only ever compared with known plugin
|
|
2323
|
-
* names, never joined into a path.
|
|
2324
|
-
*/
|
|
2325
|
-
function parseReferenceName(value) {
|
|
2326
|
-
if (value.endsWith(".md")) throw new Error(`"${value}" names a file. Ask for the reference by name, without the .md extension.`);
|
|
2327
|
-
const slash = value.lastIndexOf("/");
|
|
2328
|
-
const name = slash === -1 ? value : value.slice(slash + 1);
|
|
2329
|
-
const plugin = slash === -1 ? void 0 : value.slice(0, slash);
|
|
2330
|
-
if (!namePattern$1.test(name) || plugin !== void 0 && !pluginPattern.test(plugin)) throw new Error(`"${value}" is not a reference name. A name is letters, digits, hyphens, and dots, optionally after "<plugin>/" — not a path.`);
|
|
2331
|
-
return {
|
|
2332
|
-
name,
|
|
2333
|
-
plugin,
|
|
2334
|
-
raw: value
|
|
2335
|
-
};
|
|
2336
|
-
}
|
|
2337
|
-
const folderCandidates = [
|
|
2338
|
-
"README.md",
|
|
2339
|
-
"index.md",
|
|
2340
|
-
"SKILL.md"
|
|
2341
|
-
];
|
|
2342
|
-
/** Search order within one layer; the first that reads wins. */
|
|
2343
|
-
function candidateFiles(name) {
|
|
2344
|
-
return [`${name}.md`, ...folderCandidates.map((file) => `${name}/${file}`)];
|
|
2345
|
-
}
|
|
2346
|
-
function tryRead(path) {
|
|
2347
|
-
try {
|
|
2348
|
-
return readFileSync(path, "utf8");
|
|
2349
|
-
} catch {
|
|
2350
|
-
return;
|
|
2351
|
-
}
|
|
2352
|
-
}
|
|
2353
|
-
function pluginLabel(layer) {
|
|
2354
|
-
return layer.plugins[0] ?? "";
|
|
2355
|
-
}
|
|
2356
|
-
function layerName(layer) {
|
|
2357
|
-
return layer.tier === "plugin" ? `plugin ${pluginLabel(layer)}` : layer.tier;
|
|
2358
|
-
}
|
|
2359
|
-
/** The layers a name is resolved through, in the order `resolveReference` traces them. */
|
|
2360
|
-
function layersFor$2(ref, layers) {
|
|
2361
|
-
const plugin = ref.plugin;
|
|
2362
|
-
if (plugin === void 0) return [...layers];
|
|
2363
|
-
const named = layers.filter((layer) => layer.tier !== "plugin" || layer.plugins.includes(plugin));
|
|
2364
|
-
if (named.some((layer) => layer.tier === "plugin")) return named;
|
|
2365
|
-
return [...named, {
|
|
2366
|
-
tier: "plugin",
|
|
2367
|
-
dir: `(no dependency named ${plugin})`,
|
|
2368
|
-
plugins: [plugin],
|
|
2369
|
-
status: ""
|
|
2370
|
-
}];
|
|
2371
|
-
}
|
|
2372
|
-
function resolveReference(ref, layers, { display = (path) => path } = {}) {
|
|
2373
|
-
const warnings = [];
|
|
2374
|
-
const trace = [];
|
|
2375
|
-
const found = [];
|
|
2376
|
-
for (const layer of layersFor$2(ref, layers)) {
|
|
2377
|
-
const entry = {
|
|
2378
|
-
tier: layer.tier,
|
|
2379
|
-
plugin: pluginLabel(layer),
|
|
2380
|
-
path: layer.dir,
|
|
2381
|
-
found: false,
|
|
2382
|
-
candidate: "",
|
|
2383
|
-
merge: "",
|
|
2384
|
-
outcome: "missing",
|
|
2385
|
-
description: ""
|
|
2386
|
-
};
|
|
2387
|
-
trace.push(entry);
|
|
2388
|
-
if (layer.skipped) {
|
|
2389
|
-
entry.outcome = layer.skipped;
|
|
2390
|
-
continue;
|
|
2391
|
-
}
|
|
2392
|
-
const [hit, ...ignored] = candidateFiles(ref.name).flatMap((candidate) => {
|
|
2393
|
-
const raw = tryRead(join(layer.dir, candidate));
|
|
2394
|
-
return raw === void 0 ? [] : [{
|
|
2395
|
-
candidate,
|
|
2396
|
-
raw
|
|
2397
|
-
}];
|
|
2398
|
-
});
|
|
2399
|
-
if (!hit) continue;
|
|
2400
|
-
for (const other of ignored) warnings.push(`${display(join(layer.dir, other.candidate))} is ignored: ${hit.candidate} answers first in that folder`);
|
|
2401
|
-
const path = join(layer.dir, hit.candidate);
|
|
2402
|
-
const warn = (message) => warnings.push(`${display(path)}: ${message}`);
|
|
2403
|
-
const { metadata, body } = parseDocument(hit.raw, warn);
|
|
2404
|
-
const merge = readMergeMode(metadata, warn);
|
|
2405
|
-
const description = typeof metadata["description"] === "string" ? metadata["description"] : "";
|
|
2406
|
-
Object.assign(entry, {
|
|
2407
|
-
path,
|
|
2408
|
-
found: true,
|
|
2409
|
-
candidate: hit.candidate,
|
|
2410
|
-
merge,
|
|
2411
|
-
outcome: "",
|
|
2412
|
-
description
|
|
2413
|
-
});
|
|
2414
|
-
found.push({
|
|
2415
|
-
layer,
|
|
2416
|
-
entry,
|
|
2417
|
-
metadata,
|
|
2418
|
-
body,
|
|
2419
|
-
merge
|
|
2420
|
-
});
|
|
2421
|
-
}
|
|
2422
|
-
const result = {
|
|
2423
|
-
name: ref.raw,
|
|
2424
|
-
status: "missing",
|
|
2425
|
-
layers: [],
|
|
2426
|
-
warnings,
|
|
2427
|
-
plugins: [],
|
|
2428
|
-
trace
|
|
2429
|
-
};
|
|
2430
|
-
const stop = found.findIndex(({ merge }) => merge === "first-wins");
|
|
2431
|
-
const chain = stop === -1 ? found : found.slice(0, stop + 1);
|
|
2432
|
-
const shadowed = stop === -1 ? [] : found.slice(stop + 1);
|
|
2433
|
-
const base = chain.at(-1);
|
|
2434
|
-
const holders = [...new Set(found.filter(({ layer }) => layer.tier === "plugin").map(({ entry }) => entry.plugin))];
|
|
2435
|
-
if (ref.plugin === void 0 && holders.length > 1 && chain.some(({ layer }) => layer.tier === "plugin")) {
|
|
2436
|
-
for (const { entry } of found) entry.outcome = "ambiguous";
|
|
2437
|
-
result.status = "ambiguous";
|
|
2438
|
-
result.plugins = holders.map((plugin) => `${plugin}/${ref.name}`);
|
|
2439
|
-
return result;
|
|
2440
|
-
}
|
|
2441
|
-
for (const document of shadowed) document.entry.outcome = `shadowed by ${base.layer.tier} (first-wins)`;
|
|
2442
|
-
if (!base) return result;
|
|
2443
|
-
for (const { entry } of chain) entry.outcome = "used";
|
|
2444
|
-
const top = chain[0];
|
|
2445
|
-
return {
|
|
2446
|
-
...result,
|
|
2447
|
-
status: "found",
|
|
2448
|
-
tier: top.layer.tier,
|
|
2449
|
-
plugin: top.entry.plugin,
|
|
2450
|
-
path: top.entry.path,
|
|
2451
|
-
merge: top.merge,
|
|
2452
|
-
metadata: Object.assign({}, ...[...chain].reverse().map(({ metadata }) => metadata)),
|
|
2453
|
-
content: withNewline(stripMergeComments(fold(chain, display, (message) => warnings.push(message)))),
|
|
2454
|
-
layers: chain.map(({ layer, entry, merge }) => ({
|
|
2455
|
-
tier: layer.tier,
|
|
2456
|
-
plugin: entry.plugin,
|
|
2457
|
-
path: entry.path,
|
|
2458
|
-
merge
|
|
2459
|
-
}))
|
|
2460
|
-
};
|
|
2461
|
-
}
|
|
2462
|
-
/** Bottom-up: the base is the lowest document read, and each document above says how it applies. */
|
|
2463
|
-
function fold(chain, display, warn) {
|
|
2464
|
-
const label = ({ layer, entry }) => `${layerName(layer)} ${display(entry.path)}`;
|
|
2465
|
-
const [base, ...above] = [...chain].reverse();
|
|
2466
|
-
let parts = [{
|
|
2467
|
-
labels: [label(base)],
|
|
2468
|
-
body: base.body
|
|
2469
|
-
}];
|
|
2470
|
-
for (const document of above) {
|
|
2471
|
-
if (document.merge === "combine") {
|
|
2472
|
-
parts = [{
|
|
2473
|
-
labels: [label(document)],
|
|
2474
|
-
body: document.body
|
|
2475
|
-
}, ...parts];
|
|
2476
|
-
continue;
|
|
2477
|
-
}
|
|
2478
|
-
const merged = mergeSections(parseSections(parts.map(({ body }) => body.trim()).join("\n\n"), warn), parseSections(document.body, warn), label(document), warn);
|
|
2479
|
-
parts = [{
|
|
2480
|
-
labels: [label(document), ...parts.flatMap(({ labels }) => labels)],
|
|
2481
|
-
body: renderSections(merged)
|
|
2482
|
-
}];
|
|
2483
|
-
}
|
|
2484
|
-
if (parts.length === 1) return parts[0].body;
|
|
2485
|
-
return [`> Combined from ${parts.length} layers, highest precedence first. Where they conflict, the first layer wins.`, ...parts.map(({ labels, body }) => `<!-- layer: ${labels.join(", ")} -->\n\n${body.trim()}`)].join("\n\n");
|
|
2486
|
-
}
|
|
2487
|
-
function withNewline(content) {
|
|
2488
|
-
return content.endsWith("\n") ? content : `${content}\n`;
|
|
2489
|
-
}
|
|
2490
|
-
/** Every name a layer holds in any candidate form; empty for a layer that is missing or unreadable. */
|
|
2491
|
-
function layerNames(dir) {
|
|
2492
|
-
let entries;
|
|
2493
|
-
try {
|
|
2494
|
-
entries = readdirSync(dir, { withFileTypes: true });
|
|
2495
|
-
} catch {
|
|
2496
|
-
return [];
|
|
2497
|
-
}
|
|
2498
|
-
const names = /* @__PURE__ */ new Set();
|
|
2499
|
-
for (const entry of entries) {
|
|
2500
|
-
const name = entry.isFile() && entry.name.endsWith(".md") ? entry.name.slice(0, -3) : entry.name;
|
|
2501
|
-
if (!namePattern$1.test(name)) continue;
|
|
2502
|
-
if (entry.isFile() ? entry.name.endsWith(".md") : folderCandidates.some((file) => tryRead(join(dir, name, file)) !== void 0)) names.add(name);
|
|
2503
|
-
}
|
|
2504
|
-
return [...names];
|
|
2505
|
-
}
|
|
2506
|
-
function referenceNames(layers) {
|
|
2507
|
-
return [...new Set(layers.flatMap(({ dir, skipped }) => skipped ? [] : layerNames(dir)))].sort((a, b) => a.localeCompare(b));
|
|
2508
|
-
}
|
|
2509
|
-
//#endregion
|
|
2510
|
-
//#region src/references/reference-catalog.ts
|
|
2511
|
-
/** One row per name per layer holding it, with the status resolution gave that layer. */
|
|
2512
|
-
function listReferences(layers, options = {}) {
|
|
2513
|
-
const rows = [];
|
|
2514
|
-
const warnings = /* @__PURE__ */ new Set();
|
|
2515
|
-
for (const name of referenceNames(layers)) {
|
|
2516
|
-
const resolved = resolveReference(parseReferenceName(name), layers, options);
|
|
2517
|
-
for (const warning of resolved.warnings) warnings.add(warning);
|
|
2518
|
-
for (const entry of resolved.trace) {
|
|
2519
|
-
if (!entry.found) continue;
|
|
2520
|
-
rows.push({
|
|
2521
|
-
name,
|
|
2522
|
-
tier: entry.tier,
|
|
2523
|
-
plugin: entry.plugin,
|
|
2524
|
-
path: entry.path,
|
|
2525
|
-
status: entry.outcome === "ambiguous" ? `ambiguous — ask for one of ${resolved.plugins.join(", ")}` : entry.outcome,
|
|
2526
|
-
description: entry.description
|
|
2527
|
-
});
|
|
2528
|
-
}
|
|
2529
|
-
}
|
|
2530
|
-
return {
|
|
2531
|
-
rows,
|
|
2532
|
-
warnings: [...warnings]
|
|
2533
|
-
};
|
|
2534
|
-
}
|
|
2535
|
-
const matchOrder = [
|
|
2536
|
-
"name",
|
|
2537
|
-
"prefix",
|
|
2538
|
-
"close name",
|
|
2539
|
-
"description",
|
|
2540
|
-
"heading",
|
|
2541
|
-
"body"
|
|
2542
|
-
];
|
|
2543
|
-
function distance(a, b) {
|
|
2544
|
-
let previous = Array.from({ length: b.length + 1 }, (_, i) => i);
|
|
2545
|
-
for (let i = 1; i <= a.length; i++) {
|
|
2546
|
-
const current = [i];
|
|
2547
|
-
for (let j = 1; j <= b.length; j++) {
|
|
2548
|
-
const substitution = previous[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1);
|
|
2549
|
-
current.push(Math.min(previous[j] + 1, current[j - 1] + 1, substitution));
|
|
2550
|
-
}
|
|
2551
|
-
previous = current;
|
|
2552
|
-
}
|
|
2553
|
-
return previous[b.length];
|
|
2554
|
-
}
|
|
2555
|
-
function headings(content) {
|
|
2556
|
-
let fenced = false;
|
|
2557
|
-
const lines = [];
|
|
2558
|
-
for (const line of content.split("\n")) if (/^ {0,3}(`{3,}|~{3,})/.test(line)) fenced = !fenced;
|
|
2559
|
-
else if (!fenced && /^ {0,3}#{1,6}\s/.test(line)) lines.push(line);
|
|
2560
|
-
return lines.join("\n");
|
|
2561
|
-
}
|
|
2562
|
-
function tagText(value) {
|
|
2563
|
-
if (Array.isArray(value)) return value.map(String).join(" ");
|
|
2564
|
-
return typeof value === "string" ? value : "";
|
|
2565
|
-
}
|
|
2566
|
-
function matchKind(name, reference, query) {
|
|
2567
|
-
const bare = name.slice(name.lastIndexOf("/") + 1).toLowerCase();
|
|
2568
|
-
if (bare === query || name.toLowerCase() === query) return "name";
|
|
2569
|
-
if (bare.startsWith(query)) return "prefix";
|
|
2570
|
-
if (bare.includes(query) || distance(bare, query) <= Math.max(1, Math.floor(query.length / 4))) return "close name";
|
|
2571
|
-
const terms = query.split(/\s+/);
|
|
2572
|
-
const holds = (text) => {
|
|
2573
|
-
const lower = text.toLowerCase();
|
|
2574
|
-
return terms.every((term) => lower.includes(term));
|
|
2575
|
-
};
|
|
2576
|
-
const metadata = reference.metadata;
|
|
2577
|
-
if (holds(`${typeof metadata["description"] === "string" ? metadata["description"] : ""} ${tagText(metadata["tags"])}`)) return "description";
|
|
2578
|
-
const content = reference.content;
|
|
2579
|
-
if (holds(headings(content))) return "heading";
|
|
2580
|
-
if (holds(content)) return "body";
|
|
2581
|
-
}
|
|
2582
|
-
/**
|
|
2583
|
-
* Every name resolves the way `show` would; a name two plugins hold is searched once per plugin, as
|
|
2584
|
-
* the qualified name `show` would need.
|
|
2585
|
-
*/
|
|
2586
|
-
function searchReferences(query, layers, options = {}) {
|
|
2587
|
-
const normalized = query.trim().toLowerCase();
|
|
2588
|
-
const matches = [];
|
|
2589
|
-
for (const name of referenceNames(layers)) {
|
|
2590
|
-
const resolved = resolveReference(parseReferenceName(name), layers, options);
|
|
2591
|
-
const candidates = resolved.status === "ambiguous" ? resolved.plugins.map((qualified) => resolveReference(parseReferenceName(qualified), layers, options)) : [resolved];
|
|
2592
|
-
for (const reference of candidates.filter(({ status }) => status === "found")) {
|
|
2593
|
-
const match = matchKind(reference.name, reference, normalized);
|
|
2594
|
-
if (!match) continue;
|
|
2595
|
-
const description = reference.metadata["description"];
|
|
2596
|
-
matches.push({
|
|
2597
|
-
name: reference.name,
|
|
2598
|
-
tier: reference.tier,
|
|
2599
|
-
match,
|
|
2600
|
-
description: typeof description === "string" ? description.split("\n")[0]?.trim() || "" : ""
|
|
2601
|
-
});
|
|
2602
|
-
}
|
|
2603
|
-
}
|
|
2604
|
-
return matches.sort((a, b) => matchOrder.indexOf(a.match) - matchOrder.indexOf(b.match) || a.name.localeCompare(b.name));
|
|
2605
|
-
}
|
|
2606
|
-
//#endregion
|
|
2607
2630
|
//#region src/governance-overrides/governance-overrides.ts
|
|
2608
2631
|
/** @deprecated Use `managedReferencesDir`. Removed in the next major version. */
|
|
2609
2632
|
function managedGovernancesDir(platform, programData) {
|
|
2610
|
-
|
|
2611
|
-
if (platform === "win32") return join(programData || "C:\\ProgramData", "BuddyAgentHarness", "governances");
|
|
2612
|
-
return "/etc/buddy-agent-harness/governances";
|
|
2633
|
+
return managedGovernancesDir$1(platform, programData);
|
|
2613
2634
|
}
|
|
2614
2635
|
/**
|
|
2615
2636
|
* Still read below the layer above, so a machine already using it keeps working; reported as
|
|
@@ -2618,9 +2639,7 @@ function managedGovernancesDir(platform, programData) {
|
|
|
2618
2639
|
* @deprecated Use `managedReferencesDir`. Removed in the next major version.
|
|
2619
2640
|
*/
|
|
2620
2641
|
function deprecatedManagedGovernancesDir(platform, programData) {
|
|
2621
|
-
|
|
2622
|
-
if (platform === "win32") return join(programData || "C:\\ProgramData", "UniPlugin", "governances");
|
|
2623
|
-
return "/etc/universal-plugin/governances";
|
|
2642
|
+
return deprecatedManagedGovernancesDir$1(platform, programData);
|
|
2624
2643
|
}
|
|
2625
2644
|
function projectGovernancesDir(root) {
|
|
2626
2645
|
return join(root, ".agents", "governances");
|
|
@@ -2734,246 +2753,22 @@ function listGovernances(layers) {
|
|
|
2734
2753
|
return [...found.values()].sort((a, b) => a.name.localeCompare(b.name));
|
|
2735
2754
|
}
|
|
2736
2755
|
//#endregion
|
|
2737
|
-
//#region src/references/
|
|
2738
|
-
/** Nested harnesses leave `detectHarness` at `unknown`; each candidate is still a harness in play. */
|
|
2739
|
-
function detectedHarnesses(env) {
|
|
2740
|
-
return detectHarness({ env }).candidates;
|
|
2741
|
-
}
|
|
2742
|
-
const unreadableKind = {
|
|
2743
|
-
"macos-managed-preferences": "a macOS managed-preferences domain delivered by MDM",
|
|
2744
|
-
"windows-registry": "a Windows registry key delivered by MDM or Group Policy",
|
|
2745
|
-
server: "server-side settings"
|
|
2746
|
-
};
|
|
2747
|
-
function skippedLayer(tier, dir, skipped, plugins = []) {
|
|
2748
|
-
return {
|
|
2749
|
-
tier,
|
|
2750
|
-
dir,
|
|
2751
|
-
plugins,
|
|
2752
|
-
status: skipped,
|
|
2753
|
-
skipped
|
|
2754
|
-
};
|
|
2755
|
-
}
|
|
2756
|
-
/**
|
|
2757
|
-
* The folder holding a harness's managed files gets a `references/` beside them. A `directory`
|
|
2758
|
-
* location inside that folder, such as a drop-in `managed-settings.d`, is part of it, not a folder
|
|
2759
|
-
* of its own.
|
|
2760
|
-
*/
|
|
2761
|
-
function managedFolders(harness, platform, env) {
|
|
2762
|
-
const path = platform === "win32" ? win32 : posix;
|
|
2763
|
-
const locations = managedPolicyLocations(harness, {
|
|
2764
|
-
platform,
|
|
2765
|
-
env
|
|
2766
|
-
});
|
|
2767
|
-
const folders = [...new Set(locations.flatMap(({ kind, location }) => kind === "file" ? [path.dirname(location)] : kind === "directory" ? [location] : []))];
|
|
2768
|
-
return {
|
|
2769
|
-
read: folders.filter((folder) => !folders.some((other) => folder.startsWith(other + path.sep))).map((folder) => path.join(folder, "references")),
|
|
2770
|
-
unread: locations.flatMap(({ kind, location }) => {
|
|
2771
|
-
const where = unreadableKind[kind];
|
|
2772
|
-
return where ? [{
|
|
2773
|
-
location,
|
|
2774
|
-
reason: `not read — ${harness} keeps this policy in ${where}, which cannot be read locally`
|
|
2775
|
-
}] : [];
|
|
2776
|
-
})
|
|
2777
|
-
};
|
|
2778
|
-
}
|
|
2779
|
-
function harnessManagedLayers(harnesses, platform, env) {
|
|
2780
|
-
if (!harnesses.length) return [skippedLayer("managed", "(no harness detected)", "not read — no harness detected, so no harness managed folder")];
|
|
2781
|
-
return harnesses.flatMap((harness) => {
|
|
2782
|
-
const { read, unread } = managedFolders(harness, platform, env);
|
|
2783
|
-
return [...read.map((dir) => ({
|
|
2784
|
-
tier: "managed",
|
|
2785
|
-
dir,
|
|
2786
|
-
plugins: [],
|
|
2787
|
-
status: ""
|
|
2788
|
-
})), ...unread.map(({ location, reason }) => skippedLayer("managed", location, reason))];
|
|
2789
|
-
});
|
|
2790
|
-
}
|
|
2791
|
-
/**
|
|
2792
|
-
* Claude Code installs one plugin at several scopes; a project- or local-scoped install loads only in
|
|
2793
|
-
* its own project, so the nearest folder of the walk picks it, and a user install answers elsewhere.
|
|
2794
|
-
*/
|
|
2795
|
-
function activeInstall(installs, chain) {
|
|
2796
|
-
for (const dir of chain) {
|
|
2797
|
-
const install = installs.find(({ projectPath }) => projectPath === dir);
|
|
2798
|
-
if (install) return install;
|
|
2799
|
-
}
|
|
2800
|
-
return installs.find(({ projectPath }) => projectPath === void 0);
|
|
2801
|
-
}
|
|
2802
|
-
/**
|
|
2803
|
-
* Only plugins the harness has enabled: installing a plugin never activates it, and a reference is
|
|
2804
|
-
* instruction text an agent follows.
|
|
2805
|
-
*/
|
|
2806
|
-
async function enabledPluginLayers(harnesses, chain, environment) {
|
|
2807
|
-
const layers = [];
|
|
2808
|
-
for (const harness of harnesses) {
|
|
2809
|
-
const [enabled, installed] = await Promise.all([enabledPlugins(harness, environment), installedPlugins(harness, environment)]);
|
|
2810
|
-
if (!enabled.supported) {
|
|
2811
|
-
layers.push(skippedLayer("plugin", `(${harness} enabled plugins)`, `not read — ${harness} keeps no readable record of enabled plugins`));
|
|
2812
|
-
continue;
|
|
2813
|
-
}
|
|
2814
|
-
if (enabled.unread.length) layers.push(skippedLayer("plugin", `(${harness} plugin policy)`, `not read — ${enabled.unread.join("; ")} may also enable or disable ${harness} plugins`));
|
|
2815
|
-
for (const { id, enabled: on } of enabled.plugins) {
|
|
2816
|
-
if (!on) continue;
|
|
2817
|
-
const plugin = id.split("@")[0];
|
|
2818
|
-
const install = activeInstall(installed.plugins.filter((candidate) => candidate.id === id), chain);
|
|
2819
|
-
if (install) {
|
|
2820
|
-
layers.push({
|
|
2821
|
-
tier: "plugin",
|
|
2822
|
-
dir: join(install.path, "references"),
|
|
2823
|
-
plugins: [plugin],
|
|
2824
|
-
status: ""
|
|
2825
|
-
});
|
|
2826
|
-
continue;
|
|
2827
|
-
}
|
|
2828
|
-
layers.push(skippedLayer("plugin", `(${id})`, `not read — enabled in ${harness}, but no install folder for this project is recorded`, [plugin]));
|
|
2829
|
-
}
|
|
2830
|
-
}
|
|
2831
|
-
return layers;
|
|
2832
|
-
}
|
|
2833
|
-
//#endregion
|
|
2834
|
-
//#region src/references/reference-layers.ts
|
|
2756
|
+
//#region src/references/references.ts
|
|
2835
2757
|
const PACKAGE_PLUGIN = "buddy-agent-harness";
|
|
2836
|
-
|
|
2837
|
-
|
|
2838
|
-
|
|
2839
|
-
|
|
2840
|
-
|
|
2841
|
-
|
|
2842
|
-
|
|
2843
|
-
}
|
|
2844
|
-
function projectReferenceLayers(root) {
|
|
2845
|
-
return [{
|
|
2846
|
-
tier: "project",
|
|
2847
|
-
dir: projectReferencesDir(root),
|
|
2848
|
-
plugins: [],
|
|
2849
|
-
status: ""
|
|
2850
|
-
}, {
|
|
2851
|
-
tier: "project",
|
|
2852
|
-
dir: join(root, ".agents", "governances"),
|
|
2853
|
-
plugins: [],
|
|
2854
|
-
status: LEGACY_STATUS
|
|
2855
|
-
}];
|
|
2856
|
-
}
|
|
2857
|
-
function readJson(path) {
|
|
2858
|
-
try {
|
|
2859
|
-
return JSON.parse(readFileSync(path, "utf8"));
|
|
2860
|
-
} catch {
|
|
2861
|
-
return;
|
|
2862
|
-
}
|
|
2863
|
-
}
|
|
2864
|
-
function isRepositoryRoot(dir) {
|
|
2865
|
-
if (existsSync(join(dir, ".git")) || existsSync(join(dir, "pnpm-workspace.yaml"))) return true;
|
|
2866
|
-
const manifest = readJson(join(dir, "package.json"));
|
|
2867
|
-
return isRecord(manifest) && manifest["workspaces"] !== void 0;
|
|
2868
|
-
}
|
|
2869
|
-
/**
|
|
2870
|
-
* `root` and each folder above it up to the repository root, nearest first. With no repository root
|
|
2871
|
-
* above, `root` alone: a walk that never finds one would read every ancestor up to the filesystem root.
|
|
2872
|
-
*/
|
|
2873
|
-
function projectChain(root) {
|
|
2874
|
-
const start = resolve(root);
|
|
2875
|
-
const chain = [];
|
|
2876
|
-
let dir = start;
|
|
2877
|
-
for (;;) {
|
|
2878
|
-
chain.push(dir);
|
|
2879
|
-
if (isRepositoryRoot(dir)) return chain;
|
|
2880
|
-
const parent = dirname(dir);
|
|
2881
|
-
if (parent === dir) return [start];
|
|
2882
|
-
dir = parent;
|
|
2883
|
-
}
|
|
2884
|
-
}
|
|
2885
|
-
function isDirectory$2(path) {
|
|
2886
|
-
try {
|
|
2887
|
-
return statSync(path).isDirectory();
|
|
2888
|
-
} catch {
|
|
2889
|
-
return false;
|
|
2890
|
-
}
|
|
2891
|
-
}
|
|
2892
|
-
function nearestManifest(root) {
|
|
2893
|
-
let dir = root;
|
|
2894
|
-
for (;;) {
|
|
2895
|
-
const path = join(dir, "package.json");
|
|
2896
|
-
if (existsSync(path)) return path;
|
|
2897
|
-
const parent = dirname(dir);
|
|
2898
|
-
if (parent === dir) return void 0;
|
|
2899
|
-
dir = parent;
|
|
2900
|
-
}
|
|
2901
|
-
}
|
|
2902
|
-
function canonical(path) {
|
|
2903
|
-
try {
|
|
2904
|
-
return realpathSync(path);
|
|
2905
|
-
} catch {
|
|
2906
|
-
return path;
|
|
2907
|
-
}
|
|
2908
|
-
}
|
|
2909
|
-
/**
|
|
2910
|
-
* Declared dependencies only: a transitive package never becomes a plugin, because a reference is
|
|
2911
|
-
* instruction text an agent follows.
|
|
2912
|
-
*/
|
|
2913
|
-
function dependencyLayers(root, skip) {
|
|
2914
|
-
const manifestPath = nearestManifest(root);
|
|
2915
|
-
if (!manifestPath) return [];
|
|
2916
|
-
const layers = [];
|
|
2917
|
-
for (const pkg of declaredDependencies(readJson(manifestPath))) {
|
|
2918
|
-
const dir = packageDir(pkg, manifestPath);
|
|
2919
|
-
if (!dir || skip.has(canonical(dir))) continue;
|
|
2920
|
-
const references = join(dir, "references");
|
|
2921
|
-
if (!isDirectory$2(references)) continue;
|
|
2922
|
-
const manifest = readJson(join(dir, "plugin.json"));
|
|
2923
|
-
const manifestName = isRecord(manifest) && typeof manifest["name"] === "string" ? manifest["name"] : void 0;
|
|
2924
|
-
const plugins = manifestName && manifestName !== pkg ? [pkg, manifestName] : [pkg];
|
|
2925
|
-
layers.push({
|
|
2926
|
-
tier: "plugin",
|
|
2927
|
-
dir: references,
|
|
2928
|
-
plugins,
|
|
2929
|
-
status: ""
|
|
2930
|
-
});
|
|
2931
|
-
}
|
|
2932
|
-
return layers;
|
|
2933
|
-
}
|
|
2934
|
-
async function referenceLayers({ root, home, platform, programData, packageRoot = dirname(packageGovernancesDir()), env = process.env }) {
|
|
2935
|
-
const layer = (tier, dir, status = "") => ({
|
|
2936
|
-
tier,
|
|
2937
|
-
dir,
|
|
2938
|
-
plugins: [],
|
|
2939
|
-
status
|
|
2940
|
-
});
|
|
2941
|
-
const self = [PACKAGE_PLUGIN];
|
|
2942
|
-
const harnesses = detectedHarnesses(env);
|
|
2943
|
-
const chain = projectChain(root);
|
|
2944
|
-
const ownRoot = canonical(packageRoot);
|
|
2945
|
-
const enabled = await enabledPluginLayers(harnesses, chain, {
|
|
2946
|
-
env,
|
|
2947
|
-
homedir: home,
|
|
2948
|
-
cwd: resolve(root),
|
|
2949
|
-
platform
|
|
2758
|
+
/** `@cyberuni/agent-harness`'s reference layers, with this package as the plugin whose own references come first. */
|
|
2759
|
+
function referenceLayers({ packageRoot = dirname(packageGovernancesDir()), ...options }) {
|
|
2760
|
+
return referenceLayers$1({
|
|
2761
|
+
...options,
|
|
2762
|
+
plugin: {
|
|
2763
|
+
name: PACKAGE_PLUGIN,
|
|
2764
|
+
root: packageRoot
|
|
2765
|
+
}
|
|
2950
2766
|
});
|
|
2951
|
-
const layers = [
|
|
2952
|
-
layer("managed", managedReferencesDir(platform, programData)),
|
|
2953
|
-
...harnessManagedLayers(harnesses, platform, env),
|
|
2954
|
-
layer("managed", managedGovernancesDir(platform, programData), LEGACY_STATUS),
|
|
2955
|
-
layer("managed", deprecatedManagedGovernancesDir(platform, programData), DEPRECATED_STATUS),
|
|
2956
|
-
...chain.flatMap(projectReferenceLayers),
|
|
2957
|
-
layer("user", join(home, ".agents", "references")),
|
|
2958
|
-
layer("user", join(home, ".agents", "governances"), LEGACY_STATUS),
|
|
2959
|
-
{
|
|
2960
|
-
tier: "plugin",
|
|
2961
|
-
dir: join(packageRoot, "references"),
|
|
2962
|
-
plugins: self,
|
|
2963
|
-
status: ""
|
|
2964
|
-
},
|
|
2965
|
-
{
|
|
2966
|
-
tier: "plugin",
|
|
2967
|
-
dir: join(packageRoot, "governances"),
|
|
2968
|
-
plugins: self,
|
|
2969
|
-
status: LEGACY_STATUS
|
|
2970
|
-
},
|
|
2971
|
-
...enabled.filter(({ dir, skipped }) => skipped || isDirectory$2(dir) && canonical(dirname(dir)) !== ownRoot),
|
|
2972
|
-
...dependencyLayers(root, /* @__PURE__ */ new Set([ownRoot]))
|
|
2973
|
-
];
|
|
2974
|
-
const seen = /* @__PURE__ */ new Set();
|
|
2975
|
-
return layers.filter(({ dir }) => !seen.has(dir) && seen.add(dir));
|
|
2976
2767
|
}
|
|
2768
|
+
const referenceCommand = createReferenceCommand({ plugin: {
|
|
2769
|
+
name: PACKAGE_PLUGIN,
|
|
2770
|
+
root: dirname(packageGovernancesDir())
|
|
2771
|
+
} });
|
|
2977
2772
|
//#endregion
|
|
2978
2773
|
//#region src/skill-projection/skill-projection.ts
|
|
2979
2774
|
function skillNames(skillsDirectory) {
|
|
@@ -3086,18 +2881,35 @@ function importsGlobal(body, bridge, home) {
|
|
|
3086
2881
|
const spellings = bridge.kind === "import" ? [bridge.line, `@${join(home, globalInstructions)}`] : [];
|
|
3087
2882
|
return body.split("\n").some((line) => spellings.includes(line.trim()));
|
|
3088
2883
|
}
|
|
3089
|
-
/**
|
|
3090
|
-
|
|
2884
|
+
/**
|
|
2885
|
+
* Follows `relocatedBy` the way each harness does. An empty value is no value to Codex and Copilot CLI
|
|
2886
|
+
* (E-CODEX-06, E-COPILOT-06), and the directory Claude Code starts in to Claude Code (E-CC-20).
|
|
2887
|
+
*/
|
|
2888
|
+
function base(scope, env, start) {
|
|
3091
2889
|
const variable = scope.relocatedBy;
|
|
3092
|
-
const
|
|
2890
|
+
const value = variable === void 0 ? void 0 : env[variable];
|
|
2891
|
+
if (variable === void 0 || value === void 0) return {};
|
|
2892
|
+
if (value !== "") return { moved: {
|
|
2893
|
+
root: resolve(value),
|
|
2894
|
+
display: `$${variable}`
|
|
2895
|
+
} };
|
|
2896
|
+
return scope.emptyRelocatesToStart ? {
|
|
2897
|
+
moved: {
|
|
2898
|
+
root: start,
|
|
2899
|
+
display: "."
|
|
2900
|
+
},
|
|
2901
|
+
emptied: variable
|
|
2902
|
+
} : {};
|
|
2903
|
+
}
|
|
2904
|
+
function locate(home, scope, { moved }, path) {
|
|
3093
2905
|
if (!moved || path !== scope.detect && !path.startsWith(`${scope.detect}/`)) return {
|
|
3094
2906
|
absolute: join(home, path),
|
|
3095
2907
|
display: `~/${path}`
|
|
3096
2908
|
};
|
|
3097
2909
|
const rest = path.slice(scope.detect.length);
|
|
3098
2910
|
return {
|
|
3099
|
-
absolute: join(
|
|
3100
|
-
display:
|
|
2911
|
+
absolute: join(moved.root, rest),
|
|
2912
|
+
display: `${moved.display}${rest}`
|
|
3101
2913
|
};
|
|
3102
2914
|
}
|
|
3103
2915
|
/** A shadow is read only where it is a file holding more than whitespace (E-CODEX-06). */
|
|
@@ -3157,10 +2969,11 @@ function finding(path, problem, cli) {
|
|
|
3157
2969
|
}
|
|
3158
2970
|
/**
|
|
3159
2971
|
* Whether each harness the user has installed loads `~/.agents/AGENTS.md` through its own user-scope
|
|
3160
|
-
* file, read from wherever `env` moves it
|
|
3161
|
-
*
|
|
2972
|
+
* file, read from wherever `env` moves it — `start`, for a harness that reads an empty variable as
|
|
2973
|
+
* the directory it starts in. Read-only: the repair is handed to the user, since nothing here
|
|
2974
|
+
* writes outside the repository.
|
|
3162
2975
|
*/
|
|
3163
|
-
function diagnoseGlobalInstructions(home, preferred, cli, env = {}) {
|
|
2976
|
+
function diagnoseGlobalInstructions(home, preferred, cli, env = {}, start = process.cwd()) {
|
|
3164
2977
|
const hasGlobal = exists$1(join(home, globalInstructions));
|
|
3165
2978
|
const rows = [];
|
|
3166
2979
|
const findings = [];
|
|
@@ -3168,10 +2981,11 @@ function diagnoseGlobalInstructions(home, preferred, cli, env = {}) {
|
|
|
3168
2981
|
const user = harness.user;
|
|
3169
2982
|
const bridge = user?.instructionBridge;
|
|
3170
2983
|
if (!user || !bridge) continue;
|
|
3171
|
-
|
|
3172
|
-
|
|
2984
|
+
const moved = base(user, env, start);
|
|
2985
|
+
if (!preferred.includes(harness.name) && !isDirectory$1(locate(home, user, moved, user.detect).absolute)) continue;
|
|
2986
|
+
const file = locate(home, user, moved, bridge.path);
|
|
3173
2987
|
const inspection = inspect$1(home, file.absolute, bridge);
|
|
3174
|
-
const shadow = (user.shadowedBy ?? []).map((path) => locate(home, user,
|
|
2988
|
+
const shadow = (user.shadowedBy ?? []).map((path) => locate(home, user, moved, path)).find(({ absolute }) => readsAsShadow(absolute));
|
|
3175
2989
|
if (shadow !== void 0) {
|
|
3176
2990
|
const read = inspect$1(home, shadow.absolute, bridge);
|
|
3177
2991
|
if (read.status === "ok") {
|
|
@@ -3196,7 +3010,8 @@ function diagnoseGlobalInstructions(home, preferred, cli, env = {}) {
|
|
|
3196
3010
|
kind: inspection.kind,
|
|
3197
3011
|
status: inspection.status
|
|
3198
3012
|
});
|
|
3199
|
-
if (hasGlobal &&
|
|
3013
|
+
if (hasGlobal && moved.emptied) findings.push(finding(`$${moved.emptied}`, "global-instructions-emptied", cli));
|
|
3014
|
+
else if (hasGlobal && inspection.problem) findings.push(finding(file.display, inspection.problem, cli));
|
|
3200
3015
|
}
|
|
3201
3016
|
return {
|
|
3202
3017
|
globalInstructions: rows,
|
|
@@ -3622,7 +3437,7 @@ function diagnoseBridges({ root, harnesses: preferred = [], cli, home, env }) {
|
|
|
3622
3437
|
const global = home === void 0 ? {
|
|
3623
3438
|
globalInstructions: [],
|
|
3624
3439
|
findings: []
|
|
3625
|
-
} : diagnoseGlobalInstructions(home, preferred, cli, env);
|
|
3440
|
+
} : diagnoseGlobalInstructions(home, preferred, cli, env, root);
|
|
3626
3441
|
findings.push(...global.findings);
|
|
3627
3442
|
return {
|
|
3628
3443
|
bridges,
|
|
@@ -3716,7 +3531,7 @@ const doctorCommand = command({
|
|
|
3716
3531
|
cli: commandInvocation
|
|
3717
3532
|
})
|
|
3718
3533
|
];
|
|
3719
|
-
const { rows } = listReferences(await referenceLayers({
|
|
3534
|
+
const { rows } = listReferences$1(await referenceLayers({
|
|
3720
3535
|
root,
|
|
3721
3536
|
home,
|
|
3722
3537
|
platform: process.platform,
|
|
@@ -3739,7 +3554,7 @@ const doctorCommand = command({
|
|
|
3739
3554
|
});
|
|
3740
3555
|
//#endregion
|
|
3741
3556
|
//#region src/governance-overrides/governance.command.ts
|
|
3742
|
-
function layersFor
|
|
3557
|
+
function layersFor(args) {
|
|
3743
3558
|
const layers = governanceLayers({
|
|
3744
3559
|
root: args.root ?? process.cwd(),
|
|
3745
3560
|
home: homedir(),
|
|
@@ -3750,7 +3565,7 @@ function layersFor$1(args) {
|
|
|
3750
3565
|
}
|
|
3751
3566
|
const GOVERNANCE_DEPRECATED = "warning: \"governance\" is deprecated and will be removed in the next major version; use \"reference show|list\" instead.\n";
|
|
3752
3567
|
const DEPRECATED_MANAGED = "deprecated — move these documents to the managed layer above";
|
|
3753
|
-
const rootOption
|
|
3568
|
+
const rootOption = {
|
|
3754
3569
|
description: "Repository or package directory. Defaults to the current directory.",
|
|
3755
3570
|
type: z.optional(z.string())
|
|
3756
3571
|
};
|
|
@@ -3762,7 +3577,7 @@ const governanceListCommand = command({
|
|
|
3762
3577
|
name: "list",
|
|
3763
3578
|
description: "List every governance the override layers hold, each at the layer that would win.",
|
|
3764
3579
|
options: {
|
|
3765
|
-
root: rootOption
|
|
3580
|
+
root: rootOption,
|
|
3766
3581
|
"overrides-only": overridesOnlyOption,
|
|
3767
3582
|
format: {
|
|
3768
3583
|
description: "Output format: toon (default), json, or text for a human-readable report.",
|
|
@@ -3775,7 +3590,7 @@ const governanceListCommand = command({
|
|
|
3775
3590
|
try {
|
|
3776
3591
|
const format = parseFormat(args.format);
|
|
3777
3592
|
const home = homedir();
|
|
3778
|
-
const layers = layersFor
|
|
3593
|
+
const layers = layersFor(args);
|
|
3779
3594
|
const entries = listGovernances(layers);
|
|
3780
3595
|
writeResult({
|
|
3781
3596
|
layers: layers.map(({ scope, dir }) => ({
|
|
@@ -3805,7 +3620,7 @@ const governanceShowCommand = command({
|
|
|
3805
3620
|
type: z.string()
|
|
3806
3621
|
}],
|
|
3807
3622
|
options: {
|
|
3808
|
-
root: rootOption
|
|
3623
|
+
root: rootOption,
|
|
3809
3624
|
"overrides-only": overridesOnlyOption,
|
|
3810
3625
|
format: {
|
|
3811
3626
|
description: "Output format: text (default) writes the document itself; toon and json wrap it with the layer it came from.",
|
|
@@ -3818,7 +3633,7 @@ const governanceShowCommand = command({
|
|
|
3818
3633
|
try {
|
|
3819
3634
|
const format = parseFormat(args.format);
|
|
3820
3635
|
const name = parseGovernanceName(args.name);
|
|
3821
|
-
const found = resolveGovernance(name, layersFor
|
|
3636
|
+
const found = resolveGovernance(name, layersFor(args));
|
|
3822
3637
|
if (!found) {
|
|
3823
3638
|
process.stderr.write(args["overrides-only"] ? `error: no override for governance "${name}" in the project, user, or machine-wide layer.\n` : `error: no governance named "${name}" in any layer.\n`);
|
|
3824
3639
|
return exitCodes.error;
|
|
@@ -3844,410 +3659,6 @@ const governanceCommand = command({
|
|
|
3844
3659
|
commands: [governanceListCommand, governanceShowCommand]
|
|
3845
3660
|
});
|
|
3846
3661
|
//#endregion
|
|
3847
|
-
//#region src/references/create-reference.ts
|
|
3848
|
-
/** No `#` title: `merge-sections` matches by heading path, so a title would hold every section under it. */
|
|
3849
|
-
const defaultTemplate = `---
|
|
3850
|
-
description: What this reference covers, and when an agent should read it.
|
|
3851
|
-
tags: [topic]
|
|
3852
|
-
---
|
|
3853
|
-
|
|
3854
|
-
## Overview
|
|
3855
|
-
|
|
3856
|
-
Write the guidance here. Give each topic its own top-level \`##\` section.
|
|
3857
|
-
`;
|
|
3858
|
-
function readTemplate(path) {
|
|
3859
|
-
if (path === void 0) return parseTemplate(defaultTemplate, "the default template");
|
|
3860
|
-
let content;
|
|
3861
|
-
try {
|
|
3862
|
-
content = readFileSync(path, "utf8");
|
|
3863
|
-
} catch (error) {
|
|
3864
|
-
throw new Error(`cannot read the template ${path}: ${error.message}`);
|
|
3865
|
-
}
|
|
3866
|
-
return parseTemplate(content, `the template ${path}`);
|
|
3867
|
-
}
|
|
3868
|
-
function parseTemplate(content, label) {
|
|
3869
|
-
let mapping = true;
|
|
3870
|
-
const { metadata, body } = parseDocument(content, () => {
|
|
3871
|
-
mapping = false;
|
|
3872
|
-
});
|
|
3873
|
-
if (!mapping) throw new Error(`${label} has frontmatter that is not a YAML mapping.`);
|
|
3874
|
-
return {
|
|
3875
|
-
content,
|
|
3876
|
-
metadata,
|
|
3877
|
-
body
|
|
3878
|
-
};
|
|
3879
|
-
}
|
|
3880
|
-
/** Adds one line and changes nothing else, so the result still reads as the template it came from. */
|
|
3881
|
-
function withMergeSections(content) {
|
|
3882
|
-
const match = frontmatterPattern.exec(content);
|
|
3883
|
-
if (!match) return `---\nmerge: merge-sections\n---\n\n${content}`;
|
|
3884
|
-
const open = match[0].indexOf("\n") + 1;
|
|
3885
|
-
const newline = match[0][open - 2] === "\r" ? "\r\n" : "\n";
|
|
3886
|
-
const end = open + match[1].length;
|
|
3887
|
-
return `${content.slice(0, end)}${newline}merge: merge-sections${content.slice(end)}`;
|
|
3888
|
-
}
|
|
3889
|
-
function templateWarnings({ metadata, body }) {
|
|
3890
|
-
const warnings = titleHeadings(body).map((heading) => `"${heading.trim()}" is a heading with one hash; merge-sections matches by heading path, so an override would replace or duplicate the whole document. Use top-level ## sections.`);
|
|
3891
|
-
if (typeof metadata["description"] !== "string" || !metadata["description"].trim()) warnings.push("the reference has no `description` in its frontmatter; `list` and `search` show it blank.");
|
|
3892
|
-
return warnings;
|
|
3893
|
-
}
|
|
3894
|
-
//#endregion
|
|
3895
|
-
//#region src/references/reference.command.ts
|
|
3896
|
-
const rootOption = {
|
|
3897
|
-
description: "Directory the project tier is read from, and each folder above it up to the repository root. Defaults to the current directory.",
|
|
3898
|
-
type: z.optional(z.string())
|
|
3899
|
-
};
|
|
3900
|
-
function layersFor(args, home) {
|
|
3901
|
-
return referenceLayers({
|
|
3902
|
-
root: args.root ?? process.cwd(),
|
|
3903
|
-
home,
|
|
3904
|
-
platform: process.platform,
|
|
3905
|
-
programData: process.env["ProgramData"],
|
|
3906
|
-
env: process.env
|
|
3907
|
-
});
|
|
3908
|
-
}
|
|
3909
|
-
function fail(error, fallback) {
|
|
3910
|
-
process.stderr.write(`error: ${error instanceof Error ? error.message : fallback}\n`);
|
|
3911
|
-
return exitCodes.error;
|
|
3912
|
-
}
|
|
3913
|
-
function traceOf(resolved, home) {
|
|
3914
|
-
return resolved.trace.map(({ description: _, ...step }) => ({
|
|
3915
|
-
...step,
|
|
3916
|
-
path: collapseHome(home, step.path)
|
|
3917
|
-
}));
|
|
3918
|
-
}
|
|
3919
|
-
function showEntry(resolved, home, suggestions, trace) {
|
|
3920
|
-
const entry = {
|
|
3921
|
-
name: resolved.name,
|
|
3922
|
-
status: resolved.status,
|
|
3923
|
-
warnings: []
|
|
3924
|
-
};
|
|
3925
|
-
if (resolved.status === "found") Object.assign(entry, {
|
|
3926
|
-
tier: resolved.tier,
|
|
3927
|
-
plugin: resolved.plugin,
|
|
3928
|
-
path: collapseHome(home, resolved.path),
|
|
3929
|
-
merge: resolved.merge,
|
|
3930
|
-
metadata: resolved.metadata,
|
|
3931
|
-
content: resolved.content,
|
|
3932
|
-
layers: resolved.layers.map((layer) => ({
|
|
3933
|
-
...layer,
|
|
3934
|
-
path: collapseHome(home, layer.path)
|
|
3935
|
-
}))
|
|
3936
|
-
});
|
|
3937
|
-
if (resolved.status === "missing") entry.suggestions = suggestions;
|
|
3938
|
-
if (resolved.status === "ambiguous") entry.plugins = resolved.plugins;
|
|
3939
|
-
entry.warnings = resolved.warnings;
|
|
3940
|
-
if (trace) entry.trace = traceOf(resolved, home);
|
|
3941
|
-
return entry;
|
|
3942
|
-
}
|
|
3943
|
-
function missReason(entry) {
|
|
3944
|
-
if (entry.status === "ambiguous") return `"${entry.name}" is held by more than one plugin; ask for one of ${entry.plugins.join(", ")}.`;
|
|
3945
|
-
const hint = entry.suggestions?.length ? ` Did you mean: ${entry.suggestions.join(", ")}?` : "";
|
|
3946
|
-
return `no reference named "${entry.name}" in any tier.${hint}`;
|
|
3947
|
-
}
|
|
3948
|
-
function writeShowText(entries) {
|
|
3949
|
-
if (entries.length === 1) {
|
|
3950
|
-
const [entry] = entries;
|
|
3951
|
-
if (entry.content !== void 0) writeDocument(entry.content);
|
|
3952
|
-
return;
|
|
3953
|
-
}
|
|
3954
|
-
writeDocument(entries.map((entry) => entry.content === void 0 ? `<reference name="${entry.name}" status="${entry.status}" />` : `<reference name="${entry.name}" tier="${entry.tier}">\n${entry.content}</reference>`).join("\n\n"));
|
|
3955
|
-
}
|
|
3956
|
-
function writeShowStderr(entries, format) {
|
|
3957
|
-
for (const entry of entries) {
|
|
3958
|
-
if (format === "text") {
|
|
3959
|
-
for (const warning of entry.warnings) process.stderr.write(`warning: ${warning}\n`);
|
|
3960
|
-
if (entry.trace) process.stderr.write(`${renderText({ [`trace ${entry.name}`]: entry.trace })}\n`);
|
|
3961
|
-
}
|
|
3962
|
-
if (entry.status !== "found") process.stderr.write(`error: ${missReason(entry)}\n`);
|
|
3963
|
-
}
|
|
3964
|
-
}
|
|
3965
|
-
const referenceShowCommand = command({
|
|
3966
|
-
name: "show",
|
|
3967
|
-
description: "Print one or more references, each resolved through the tiers and combined as its layers ask.",
|
|
3968
|
-
arguments: [{
|
|
3969
|
-
name: "names",
|
|
3970
|
-
description: "Reference names, without the `.md` extension; `<plugin>/<name>` picks one plugin.",
|
|
3971
|
-
type: z.array(z.string())
|
|
3972
|
-
}],
|
|
3973
|
-
options: {
|
|
3974
|
-
root: rootOption,
|
|
3975
|
-
trace: {
|
|
3976
|
-
description: "Report every path checked, the file that matched, the merge mode, and why a layer was dropped.",
|
|
3977
|
-
type: z.optional(z.boolean())
|
|
3978
|
-
},
|
|
3979
|
-
format: {
|
|
3980
|
-
description: "Output format: text (default) writes the documents themselves; toon and json return an array with metadata.",
|
|
3981
|
-
type: z.optional(z.string()),
|
|
3982
|
-
default: "text"
|
|
3983
|
-
}
|
|
3984
|
-
},
|
|
3985
|
-
async run(args) {
|
|
3986
|
-
try {
|
|
3987
|
-
const format = parseFormat(args.format);
|
|
3988
|
-
const names = args.names.map(parseReferenceName);
|
|
3989
|
-
if (!names.length) throw new Error("Name at least one reference.");
|
|
3990
|
-
const home = homedir();
|
|
3991
|
-
const layers = await layersFor(args, home);
|
|
3992
|
-
const display = (path) => collapseHome(home, path);
|
|
3993
|
-
const entries = names.map((name) => {
|
|
3994
|
-
const resolved = resolveReference(name, layers, { display });
|
|
3995
|
-
const suggestions = resolved.status === "missing" ? searchReferences(name.name, layers, { display }).slice(0, 3).map((match) => match.name) : [];
|
|
3996
|
-
return showEntry(resolved, home, suggestions, Boolean(args.trace));
|
|
3997
|
-
});
|
|
3998
|
-
if (format === "text") writeShowText(entries);
|
|
3999
|
-
else writeResult(entries, format);
|
|
4000
|
-
writeShowStderr(entries, format);
|
|
4001
|
-
return entries.every((entry) => entry.status === "found") ? exitCodes.success : exitCodes.error;
|
|
4002
|
-
} catch (error) {
|
|
4003
|
-
return fail(error, "Reference lookup failed.");
|
|
4004
|
-
}
|
|
4005
|
-
}
|
|
4006
|
-
});
|
|
4007
|
-
const listFormatOption = {
|
|
4008
|
-
description: "Output format: toon (default), json, or text for a human-readable report.",
|
|
4009
|
-
type: z.optional(z.string()),
|
|
4010
|
-
default: "toon"
|
|
4011
|
-
};
|
|
4012
|
-
const referenceListCommand = command({
|
|
4013
|
-
name: "list",
|
|
4014
|
-
description: "List every layer, and every reference at every layer that holds it, marked used or shadowed.",
|
|
4015
|
-
options: {
|
|
4016
|
-
root: rootOption,
|
|
4017
|
-
format: listFormatOption
|
|
4018
|
-
},
|
|
4019
|
-
async run(args) {
|
|
4020
|
-
try {
|
|
4021
|
-
const format = parseFormat(args.format);
|
|
4022
|
-
const home = homedir();
|
|
4023
|
-
const layers = await layersFor(args, home);
|
|
4024
|
-
const { rows, warnings } = listReferences(layers, { display: (path) => collapseHome(home, path) });
|
|
4025
|
-
const report = {
|
|
4026
|
-
layers: layers.map(({ tier, plugins, dir, status }) => ({
|
|
4027
|
-
tier,
|
|
4028
|
-
plugin: plugins[0] ?? "",
|
|
4029
|
-
path: collapseHome(home, dir),
|
|
4030
|
-
status
|
|
4031
|
-
})),
|
|
4032
|
-
references: rows.length ? rows.map((row) => ({
|
|
4033
|
-
...row,
|
|
4034
|
-
path: collapseHome(home, row.path)
|
|
4035
|
-
})) : "0 references — no layer holds one"
|
|
4036
|
-
};
|
|
4037
|
-
if (warnings.length) report.warnings = warnings;
|
|
4038
|
-
writeResult(report, format);
|
|
4039
|
-
return exitCodes.success;
|
|
4040
|
-
} catch (error) {
|
|
4041
|
-
return fail(error, "Reference listing failed.");
|
|
4042
|
-
}
|
|
4043
|
-
}
|
|
4044
|
-
});
|
|
4045
|
-
const referenceSearchCommand = command({
|
|
4046
|
-
name: "search",
|
|
4047
|
-
description: "Find references by name, description, tags, headings, or body, best match first.",
|
|
4048
|
-
arguments: [{
|
|
4049
|
-
name: "query",
|
|
4050
|
-
description: "What the reference is about.",
|
|
4051
|
-
type: z.string()
|
|
4052
|
-
}],
|
|
4053
|
-
options: {
|
|
4054
|
-
root: rootOption,
|
|
4055
|
-
format: listFormatOption
|
|
4056
|
-
},
|
|
4057
|
-
async run(args) {
|
|
4058
|
-
try {
|
|
4059
|
-
const format = parseFormat(args.format);
|
|
4060
|
-
const query = args.query.trim();
|
|
4061
|
-
if (!query) throw new Error("Search needs a query.");
|
|
4062
|
-
const home = homedir();
|
|
4063
|
-
const matches = searchReferences(query, await layersFor(args, home), { display: (path) => collapseHome(home, path) });
|
|
4064
|
-
writeResult({
|
|
4065
|
-
query,
|
|
4066
|
-
references: matches.length ? matches : `0 references match "${query}"`
|
|
4067
|
-
}, format);
|
|
4068
|
-
return exitCodes.success;
|
|
4069
|
-
} catch (error) {
|
|
4070
|
-
return fail(error, "Reference search failed.");
|
|
4071
|
-
}
|
|
4072
|
-
}
|
|
4073
|
-
});
|
|
4074
|
-
/** Managed is left out: writing there needs an admin, and most of it cannot be read locally. */
|
|
4075
|
-
const slotScopes = {
|
|
4076
|
-
project: "everyone working in this repository",
|
|
4077
|
-
user: "only you, in every repository",
|
|
4078
|
-
plugin: "read-only; override it with the project or user file"
|
|
4079
|
-
};
|
|
4080
|
-
const callerScope = "read-only; the calling skill's own copy, read only when no layer holds the name";
|
|
4081
|
-
const mergeNote = "The default, first-wins, makes the override replace the whole document. Set `merge: merge-sections` in its frontmatter to keep the sections it does not redefine.";
|
|
4082
|
-
function slotStatus(outcome) {
|
|
4083
|
-
if (outcome === "missing") return "empty";
|
|
4084
|
-
return outcome.startsWith("shadowed") ? "shadowed" : outcome;
|
|
4085
|
-
}
|
|
4086
|
-
/** Where Load reads the caller's copy when no layer holds the name, in the order it tries them. */
|
|
4087
|
-
function callerCopy(caller, name) {
|
|
4088
|
-
return [join(caller, "references", `${name}.md`), join(caller, "references", "governances", `${name}.md`)].find((path) => existsSync(path));
|
|
4089
|
-
}
|
|
4090
|
-
function callerStatus(resolved) {
|
|
4091
|
-
if (resolved.status === "missing") return "used";
|
|
4092
|
-
return resolved.status === "ambiguous" ? "not read — the name is ambiguous" : "shadowed";
|
|
4093
|
-
}
|
|
4094
|
-
const referenceWhereCommand = command({
|
|
4095
|
-
name: "where",
|
|
4096
|
-
description: "List the project and user files an override of a reference can be written to, highest precedence first, with the copy each overrides and who it applies to.",
|
|
4097
|
-
arguments: [{
|
|
4098
|
-
name: "name",
|
|
4099
|
-
description: "Reference name, without the `.md` extension; `<plugin>/<name>` picks one plugin.",
|
|
4100
|
-
type: z.string()
|
|
4101
|
-
}],
|
|
4102
|
-
options: {
|
|
4103
|
-
root: rootOption,
|
|
4104
|
-
caller: {
|
|
4105
|
-
description: "Folder of the skill that loads the reference, so its own copy is reported as the reference skill's Load mode reads it.",
|
|
4106
|
-
type: z.optional(z.string())
|
|
4107
|
-
},
|
|
4108
|
-
format: listFormatOption
|
|
4109
|
-
},
|
|
4110
|
-
async run(args) {
|
|
4111
|
-
try {
|
|
4112
|
-
const format = parseFormat(args.format);
|
|
4113
|
-
const name = parseReferenceName(args.name);
|
|
4114
|
-
const home = homedir();
|
|
4115
|
-
const layers = await layersFor(args, home);
|
|
4116
|
-
const root = resolve(args.root ?? process.cwd());
|
|
4117
|
-
const display = (path) => collapseHome(home, path);
|
|
4118
|
-
const resolved = resolveReference(name, layers, { display });
|
|
4119
|
-
const traced = layersFor$2(name, layers);
|
|
4120
|
-
const slots = [];
|
|
4121
|
-
for (const [index, step] of resolved.trace.entries()) {
|
|
4122
|
-
const layer = traced[index];
|
|
4123
|
-
const scope = slotScopes[step.tier];
|
|
4124
|
-
if (!scope || (layer.status || step.tier === "plugin") && !step.found) continue;
|
|
4125
|
-
const path = step.found ? step.path : join(layer.dir, `${name.name}.md`);
|
|
4126
|
-
slots.push({
|
|
4127
|
-
layer: step.tier === "plugin" ? `plugin ${step.plugin}` : step.tier,
|
|
4128
|
-
path: step.tier === "project" ? relative(root, path) : display(path),
|
|
4129
|
-
status: slotStatus(step.outcome),
|
|
4130
|
-
scope
|
|
4131
|
-
});
|
|
4132
|
-
}
|
|
4133
|
-
const copy = args.caller === void 0 ? void 0 : callerCopy(resolve(args.caller), name.name);
|
|
4134
|
-
if (copy) slots.push({
|
|
4135
|
-
layer: "caller",
|
|
4136
|
-
path: display(copy),
|
|
4137
|
-
status: callerStatus(resolved),
|
|
4138
|
-
scope: callerScope
|
|
4139
|
-
});
|
|
4140
|
-
const report = {
|
|
4141
|
-
name: name.name,
|
|
4142
|
-
root: display(root),
|
|
4143
|
-
slots,
|
|
4144
|
-
merge: mergeNote
|
|
4145
|
-
};
|
|
4146
|
-
if (resolved.status === "ambiguous") report.plugins = resolved.plugins;
|
|
4147
|
-
if (resolved.warnings.length) report.warnings = resolved.warnings;
|
|
4148
|
-
writeResult(report, format);
|
|
4149
|
-
if (resolved.status !== "ambiguous") return exitCodes.success;
|
|
4150
|
-
process.stderr.write(`error: ${missReason({
|
|
4151
|
-
name: name.raw,
|
|
4152
|
-
status: "ambiguous",
|
|
4153
|
-
plugins: resolved.plugins,
|
|
4154
|
-
warnings: []
|
|
4155
|
-
})}\n`);
|
|
4156
|
-
return exitCodes.error;
|
|
4157
|
-
} catch (error) {
|
|
4158
|
-
return fail(error, "Reference placement lookup failed.");
|
|
4159
|
-
}
|
|
4160
|
-
}
|
|
4161
|
-
});
|
|
4162
|
-
function parseScope(value) {
|
|
4163
|
-
if (value !== "project" && value !== "user") throw new Error("--scope must be project or user.");
|
|
4164
|
-
return value;
|
|
4165
|
-
}
|
|
4166
|
-
const referenceCreateCommand = command({
|
|
4167
|
-
name: "create",
|
|
4168
|
-
description: "Start a new reference in the project or user tier from a template, marked merge-sections when it overrides a copy below. Never overwrites.",
|
|
4169
|
-
arguments: [{
|
|
4170
|
-
name: "name",
|
|
4171
|
-
description: "Reference name, without the `.md` extension.",
|
|
4172
|
-
type: z.string()
|
|
4173
|
-
}],
|
|
4174
|
-
options: {
|
|
4175
|
-
root: rootOption,
|
|
4176
|
-
template: {
|
|
4177
|
-
description: "File whose text is written as it is, frontmatter included. Defaults to a built-in template of top-level `##` sections with no `#` title.",
|
|
4178
|
-
type: z.optional(z.string())
|
|
4179
|
-
},
|
|
4180
|
-
scope: {
|
|
4181
|
-
description: "Tier to write: project (default), `.agents/references/` at the root, or user, `~/.agents/references/`.",
|
|
4182
|
-
type: z.optional(z.string()),
|
|
4183
|
-
default: "project"
|
|
4184
|
-
},
|
|
4185
|
-
"dry-run": {
|
|
4186
|
-
description: "Print the target path and the exact content, and write nothing.",
|
|
4187
|
-
type: z.optional(z.boolean())
|
|
4188
|
-
},
|
|
4189
|
-
format: {
|
|
4190
|
-
description: "Output format: text (default) writes the path, then the content or the trace; toon and json return an object.",
|
|
4191
|
-
type: z.optional(z.string()),
|
|
4192
|
-
default: "text"
|
|
4193
|
-
}
|
|
4194
|
-
},
|
|
4195
|
-
async run(args) {
|
|
4196
|
-
try {
|
|
4197
|
-
const format = parseFormat(args.format);
|
|
4198
|
-
const name = parseReferenceName(args.name);
|
|
4199
|
-
if (name.plugin !== void 0) throw new Error(`an override is written under the bare name, which every tier resolves; ask for "${name.name}".`);
|
|
4200
|
-
const scope = parseScope(args.scope);
|
|
4201
|
-
const template = readTemplate(args.template === void 0 ? void 0 : resolve(args.template));
|
|
4202
|
-
const home = homedir();
|
|
4203
|
-
const dir = scope === "project" ? projectReferencesDir(resolve(args.root ?? process.cwd())) : join(home, ".agents", "references");
|
|
4204
|
-
const target = join(dir, `${name.name}.md`);
|
|
4205
|
-
const display = (path) => collapseHome(home, path);
|
|
4206
|
-
const layers = await layersFor(args, home);
|
|
4207
|
-
const { trace } = resolveReference(name, layers, { display });
|
|
4208
|
-
const at = layers.findIndex((layer) => layer.dir === dir);
|
|
4209
|
-
if (trace[at]?.found) throw new Error(`${display(trace[at].path)} already holds "${name.name}"; change it with the reference skill's Update mode.`);
|
|
4210
|
-
const shadow = trace.slice(0, at).find((step) => step.found && step.merge === "first-wins");
|
|
4211
|
-
if (shadow) throw new Error(`the ${shadow.tier} copy ${display(shadow.path)} is first-wins, so nothing would read a new ${scope} file; change that copy instead.`);
|
|
4212
|
-
const content = trace.slice(at + 1).some((step) => step.found) && template.metadata["merge"] === void 0 ? withMergeSections(template.content) : template.content;
|
|
4213
|
-
const warnings = templateWarnings(template);
|
|
4214
|
-
const report = {
|
|
4215
|
-
name: name.name,
|
|
4216
|
-
scope,
|
|
4217
|
-
path: display(target),
|
|
4218
|
-
dryRun: Boolean(args["dry-run"]),
|
|
4219
|
-
content,
|
|
4220
|
-
warnings
|
|
4221
|
-
};
|
|
4222
|
-
if (!report.dryRun) {
|
|
4223
|
-
mkdirSync(dir, { recursive: true });
|
|
4224
|
-
writeFileSync(target, content, { flag: "wx" });
|
|
4225
|
-
report.trace = traceOf(resolveReference(name, layers, { display }), home);
|
|
4226
|
-
}
|
|
4227
|
-
if (format !== "text") writeResult(report, format);
|
|
4228
|
-
else {
|
|
4229
|
-
for (const warning of warnings) process.stderr.write(`warning: ${warning}\n`);
|
|
4230
|
-
if (report.trace) process.stdout.write(`${report.path}\n\n${renderText({ trace: report.trace })}\n`);
|
|
4231
|
-
else writeDocument(`${report.path}\n\n${content}`);
|
|
4232
|
-
}
|
|
4233
|
-
return exitCodes.success;
|
|
4234
|
-
} catch (error) {
|
|
4235
|
-
return fail(error, "Reference creation failed.");
|
|
4236
|
-
}
|
|
4237
|
-
}
|
|
4238
|
-
});
|
|
4239
|
-
const referenceCommand = command({
|
|
4240
|
-
name: "reference",
|
|
4241
|
-
description: "Read on-demand reference documents by name, layered across the managed, project, user, and plugin tiers, and start a new one in the project or user tier.",
|
|
4242
|
-
commands: [
|
|
4243
|
-
referenceShowCommand,
|
|
4244
|
-
referenceListCommand,
|
|
4245
|
-
referenceSearchCommand,
|
|
4246
|
-
referenceWhereCommand,
|
|
4247
|
-
referenceCreateCommand
|
|
4248
|
-
]
|
|
4249
|
-
});
|
|
4250
|
-
//#endregion
|
|
4251
3662
|
//#region src/initialize-harnesses/initialize-harnesses.ts
|
|
4252
3663
|
function initializeHarnesses({ root, harnesses: preferred = [], copy = false, force = false }) {
|
|
4253
3664
|
const canonicalSkills = join(root, ".agents", "skills");
|
|
@@ -5346,7 +4757,7 @@ function claudeLocalEntries(home, projectDir) {
|
|
|
5346
4757
|
return entriesFromDocument("claude-code", "local", file, project, "mcpServers");
|
|
5347
4758
|
}
|
|
5348
4759
|
/** `enabledPlugins`, merged from global settings up through project-local settings, last write wins. */
|
|
5349
|
-
function enabledPlugins
|
|
4760
|
+
function enabledPlugins(home, projectDir) {
|
|
5350
4761
|
const enabled = {};
|
|
5351
4762
|
for (const file of [
|
|
5352
4763
|
join(home, ".claude", "settings.json"),
|
|
@@ -5372,7 +4783,7 @@ function pluginEntries(home, projectDir) {
|
|
|
5372
4783
|
const document = parseJsonWithComments(text);
|
|
5373
4784
|
const installed = isRecord(document) ? document["plugins"] : void 0;
|
|
5374
4785
|
if (!isRecord(installed)) return [];
|
|
5375
|
-
const enabled = enabledPlugins
|
|
4786
|
+
const enabled = enabledPlugins(home, projectDir);
|
|
5376
4787
|
const absoluteProject = resolve(projectDir);
|
|
5377
4788
|
const entries = [];
|
|
5378
4789
|
for (const [id, list] of Object.entries(installed)) {
|