@kirkchinese/harness-forge-core 0.4.0 → 0.5.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.
Files changed (56) hide show
  1. package/lib/assess.js +24 -4
  2. package/lib/contracts.d.ts +1 -1
  3. package/lib/dialects/claude-code/index.js +38 -41
  4. package/lib/dialects/claude-code/sessions/discover.js +31 -17
  5. package/lib/dialects/claude-code/sessions/parse.js +89 -83
  6. package/lib/dialects/claude-code/sessions/title.d.ts +23 -0
  7. package/lib/dialects/claude-code/sessions/title.js +74 -0
  8. package/lib/dialects/claude-code/statusline.d.ts +12 -0
  9. package/lib/dialects/claude-code/statusline.js +74 -0
  10. package/lib/dialects/claude-code/user-assets.d.ts +37 -6
  11. package/lib/dialects/claude-code/user-assets.js +155 -34
  12. package/lib/dialects/codex/index.js +8 -1
  13. package/lib/dialects/codex/mcp-server.d.ts +17 -0
  14. package/lib/dialects/codex/mcp-server.js +116 -0
  15. package/lib/dialects/codex/plugins.d.ts +16 -0
  16. package/lib/dialects/codex/plugins.js +120 -0
  17. package/lib/dialects/codex/user-assets.d.ts +10 -6
  18. package/lib/dialects/codex/user-assets.js +26 -42
  19. package/lib/dialects/opencode/index.js +43 -8
  20. package/lib/dialects/opencode/inventory.d.ts +100 -0
  21. package/lib/dialects/opencode/inventory.js +318 -0
  22. package/lib/dialects/opencode/plugin-id.d.ts +21 -0
  23. package/lib/dialects/opencode/plugin-id.js +296 -0
  24. package/lib/dialects/opencode/scan.d.ts +22 -0
  25. package/lib/dialects/opencode/scan.js +119 -121
  26. package/lib/dialects/types.d.ts +60 -6
  27. package/lib/discover.d.ts +32 -7
  28. package/lib/discover.js +58 -17
  29. package/lib/fingerprint.js +7 -0
  30. package/lib/harness-installs.d.ts +42 -0
  31. package/lib/harness-installs.js +59 -0
  32. package/lib/index.d.ts +6 -0
  33. package/lib/index.js +5 -0
  34. package/lib/instructions.d.ts +28 -2
  35. package/lib/instructions.js +202 -30
  36. package/lib/license.js +12 -11
  37. package/lib/manifest.d.ts +6 -0
  38. package/lib/manifest.js +41 -12
  39. package/lib/marketplace.d.ts +15 -1
  40. package/lib/marketplace.js +55 -38
  41. package/lib/paths.d.ts +65 -0
  42. package/lib/paths.js +152 -2
  43. package/lib/plan.js +3 -1
  44. package/lib/port-brief.d.ts +28 -5
  45. package/lib/port-brief.js +52 -10
  46. package/lib/remote.d.ts +121 -0
  47. package/lib/remote.js +352 -0
  48. package/lib/sessions/index.d.ts +1 -0
  49. package/lib/sessions/index.js +1 -0
  50. package/lib/sessions/lines.d.ts +57 -0
  51. package/lib/sessions/lines.js +122 -0
  52. package/lib/text.d.ts +9 -0
  53. package/lib/text.js +19 -0
  54. package/lib/trust.js +19 -6
  55. package/lib/types.d.ts +48 -1
  56. package/package.json +1 -1
@@ -0,0 +1,42 @@
1
+ import type { SourceId } from './types.js';
2
+ /** One plugin a harness has installed. */
3
+ export interface HarnessInstall {
4
+ readonly harness: SourceId;
5
+ /** `HarnessPluginEntry.key`: `<name>@<marketplace>`, or OpenCode's package folder. */
6
+ readonly key: string;
7
+ readonly root: string;
8
+ /** `false` when the harness has it switched off; absent when on, or when that cannot be told. */
9
+ readonly enabled?: false;
10
+ }
11
+ /** Every harness's installs, and how much of each harness's record could be read. */
12
+ export interface HarnessInstalls {
13
+ readonly installs: readonly HarnessInstall[];
14
+ /**
15
+ * Harnesses whose record, or one of its entries, could not be read: a plugin missing from what they list may only
16
+ * be unreadable, so its absence proves nothing. Why is in `unread`.
17
+ */
18
+ readonly uncertain: ReadonlySet<SourceId>;
19
+ /** Installs a harness records whose files are not where it says: still installed, not followable now. */
20
+ readonly unresolved: ReadonlyArray<{
21
+ readonly harness: SourceId;
22
+ readonly key: string;
23
+ readonly message: string;
24
+ }>;
25
+ /** What of each harness's record could not be read, each saying why. */
26
+ readonly unread: ReadonlyArray<{
27
+ readonly harness: SourceId;
28
+ readonly message: string;
29
+ }>;
30
+ }
31
+ /** Read what every harness has installed now. */
32
+ export declare function harnessInstalls(home?: string): HarnessInstalls;
33
+ /**
34
+ * The harness install a plugin folder is: one a harness lists at that folder, else one its layout spells out
35
+ * (`inferred`: a version the harness may no longer list, or a marketplace offer it never installed).
36
+ * @param name - the plugin's own name, for a layout that does not spell it.
37
+ */
38
+ export declare function identifyHarnessInstall(root: string, name: string, current: HarnessInstalls, home?: string): {
39
+ readonly harness: SourceId;
40
+ readonly key: string;
41
+ readonly inferred?: true;
42
+ } | undefined;
@@ -0,0 +1,59 @@
1
+ /**
2
+ * What each harness has installed right now, by the key it knows an install
3
+ * by across updates: the readers discovery uses (`installed_plugins.json`,
4
+ * Codex's `config.toml`, the OpenCode inventory), read for every harness
5
+ * whatever the discovery folders are. A migrated plugin follows its harness
6
+ * through this: to the folder of a new version, or out when it is uninstalled.
7
+ * @module @kirkchinese/harness-forge-core
8
+ */
9
+ import { homedir } from 'node:os';
10
+ import { resolve } from 'node:path';
11
+ import { dialects } from './dialects/registry.js';
12
+ /** Read what every harness has installed now. */
13
+ export function harnessInstalls(home = homedir()) {
14
+ const installs = [];
15
+ const unresolved = [];
16
+ const unread = [];
17
+ for (const dialect of dialects()) {
18
+ const recorded = dialect.harnessPlugins;
19
+ if (recorded === undefined)
20
+ continue;
21
+ for (const folder of recorded.roots(home)) {
22
+ try {
23
+ const listed = recorded.list(home, folder);
24
+ for (const message of listed.unread)
25
+ unread.push({ harness: dialect.id, message });
26
+ for (const item of listed.unresolved)
27
+ unresolved.push({ harness: dialect.id, ...item });
28
+ for (const entry of listed.entries) {
29
+ if (installs.some(known => known.harness === dialect.id && known.key === entry.key))
30
+ continue;
31
+ installs.push({ harness: dialect.id, key: entry.key, root: resolve(entry.root), ...(entry.enabled === false ? { enabled: false } : {}) });
32
+ }
33
+ }
34
+ catch (error) {
35
+ unread.push({ harness: dialect.id, message: `${folder}: ${error instanceof Error ? error.message : String(error)}` });
36
+ }
37
+ }
38
+ }
39
+ return { installs, uncertain: new Set(unread.map(item => item.harness)), unresolved, unread };
40
+ }
41
+ /**
42
+ * The harness install a plugin folder is: one a harness lists at that folder, else one its layout spells out
43
+ * (`inferred`: a version the harness may no longer list, or a marketplace offer it never installed).
44
+ * @param name - the plugin's own name, for a layout that does not spell it.
45
+ */
46
+ export function identifyHarnessInstall(root, name, current, home = homedir()) {
47
+ const listed = current.installs.find(install => samePath(install.root, root));
48
+ if (listed !== undefined)
49
+ return { harness: listed.harness, key: listed.key };
50
+ for (const dialect of dialects()) {
51
+ const key = dialect.harnessPlugins?.identify?.(home, root, name);
52
+ if (key !== undefined)
53
+ return { harness: dialect.id, key, inferred: true };
54
+ }
55
+ return undefined;
56
+ }
57
+ function samePath(a, b) {
58
+ return process.platform === 'win32' ? resolve(a).toLowerCase() === resolve(b).toLowerCase() : resolve(a) === resolve(b);
59
+ }
package/lib/index.d.ts CHANGED
@@ -5,6 +5,7 @@
5
5
  */
6
6
  export * from './types.js';
7
7
  export * from './naming.js';
8
+ export * from './text.js';
8
9
  export * from './paths.js';
9
10
  export * from './frontmatter.js';
10
11
  export * from './manifest.js';
@@ -12,17 +13,22 @@ export * from './schema.js';
12
13
  export * from './assess.js';
13
14
  export * from './hook-events.js';
14
15
  export * from './marketplace.js';
16
+ export * from './remote.js';
15
17
  export * from './dialects/opencode/scan.js';
18
+ export type { PluginIdProblem, PluginIdRead } from './dialects/opencode/plugin-id.js';
16
19
  export * from './contracts.js';
17
20
  export * from './fingerprint.js';
18
21
  export * from './plan.js';
19
22
  export * from './license.js';
20
23
  export * from './port-brief.js';
21
24
  export * from './discover.js';
25
+ export * from './harness-installs.js';
22
26
  export * from './dialects/index.js';
23
27
  export * from './dialects/claude-code/user-assets.js';
28
+ export * from './dialects/claude-code/statusline.js';
24
29
  export * from './dialects/codex/user-assets.js';
25
30
  export * from './dialects/codex/skill-policy.js';
31
+ export * from './dialects/codex/mcp-server.js';
26
32
  export * from './sessions/index.js';
27
33
  export * from './instructions.js';
28
34
  export * from './trust.js';
package/lib/index.js CHANGED
@@ -5,6 +5,7 @@
5
5
  */
6
6
  export * from './types.js';
7
7
  export * from './naming.js';
8
+ export * from './text.js';
8
9
  export * from './paths.js';
9
10
  export * from './frontmatter.js';
10
11
  export * from './manifest.js';
@@ -12,6 +13,7 @@ export * from './schema.js';
12
13
  export * from './assess.js';
13
14
  export * from './hook-events.js';
14
15
  export * from './marketplace.js';
16
+ export * from './remote.js';
15
17
  export * from './dialects/opencode/scan.js';
16
18
  export * from './contracts.js';
17
19
  export * from './fingerprint.js';
@@ -19,10 +21,13 @@ export * from './plan.js';
19
21
  export * from './license.js';
20
22
  export * from './port-brief.js';
21
23
  export * from './discover.js';
24
+ export * from './harness-installs.js';
22
25
  export * from './dialects/index.js';
23
26
  export * from './dialects/claude-code/user-assets.js';
27
+ export * from './dialects/claude-code/statusline.js';
24
28
  export * from './dialects/codex/user-assets.js';
25
29
  export * from './dialects/codex/skill-policy.js';
30
+ export * from './dialects/codex/mcp-server.js';
26
31
  export * from './sessions/index.js';
27
32
  export * from './instructions.js';
28
33
  export * from './trust.js';
@@ -2,6 +2,27 @@
2
2
  export declare const MAX_IMPORT_DEPTH = 5;
3
3
  /** The default cap on the text one rendering carries. */
4
4
  export declare const DEFAULT_INSTRUCTION_BYTES = 65536;
5
+ /**
6
+ * The bytes one load reads from all its files together: a rendering keeps at
7
+ * most {@link DEFAULT_INSTRUCTION_BYTES} (64 KiB), so 4 MiB leaves room for
8
+ * four maximal files or hundreds of ordinary ones, while a cloned repository
9
+ * full of permitted imports cannot make each session start read gigabytes.
10
+ */
11
+ export declare const INSTRUCTION_READ_BYTES: number;
12
+ /**
13
+ * The paths one load tries: every candidate path costs one, whether it is
14
+ * missing, refused, binary or read. Real setups try a few paths per directory
15
+ * and a handful of imports; 256 is far beyond that, and bounds the filesystem
16
+ * work a crafted import graph (thousands of missing imports included) can
17
+ * cause on every prompt.
18
+ */
19
+ export declare const INSTRUCTION_PATHS_TRIED = 256;
20
+ /**
21
+ * The unused files one load lists with their reasons (`skipped`); the rest are
22
+ * only counted (`skippedUnlisted`). 32 names every problem a real setup has
23
+ * and keeps the diagnostics small when a crafted file imports thousands.
24
+ */
25
+ export declare const INSTRUCTION_SKIPS_LISTED = 32;
5
26
  export type InstructionKind = 'user' | 'codex' | 'project' | 'local' | 'import';
6
27
  /** One instruction file to add to a prompt. */
7
28
  export interface InstructionFile {
@@ -31,11 +52,15 @@ export interface InstructionSet {
31
52
  readonly path: string;
32
53
  readonly bytes: number;
33
54
  }[];
34
- /** Files that exist but were not used, with the reason. */
55
+ /** Files that exist but were not used, with the reason: at most {@link INSTRUCTION_SKIPS_LISTED}. */
35
56
  readonly skipped: readonly {
36
57
  readonly path: string;
37
58
  readonly reason: string;
38
59
  }[];
60
+ /** How many more files were not used than `skipped` lists. */
61
+ readonly skippedUnlisted: number;
62
+ /** Set when reading stopped at a limit: a note saying so, for the prompt and the workbench. */
63
+ readonly stopped?: string;
39
64
  /** The directory the project's files are read down from. */
40
65
  readonly root: string;
41
66
  }
@@ -63,5 +88,6 @@ export interface RenderedInstructions {
63
88
  /**
64
89
  * Frame the files as prompt text under a byte budget. When they do not fit, the
65
90
  * broadest files are left out first and the last one is cut; a note names both.
91
+ * @param stopped - the note of a load that stopped at a limit (`InstructionSet.stopped`), added at the end.
66
92
  */
67
- export declare function renderInstructions(files: readonly InstructionFile[], maxBytes?: number): RenderedInstructions;
93
+ export declare function renderInstructions(files: readonly InstructionFile[], maxBytes?: number, stopped?: string): RenderedInstructions;
@@ -27,17 +27,49 @@
27
27
  * A project file that is a symbolic link resolving outside the workspace is
28
28
  * skipped as well. Files the user wrote themselves (`~/.claude/CLAUDE.md`, `~/.codex`) may
29
29
  * import from anywhere.
30
+ *
31
+ * Each file is opened once, and what is checked is what is read: the
32
+ * containment check uses the opened file's own real path (see `openFile`),
33
+ * and the content comes from that descriptor. Reading runs for every
34
+ * workspace, trusted or not, so one load reads at most
35
+ * {@link INSTRUCTION_READ_BYTES} bytes (a binary file's included) while trying
36
+ * at most {@link INSTRUCTION_PATHS_TRIED} paths (a missing one included), and
37
+ * lists at most {@link INSTRUCTION_SKIPS_LISTED} files it did not use; past a
38
+ * limit it stops, says so (`stopped`) and touches the filesystem no more.
30
39
  * @module @kirkchinese/harness-forge-core
31
40
  */
32
- import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs';
41
+ import { closeSync, constants, existsSync, fstatSync, openSync, readlinkSync, readSync, realpathSync, statSync } from 'node:fs';
33
42
  import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
34
43
  import { claudeExternalImportsApproved, workspaceRootOf } from './trust.js';
44
+ import { linksReachNewShare, reachesNewShare } from './paths.js';
45
+ import { stripTrailing } from './text.js';
35
46
  /** How deep `@path` imports nest (Claude Code's limit). */
36
47
  export const MAX_IMPORT_DEPTH = 5;
37
48
  /** The default cap on the text one rendering carries. */
38
49
  export const DEFAULT_INSTRUCTION_BYTES = 65_536;
39
50
  /** A source file larger than this is not read. */
40
51
  const MAX_SOURCE_BYTES = 1_048_576;
52
+ /**
53
+ * The bytes one load reads from all its files together: a rendering keeps at
54
+ * most {@link DEFAULT_INSTRUCTION_BYTES} (64 KiB), so 4 MiB leaves room for
55
+ * four maximal files or hundreds of ordinary ones, while a cloned repository
56
+ * full of permitted imports cannot make each session start read gigabytes.
57
+ */
58
+ export const INSTRUCTION_READ_BYTES = 4 * 1_048_576;
59
+ /**
60
+ * The paths one load tries: every candidate path costs one, whether it is
61
+ * missing, refused, binary or read. Real setups try a few paths per directory
62
+ * and a handful of imports; 256 is far beyond that, and bounds the filesystem
63
+ * work a crafted import graph (thousands of missing imports included) can
64
+ * cause on every prompt.
65
+ */
66
+ export const INSTRUCTION_PATHS_TRIED = 256;
67
+ /**
68
+ * The unused files one load lists with their reasons (`skipped`); the rest are
69
+ * only counted (`skippedUnlisted`). 32 names every problem a real setup has
70
+ * and keeps the diagnostics small when a crafted file imports thousands.
71
+ */
72
+ export const INSTRUCTION_SKIPS_LISTED = 32;
41
73
  function isFileAt(path) {
42
74
  try {
43
75
  return statSync(path).isFile();
@@ -105,17 +137,76 @@ export function importPaths(text) {
105
137
  }
106
138
  return found;
107
139
  }
108
- function readSource(path) {
140
+ /** `O_NOFOLLOW` where the platform has it (not Windows): the last part of the path must not be a link. */
141
+ const NO_FOLLOW = constants.O_NOFOLLOW ?? 0;
142
+ /** `O_NONBLOCK` where the platform has it: a FIFO swapped in after the check does not hold the open. */
143
+ const NO_BLOCK = constants.O_NONBLOCK ?? 0;
144
+ /**
145
+ * Open the regular file `path` resolves to, once: the real path is opened
146
+ * without following a link in its last part, and the real path reported is
147
+ * the opened file's own (Linux: `/proc/self/fd`; elsewhere the real path,
148
+ * accepted only if it still names the file opened, by device and inode).
149
+ * Undefined when there is no such file, or it changed while being opened.
150
+ *
151
+ * Residual risk without `/proc` (macOS, Windows): the real path and the
152
+ * identity check are separate path operations, so a local process running at
153
+ * the same time that swaps a parent directory for a link between them could
154
+ * make a file outside the allowed place pass as the one inside it. Failing
155
+ * closed there would stop instruction files from loading on those systems, so
156
+ * the gap is documented (docs/user/compatibility.md, next to the hook input
157
+ * file note) instead.
158
+ */
159
+ function openFile(path) {
160
+ let fd;
109
161
  try {
110
- if (statSync(path).size > MAX_SOURCE_BYTES)
162
+ const resolved = realpathSync(path);
163
+ if (!statSync(resolved).isFile())
111
164
  return undefined;
112
- const text = readFileSync(path, 'utf8');
113
- return text.includes('\0') ? undefined : text;
165
+ fd = openSync(resolved, constants.O_RDONLY | NO_FOLLOW | NO_BLOCK);
166
+ }
167
+ catch {
168
+ return undefined;
169
+ }
170
+ try {
171
+ const stat = fstatSync(fd);
172
+ if (!stat.isFile())
173
+ throw new Error('not a regular file');
174
+ const identity = `${String(stat.dev)}:${String(stat.ino)}`;
175
+ let real;
176
+ try {
177
+ real = readlinkSync(`/proc/self/fd/${String(fd)}`);
178
+ }
179
+ catch {
180
+ real = realpathSync(path);
181
+ const named = statSync(real);
182
+ if (`${String(named.dev)}:${String(named.ino)}` !== identity)
183
+ throw new Error('the file changed while it was opened');
184
+ }
185
+ return { fd, real, identity, size: stat.size };
114
186
  }
115
187
  catch {
188
+ closeSync(fd);
116
189
  return undefined;
117
190
  }
118
191
  }
192
+ /**
193
+ * Up to `limit` bytes of an open file: the bytes read, whatever they were,
194
+ * and the text, undefined when it is binary or longer than `limit`.
195
+ */
196
+ function readOpen(file, limit) {
197
+ const buffer = Buffer.alloc(Math.min(file.size, limit) + 1);
198
+ let length = 0;
199
+ for (;;) {
200
+ const count = readSync(file.fd, buffer, length, buffer.length - length, length);
201
+ if (count === 0)
202
+ break;
203
+ length += count;
204
+ if (length === buffer.length)
205
+ return { text: undefined, bytes: length };
206
+ }
207
+ const text = buffer.subarray(0, length).toString('utf8');
208
+ return { text: text.includes('\0') ? undefined : text, bytes: length };
209
+ }
119
210
  function realPath(path) {
120
211
  try {
121
212
  return realpathSync(path);
@@ -155,28 +246,103 @@ export function loadInstructions(options) {
155
246
  const files = [];
156
247
  const hostFiles = [];
157
248
  const skipped = [];
249
+ let skippedUnlisted = 0;
250
+ const skip = (path, reason) => {
251
+ if (skipped.length < INSTRUCTION_SKIPS_LISTED)
252
+ skipped.push({ path, reason });
253
+ else
254
+ skippedUnlisted++;
255
+ };
158
256
  const seen = new Set();
159
257
  const external = claudeExternalImportsApproved(workspaceRootOf(cwd), home);
160
258
  const allowedFor = (trusted, path) => trusted || external || within(workspace, path);
161
- const visit = (path, source, depth, importedBy, kind) => {
162
- const real = realPath(path);
163
- if (!isFileAt(path))
164
- return;
165
- if (importedBy === undefined && source.within !== undefined && !within(source.within, real)) {
166
- skipped.push({ path, reason: 'a link to a file outside the workspace' });
167
- return;
259
+ let tried = 0;
260
+ let read = 0;
261
+ let stopped;
262
+ const stop = (limit, path) => {
263
+ stopped = `Harness Forge stopped reading instruction files at ${path}: ${limit}. Files after it, and their imports, were not read.`;
264
+ };
265
+ /** Charge one path about to be tried; false, before any filesystem work, once the budget is spent. */
266
+ const attempt = (path) => {
267
+ if (stopped !== undefined)
268
+ return false;
269
+ if (tried >= INSTRUCTION_PATHS_TRIED) {
270
+ stop(`more than ${String(INSTRUCTION_PATHS_TRIED)} paths tried`, path);
271
+ return false;
272
+ }
273
+ tried++;
274
+ return true;
275
+ };
276
+ /** Whether a file at its real path may be used: a source must stay where it was found, an import inside the workspace. */
277
+ const refusal = (real, source, importedBy) => {
278
+ if (importedBy === undefined && source.within !== undefined && !within(source.within, real))
279
+ return 'a link to a file outside the workspace';
280
+ if (importedBy !== undefined && !allowedFor(source.trusted, real))
281
+ return 'an import outside the workspace';
282
+ return undefined;
283
+ };
284
+ /** Use the first of `candidates` that is a file; each one tried is charged, missing or not. */
285
+ /**
286
+ * Whether a project file's path, or a link on its way, leads to a network share the workspace is not on: on
287
+ * Windows, touching it would sign in to that server, so nothing is opened, resolved or even stat'ed there
288
+ * (`linksReachNewShare` reads links with `lstat` and `readlink` only). The user's own files are theirs to point
289
+ * anywhere.
290
+ */
291
+ const offShare = (path, source) => !source.trusted && linksReachNewShare(path, workspace);
292
+ const visit = (candidates, source, depth, importedBy, kind) => {
293
+ let path;
294
+ for (const candidate of candidates) {
295
+ if (!attempt(candidate))
296
+ return;
297
+ if (offShare(candidate, source)) {
298
+ skip(candidate, importedBy === undefined ? 'a link to a file outside the workspace' : 'an import outside the workspace');
299
+ return;
300
+ }
301
+ if (isFileAt(candidate)) {
302
+ path = candidate;
303
+ break;
304
+ }
168
305
  }
169
- if (seen.has(real))
306
+ if (path === undefined)
170
307
  return;
171
- seen.add(real);
172
- if (importedBy !== undefined && !allowedFor(source.trusted, real)) {
173
- skipped.push({ path, reason: 'an import outside the workspace' });
308
+ // Refuse what is plainly out of bounds before opening it; the opened file is checked again below.
309
+ const before = refusal(realPath(path), source, importedBy);
310
+ if (before !== undefined) {
311
+ skip(path, before);
174
312
  return;
175
313
  }
176
- const content = readSource(path);
177
- if (content === undefined) {
178
- skipped.push({ path, reason: 'unreadable, binary, or larger than 1 MiB' });
314
+ const file = openFile(path);
315
+ if (file === undefined)
179
316
  return;
317
+ let content;
318
+ try {
319
+ const after = refusal(file.real, source, importedBy);
320
+ if (after !== undefined) {
321
+ skip(path, after);
322
+ return;
323
+ }
324
+ if (seen.has(file.identity))
325
+ return;
326
+ seen.add(file.identity);
327
+ if (file.size > MAX_SOURCE_BYTES) {
328
+ skip(path, 'unreadable, binary, or larger than 1 MiB');
329
+ return;
330
+ }
331
+ if (read + file.size > INSTRUCTION_READ_BYTES) {
332
+ stop(`more than ${String(INSTRUCTION_READ_BYTES)} bytes in all`, path);
333
+ return;
334
+ }
335
+ const text = readOpen(file, Math.min(MAX_SOURCE_BYTES, INSTRUCTION_READ_BYTES - read));
336
+ // What was read counts, text or not.
337
+ read += text.bytes;
338
+ if (text.text === undefined) {
339
+ skip(path, 'unreadable, binary, or larger than 1 MiB');
340
+ return;
341
+ }
342
+ content = text.text;
343
+ }
344
+ finally {
345
+ closeSync(file.fd);
180
346
  }
181
347
  const bytes = Buffer.byteLength(content);
182
348
  if (source.hostLoaded && importedBy === undefined)
@@ -187,24 +353,29 @@ export function loadInstructions(options) {
187
353
  return;
188
354
  if (depth >= MAX_IMPORT_DEPTH) {
189
355
  if (importPaths(content).length > 0)
190
- skipped.push({ path, reason: `imports nest deeper than ${String(MAX_IMPORT_DEPTH)} levels` });
356
+ skip(path, `imports nest deeper than ${String(MAX_IMPORT_DEPTH)} levels`);
191
357
  return;
192
358
  }
193
359
  for (const reference of importPaths(content)) {
360
+ if (stopped !== undefined)
361
+ return;
194
362
  if (reference.startsWith('~') && !reference.startsWith('~/'))
195
363
  continue;
364
+ // A share named as written (`//server/share/x`, `\\\\server\\share\\x`): refused before it is resolved or touched.
365
+ if (!source.trusted && reachesNewShare(reference, workspace)) {
366
+ skip(reference, 'an import outside the workspace');
367
+ continue;
368
+ }
196
369
  // "see @notes.md." names notes.md: a trailing sentence mark is not part of the path unless the file has it.
197
- const target = [reference, reference.replace(/[.,;:!?)\]]+$/u, '')]
370
+ const candidates = [...new Set([reference, stripTrailing(reference, '.,;:!?)]')])]
198
371
  .filter(candidate => candidate.length > 0)
199
- .map(candidate => candidate.startsWith('~/') ? join(home, candidate.slice(2)) : resolve(dirname(path), candidate))
200
- .find(isFileAt);
201
- if (target !== undefined)
202
- visit(target, source, depth + 1, path, 'import');
372
+ .map(candidate => candidate.startsWith('~/') ? join(home, candidate.slice(2)) : resolve(dirname(path), candidate));
373
+ visit(candidates, source, depth + 1, path, 'import');
203
374
  }
204
375
  };
205
376
  for (const source of sources)
206
- visit(source.path, source, 0, undefined, source.kind);
207
- return { files, hostFiles, skipped, root };
377
+ visit([source.path], source, 0, undefined, source.kind);
378
+ return { files, hostFiles, skipped, skippedUnlisted, root, ...(stopped !== undefined ? { stopped } : {}) };
208
379
  }
209
380
  const DESCRIPTIONS = {
210
381
  user: "user's private global instructions for all projects",
@@ -222,10 +393,11 @@ function cut(text, bytes) {
222
393
  /**
223
394
  * Frame the files as prompt text under a byte budget. When they do not fit, the
224
395
  * broadest files are left out first and the last one is cut; a note names both.
396
+ * @param stopped - the note of a load that stopped at a limit (`InstructionSet.stopped`), added at the end.
225
397
  */
226
- export function renderInstructions(files, maxBytes = DEFAULT_INSTRUCTION_BYTES) {
398
+ export function renderInstructions(files, maxBytes = DEFAULT_INSTRUCTION_BYTES, stopped) {
227
399
  if (files.length === 0)
228
- return { text: '', included: [], omitted: [], truncated: [] };
400
+ return { text: stopped === undefined ? '' : `[${stopped}]`, included: [], omitted: [], truncated: [] };
229
401
  const block = (file, content) => {
230
402
  const label = file.kind === 'import' ? `imported by ${file.importedBy ?? 'an instruction file'}` : DESCRIPTIONS[file.kind];
231
403
  return `Contents of ${file.path} (${label}):\n\n${content.trim()}`;
@@ -251,7 +423,7 @@ export function renderInstructions(files, maxBytes = DEFAULT_INSTRUCTION_BYTES)
251
423
  ? ''
252
424
  : `\n\n[Harness Forge: the instruction files exceed ${String(maxBytes)} bytes; ${omitted.length > 0 ? `left out: ${omitted.join(', ')}` : ''}${omitted.length > 0 && truncated.length > 0 ? '; ' : ''}${truncated.length > 0 ? `cut: ${truncated.join(', ')}` : ''}.]`;
253
425
  return {
254
- text: `${PREAMBLE}\n\n${kept.map(item => item.text).join('\n\n')}${note}`,
426
+ text: `${PREAMBLE}\n\n${kept.map(item => item.text).join('\n\n')}${note}${stopped === undefined ? '' : `\n\n[${stopped}]`}`,
255
427
  included: kept.map(item => ({ path: item.file.path, bytes: item.file.bytes })),
256
428
  omitted,
257
429
  truncated,
package/lib/license.js CHANGED
@@ -4,9 +4,9 @@
4
4
  * SPDX expression parsing is intentionally out of scope.
5
5
  * @module @kirkchinese/harness-forge-core
6
6
  */
7
- import { readdirSync, readFileSync } from 'node:fs';
7
+ import { readdirSync } from 'node:fs';
8
8
  import { join } from 'node:path';
9
- import { readJsonObject } from './paths.js';
9
+ import { leadsToShare, readJsonObject, readText } from './paths.js';
10
10
  const SIGNATURES = [
11
11
  [/MIT License|Permission is hereby granted, free of charge/iu, 'MIT'],
12
12
  [/Apache License,?\s+Version 2\.0/iu, 'Apache-2.0'],
@@ -27,6 +27,9 @@ export function detectLicense(root, declared) {
27
27
  return packageJson['license'].trim();
28
28
  }
29
29
  let names;
30
+ // On a link to a network share the path is not on: as unreadable (see `leadsToShare`).
31
+ if (leadsToShare(root))
32
+ return undefined;
30
33
  try {
31
34
  names = readdirSync(root);
32
35
  }
@@ -37,15 +40,13 @@ export function detectLicense(root, declared) {
37
40
  .filter(name => /^(?:licen[cs]e|copying)(?:\..*)?$/iu.test(name))
38
41
  .sort((a, b) => a.localeCompare(b, 'en'));
39
42
  for (const name of candidates) {
40
- try {
41
- const text = readFileSync(join(root, name), 'utf8').slice(0, 16_384);
42
- for (const [pattern, id] of SIGNATURES)
43
- if (pattern.test(text))
44
- return id;
45
- }
46
- catch {
47
- // A license file we cannot read is simply not recognized.
48
- }
43
+ // A license file we cannot read (or one on a link to a network share, see `leadsToShare`) is simply not recognized.
44
+ const text = readText(join(root, name))?.slice(0, 16_384);
45
+ if (text === undefined)
46
+ continue;
47
+ for (const [pattern, id] of SIGNATURES)
48
+ if (pattern.test(text))
49
+ return id;
49
50
  }
50
51
  return undefined;
51
52
  }
package/lib/manifest.d.ts CHANGED
@@ -30,6 +30,12 @@ export interface ScanResult {
30
30
  }
31
31
  /** Detect the manifest convention at a plugin root. */
32
32
  export declare function detectManifest(root: string, explicitPath?: string, source?: SourceId): DetectedManifest | undefined;
33
+ /**
34
+ * Whether `root` holds one of the named plugin-layout directories. A directory
35
+ * that is itself a skill (it has a `SKILL.md`) is a skill folder that happens
36
+ * to be called `agents` or `hooks`, not a layout directory.
37
+ */
38
+ export declare function hasLayoutDirectory(root: string, names: readonly string[]): boolean;
33
39
  /**
34
40
  * Scan one plugin directory. The scan is read-only and tolerant: a malformed
35
41
  * component produces a warning, not a thrown error.