@harnesspm/cli 0.0.0-snapshot.412a718
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +259 -0
- package/LICENSE +21 -0
- package/README.md +70 -0
- package/dist/added.d.ts +51 -0
- package/dist/added.js +192 -0
- package/dist/check.d.ts +14 -0
- package/dist/check.js +263 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +218 -0
- package/dist/commands.d.ts +58 -0
- package/dist/commands.js +1299 -0
- package/dist/config.d.ts +15 -0
- package/dist/config.js +45 -0
- package/dist/deliver.d.ts +1 -0
- package/dist/deliver.js +31 -0
- package/dist/doctor.d.ts +18 -0
- package/dist/doctor.js +99 -0
- package/dist/exec-outputs.d.ts +75 -0
- package/dist/exec-outputs.js +425 -0
- package/dist/exec-units.d.ts +68 -0
- package/dist/exec-units.js +151 -0
- package/dist/fetch.d.ts +16 -0
- package/dist/fetch.js +145 -0
- package/dist/frontmatter.d.ts +16 -0
- package/dist/frontmatter.js +49 -0
- package/dist/homes.d.ts +7 -0
- package/dist/homes.js +21 -0
- package/dist/lock.d.ts +47 -0
- package/dist/lock.js +245 -0
- package/dist/manifest.d.ts +78 -0
- package/dist/manifest.js +169 -0
- package/dist/new.d.ts +33 -0
- package/dist/new.js +228 -0
- package/dist/outputs.d.ts +124 -0
- package/dist/outputs.js +875 -0
- package/dist/parent.d.ts +41 -0
- package/dist/parent.js +182 -0
- package/dist/render.d.ts +91 -0
- package/dist/render.js +221 -0
- package/dist/resolve.d.ts +132 -0
- package/dist/resolve.js +522 -0
- package/dist/reviewed.d.ts +15 -0
- package/dist/reviewed.js +41 -0
- package/dist/run.d.ts +18 -0
- package/dist/run.js +133 -0
- package/dist/sections.d.ts +32 -0
- package/dist/sections.js +121 -0
- package/dist/telemetry-api.d.ts +26 -0
- package/dist/telemetry-api.js +60 -0
- package/dist/telemetry.d.ts +119 -0
- package/dist/telemetry.js +401 -0
- package/dist/user-outputs.d.ts +30 -0
- package/dist/user-outputs.js +239 -0
- package/dist/util.d.ts +137 -0
- package/dist/util.js +370 -0
- package/dist/workspaces.d.ts +2 -0
- package/dist/workspaces.js +62 -0
- package/docs/spec/01-overview.md +149 -0
- package/docs/spec/02-package-format.md +252 -0
- package/docs/spec/03-resolution.md +108 -0
- package/docs/spec/04-outputs.md +194 -0
- package/docs/spec/05-executables.md +170 -0
- package/docs/spec/06-trust.md +88 -0
- package/docs/spec/07-added.md +109 -0
- package/docs/spec/08-improving.md +79 -0
- package/docs/spec/09-cloud.md +68 -0
- package/docs/spec/10-cli.md +181 -0
- package/docs/spec/11-standards.md +52 -0
- package/docs/spec/12-dogfooding.md +51 -0
- package/docs/spec/13-open-questions.md +97 -0
- package/docs/spec/14-telemetry.md +199 -0
- package/docs/spec/README.md +33 -0
- package/harness/dev.harnesspm/rules/generated-files.md +9 -0
- package/harness/dev.harnesspm/rules/harnesspm-config.md +12 -0
- package/harness/plugin.json +13 -0
- package/harness/skills/harnesspm-export/SKILL.md +43 -0
- package/harness/skills/harnesspm-import/SKILL.md +40 -0
- package/harness/skills/harnesspm-improve/SKILL.md +38 -0
- package/package.json +73 -0
- package/schema/harnesspm.schema.json +58 -0
package/dist/util.d.ts
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
/** The npm package of harnesspm. The command it installs is `harnesspm` (spec 10.1). */
|
|
2
|
+
export declare const PACKAGE_NAME = "@harnesspm/cli";
|
|
3
|
+
/**
|
|
4
|
+
* Earlier names of the package. harnesspm still finds an installed copy under them and treats their commands as its own,
|
|
5
|
+
* until 1.0.0 (spec 10.1). Delete them then.
|
|
6
|
+
*/
|
|
7
|
+
export declare const OLD_PACKAGE_NAMES: string[];
|
|
8
|
+
/** Every name of the package, the current one first. */
|
|
9
|
+
export declare const PACKAGE_NAMES: string[];
|
|
10
|
+
/**
|
|
11
|
+
* How harnesspm runs, in every text, message and hook it writes (spec 10.1): npx runs the installed version in a project
|
|
12
|
+
* that depends on it, and downloads the package by its full name elsewhere. Never the bare `npx harnesspm`: outside such
|
|
13
|
+
* a project, npx would fetch whatever is published under the unscoped name, and a hook has nobody to ask.
|
|
14
|
+
*/
|
|
15
|
+
export declare const NPX_ANY = "npx -y @harnesspm/cli";
|
|
16
|
+
/**
|
|
17
|
+
* The bare form that earlier versions wrote and that some packages' text still types. harnesspm only matches it, in
|
|
18
|
+
* allow rules for a project's scripts, where npx finds the installed command (spec 5.4).
|
|
19
|
+
*/
|
|
20
|
+
export declare const NPX_BARE = "npx harnesspm";
|
|
21
|
+
/** A command prefix that starts harnesspm: as shell words, for hooks, and as an argument list, for MCP servers. */
|
|
22
|
+
export interface Runner {
|
|
23
|
+
shell: string;
|
|
24
|
+
argv: string[];
|
|
25
|
+
}
|
|
26
|
+
/** A runner through npx, such as `npx -y @harnesspm/cli`. */
|
|
27
|
+
export declare const npxRunner: (prefix: string) => Runner;
|
|
28
|
+
/** A word for sh: as it is when it is safe, else in single quotes. */
|
|
29
|
+
export declare function shellWord(word: string): string;
|
|
30
|
+
/**
|
|
31
|
+
* The CLI file of the harnesspm that the project installed, by the `bin` field of its package.json, under the current
|
|
32
|
+
* name first, then an earlier one. The path goes through `node_modules/@harnesspm/cli`, not its real path, so it stays
|
|
33
|
+
* the same when pnpm moves the package.
|
|
34
|
+
*/
|
|
35
|
+
export declare function installedCli(projectDir: string): string | undefined;
|
|
36
|
+
/**
|
|
37
|
+
* How hooks and MCP servers start harnesspm in a project (spec 5.2, 14.4): `node` with the CLI file that the project
|
|
38
|
+
* installed, else `fallback` through npx, which costs about 0.4 s per call. `node` runs the file whatever its mode: Yarn 4
|
|
39
|
+
* drops the executable bit on an upgrade in place (research/package-managers.md). The path is absolute, so only
|
|
40
|
+
* per-machine files use it. Allow rules keep the npx form, because they must match the command the agent types
|
|
41
|
+
* (spec 5.4). Windows keeps npx, so commands there hold no shell-quoted path.
|
|
42
|
+
*/
|
|
43
|
+
export declare function runner(projectDir: string, fallback: string): Runner;
|
|
44
|
+
/** An error that the CLI prints without a stack trace. */
|
|
45
|
+
export declare class HarnessError extends Error {
|
|
46
|
+
}
|
|
47
|
+
export declare function exists(p: string): boolean;
|
|
48
|
+
export declare function isFile(p: string): boolean;
|
|
49
|
+
export declare function isDir(p: string): boolean;
|
|
50
|
+
export declare function readText(file: string): string;
|
|
51
|
+
export declare function readTextIfExists(file: string): string | undefined;
|
|
52
|
+
export declare function readJson(file: string): unknown;
|
|
53
|
+
export declare function readJsonIfExists(file: string): unknown;
|
|
54
|
+
export declare function isRecord(value: unknown): value is Record<string, unknown>;
|
|
55
|
+
export declare function hash(text: string | Buffer): string;
|
|
56
|
+
/** A forward-slash path, for outputs that must be the same on every machine. */
|
|
57
|
+
export declare function toPosix(p: string): string;
|
|
58
|
+
export declare function relPosix(from: string, to: string): string;
|
|
59
|
+
export declare function ensureDir(dir: string): void;
|
|
60
|
+
/** Writes a file only when its content changes. Returns true when it wrote. */
|
|
61
|
+
export declare function writeIfChanged(file: string, content: string): boolean;
|
|
62
|
+
/** Creates or updates a relative symbolic link. Returns true when it changed the link. */
|
|
63
|
+
export declare function linkIfChanged(linkPath: string, target: string): boolean;
|
|
64
|
+
export declare function isSymlink(p: string): boolean;
|
|
65
|
+
export declare function realpath(p: string): string;
|
|
66
|
+
/** Whether `from`, by default the folder harnesspm started in, is `dir` or inside it. Both are compared as real paths. */
|
|
67
|
+
export declare function insideDir(dir: string, from?: string): boolean;
|
|
68
|
+
/** Compares versions like 1.2.10 and 1.10.0 by their numeric parts. */
|
|
69
|
+
export declare function compareVersions(a: string, b: string): number;
|
|
70
|
+
/** Where a project's per-machine files are excluded from git (spec 4.1). */
|
|
71
|
+
export interface GitExclude {
|
|
72
|
+
/** The clone's exclude file, usually `.git/info/exclude` at the git root. */
|
|
73
|
+
file: string;
|
|
74
|
+
/** The top folder of the work tree. */
|
|
75
|
+
root: string;
|
|
76
|
+
/** The project's folder from `root`, such as `docs-site/`, or `''` at the root. Patterns in `file` start from `root`, so every entry starts with it. */
|
|
77
|
+
prefix: string;
|
|
78
|
+
}
|
|
79
|
+
/** The clone's exclude file and the project's path inside the work tree, or undefined outside a git repository. */
|
|
80
|
+
export declare function gitExclude(projectDir: string): GitExclude | undefined;
|
|
81
|
+
/** The file that holds this clone's git excludes, or undefined outside a git repository. */
|
|
82
|
+
export declare function gitExcludeFile(projectDir: string): string | undefined;
|
|
83
|
+
/** An exclude entry for a path from the project folder, such as `CLAUDE.local.md`: anchored at the git root, as git reads it. */
|
|
84
|
+
export declare const excludeEntry: (prefix: string, rel: string) => string;
|
|
85
|
+
/** Adds one entry to the clone's exclude file, after everything else in it, unless it is there already. */
|
|
86
|
+
export declare function addExclude(projectDir: string, rel: string): void;
|
|
87
|
+
/**
|
|
88
|
+
* Which files below `dir` a docs unit counts, by their posix path relative to `dir` (spec 2.7): every file but
|
|
89
|
+
* the ones git ignores. An ignored file never reaches another clone, so counting it would make this machine's
|
|
90
|
+
* lock, index and check differ from everyone else's. Every file counts when git is missing, `dir` is outside a
|
|
91
|
+
* work tree, or git ignores `dir` itself, as it ignores an installed package in node_modules.
|
|
92
|
+
*/
|
|
93
|
+
export declare function gitKeeps(dir: string): (rel: string) => boolean;
|
|
94
|
+
/** Whether `file` is `dir` or below it. */
|
|
95
|
+
export declare function isInside(dir: string, file: string): boolean;
|
|
96
|
+
/**
|
|
97
|
+
* A Markdown page with its code samples blanked out, so that a link in a sample is not read (spec 2.10):
|
|
98
|
+
* fenced code blocks and code spans, as CommonMark reads them. A fence that is never closed runs to the end of the page.
|
|
99
|
+
* A fence may be indented, as in a list item. Its closing fence is indented at most 3 columns more.
|
|
100
|
+
* Indented code blocks stay: telling one from a list item's paragraph needs a full Markdown parser.
|
|
101
|
+
* Blanks keep every other character where it was, so a match in the result is at the same place in the page.
|
|
102
|
+
*/
|
|
103
|
+
export declare function withoutCode(text: string): string;
|
|
104
|
+
/**
|
|
105
|
+
* The links of a Markdown page outside its code samples that point at a file of its own package: neither a URL nor
|
|
106
|
+
* an absolute path. Each is the target without its fragment, and where that target starts in the page.
|
|
107
|
+
*/
|
|
108
|
+
export declare function relativeLinks(text: string): {
|
|
109
|
+
link: string;
|
|
110
|
+
index: number;
|
|
111
|
+
}[];
|
|
112
|
+
/** Whether git ignores the folder `dir` itself. False outside a work tree, or when git is missing. */
|
|
113
|
+
export declare function gitIgnoresDir(dir: string): boolean;
|
|
114
|
+
/**
|
|
115
|
+
* The file whose pattern makes git ignore `rel`, a path in `projectDir` that need not exist (a folder ends in `/`): a
|
|
116
|
+
* `.gitignore` or `.git/info/exclude` by its path from the git root, or a global excludes file by its absolute path.
|
|
117
|
+
* Null when git does not ignore it, undefined outside a work tree.
|
|
118
|
+
*/
|
|
119
|
+
export declare function gitIgnoreSource(projectDir: string, rel: string): string | null | undefined;
|
|
120
|
+
/** Whether a file written at `rel` stays out of every commit: git ignores it, or there is no work tree. */
|
|
121
|
+
export declare function gitKeepsOut(projectDir: string, rel: string): boolean;
|
|
122
|
+
export declare function listDir(dir: string): string[];
|
|
123
|
+
export type Caller = 'model' | 'hook' | 'person';
|
|
124
|
+
/**
|
|
125
|
+
* Who runs harnesspm (spec 6.2, rule 4). Claude Code marks model commands (`AI_AGENT=…_agent`) and hooks
|
|
126
|
+
* (`…_harness`). Codex sets `CODEX_CI=1` and `CODEX_TOOL_CALL_ID` only in commands the model runs.
|
|
127
|
+
*/
|
|
128
|
+
export declare function caller(env?: NodeJS.ProcessEnv): Caller;
|
|
129
|
+
/** True when Codex's model runs the command: Codex marks only those (spec 6.2, rule 4). */
|
|
130
|
+
export declare function codexRun(env?: NodeJS.ProcessEnv): boolean;
|
|
131
|
+
/** True in a Claude Code cloud session, where the person has no terminal of their own (spec 9). */
|
|
132
|
+
export declare function inCloudSession(env?: NodeJS.ProcessEnv): boolean;
|
|
133
|
+
/** `<host>/<path>` of a repository's `origin` remote, without `.git`, for SSH and HTTPS URLs. Undefined without one. */
|
|
134
|
+
export declare function remoteKey(projectDir: string): string | undefined;
|
|
135
|
+
export declare function normalizeRemote(url: string): string;
|
|
136
|
+
/** The agent whose marker is in the environment: `claude`, `codex`, or undefined (spec 5.1). */
|
|
137
|
+
export declare function agentOf(env?: NodeJS.ProcessEnv): 'claude' | 'codex' | undefined;
|
package/dist/util.js
ADDED
|
@@ -0,0 +1,370 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { spawnSync } from 'node:child_process';
|
|
3
|
+
import * as fs from 'node:fs';
|
|
4
|
+
import * as path from 'node:path';
|
|
5
|
+
/** The npm package of harnesspm. The command it installs is `harnesspm` (spec 10.1). */
|
|
6
|
+
export const PACKAGE_NAME = '@harnesspm/cli';
|
|
7
|
+
/**
|
|
8
|
+
* Earlier names of the package. harnesspm still finds an installed copy under them and treats their commands as its own,
|
|
9
|
+
* until 1.0.0 (spec 10.1). Delete them then.
|
|
10
|
+
*/
|
|
11
|
+
export const OLD_PACKAGE_NAMES = ['@tenphi/harnesspm'];
|
|
12
|
+
/** Every name of the package, the current one first. */
|
|
13
|
+
export const PACKAGE_NAMES = [PACKAGE_NAME, ...OLD_PACKAGE_NAMES];
|
|
14
|
+
/**
|
|
15
|
+
* How harnesspm runs, in every text, message and hook it writes (spec 10.1): npx runs the installed version in a project
|
|
16
|
+
* that depends on it, and downloads the package by its full name elsewhere. Never the bare `npx harnesspm`: outside such
|
|
17
|
+
* a project, npx would fetch whatever is published under the unscoped name, and a hook has nobody to ask.
|
|
18
|
+
*/
|
|
19
|
+
export const NPX_ANY = `npx -y ${PACKAGE_NAME}`;
|
|
20
|
+
/**
|
|
21
|
+
* The bare form that earlier versions wrote and that some packages' text still types. harnesspm only matches it, in
|
|
22
|
+
* allow rules for a project's scripts, where npx finds the installed command (spec 5.4).
|
|
23
|
+
*/
|
|
24
|
+
export const NPX_BARE = 'npx harnesspm';
|
|
25
|
+
/** A runner through npx, such as `npx -y @harnesspm/cli`. */
|
|
26
|
+
export const npxRunner = (prefix) => ({ shell: prefix, argv: prefix.split(' ') });
|
|
27
|
+
/** A word for sh: as it is when it is safe, else in single quotes. */
|
|
28
|
+
export function shellWord(word) {
|
|
29
|
+
return /^[\w@%+=:,./-]+$/.test(word) ? word : `'${word.replaceAll("'", "'\\''")}'`;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* The CLI file of the harnesspm that the project installed, by the `bin` field of its package.json, under the current
|
|
33
|
+
* name first, then an earlier one. The path goes through `node_modules/@harnesspm/cli`, not its real path, so it stays
|
|
34
|
+
* the same when pnpm moves the package.
|
|
35
|
+
*/
|
|
36
|
+
export function installedCli(projectDir) {
|
|
37
|
+
for (const name of PACKAGE_NAMES) {
|
|
38
|
+
const dir = path.join(projectDir, 'node_modules', ...name.split('/'));
|
|
39
|
+
try {
|
|
40
|
+
const pkg = readJsonIfExists(path.join(dir, 'package.json'));
|
|
41
|
+
const bin = isRecord(pkg) ? (typeof pkg['bin'] === 'string' ? pkg['bin'] : isRecord(pkg['bin']) ? pkg['bin']['harnesspm'] : undefined) : undefined;
|
|
42
|
+
if (typeof bin === 'string' && isFile(path.join(dir, bin)))
|
|
43
|
+
return path.join(dir, bin);
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
// Not installed under this name.
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return undefined;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* How hooks and MCP servers start harnesspm in a project (spec 5.2, 14.4): `node` with the CLI file that the project
|
|
53
|
+
* installed, else `fallback` through npx, which costs about 0.4 s per call. `node` runs the file whatever its mode: Yarn 4
|
|
54
|
+
* drops the executable bit on an upgrade in place (research/package-managers.md). The path is absolute, so only
|
|
55
|
+
* per-machine files use it. Allow rules keep the npx form, because they must match the command the agent types
|
|
56
|
+
* (spec 5.4). Windows keeps npx, so commands there hold no shell-quoted path.
|
|
57
|
+
*/
|
|
58
|
+
export function runner(projectDir, fallback) {
|
|
59
|
+
const cli = process.platform === 'win32' ? undefined : installedCli(projectDir);
|
|
60
|
+
if (cli === undefined)
|
|
61
|
+
return npxRunner(fallback);
|
|
62
|
+
return { shell: `node ${shellWord(cli)}`, argv: ['node', cli] };
|
|
63
|
+
}
|
|
64
|
+
/** An error that the CLI prints without a stack trace. */
|
|
65
|
+
export class HarnessError extends Error {
|
|
66
|
+
}
|
|
67
|
+
export function exists(p) {
|
|
68
|
+
try {
|
|
69
|
+
fs.lstatSync(p);
|
|
70
|
+
return true;
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
return false;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
export function isFile(p) {
|
|
77
|
+
try {
|
|
78
|
+
return fs.statSync(p).isFile();
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
return false;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
export function isDir(p) {
|
|
85
|
+
try {
|
|
86
|
+
return fs.statSync(p).isDirectory();
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
return false;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
export function readText(file) {
|
|
93
|
+
return fs.readFileSync(file, 'utf8');
|
|
94
|
+
}
|
|
95
|
+
export function readTextIfExists(file) {
|
|
96
|
+
return isFile(file) ? readText(file) : undefined;
|
|
97
|
+
}
|
|
98
|
+
export function readJson(file) {
|
|
99
|
+
try {
|
|
100
|
+
return JSON.parse(readText(file));
|
|
101
|
+
}
|
|
102
|
+
catch (error) {
|
|
103
|
+
throw new HarnessError(`Cannot read ${file}: ${error.message}`);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
export function readJsonIfExists(file) {
|
|
107
|
+
return isFile(file) ? readJson(file) : undefined;
|
|
108
|
+
}
|
|
109
|
+
export function isRecord(value) {
|
|
110
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
111
|
+
}
|
|
112
|
+
export function hash(text) {
|
|
113
|
+
return createHash('sha256').update(text).digest('hex').slice(0, 16);
|
|
114
|
+
}
|
|
115
|
+
/** A forward-slash path, for outputs that must be the same on every machine. */
|
|
116
|
+
export function toPosix(p) {
|
|
117
|
+
return p.split(path.sep).join('/');
|
|
118
|
+
}
|
|
119
|
+
export function relPosix(from, to) {
|
|
120
|
+
return toPosix(path.relative(from, to)) || '.';
|
|
121
|
+
}
|
|
122
|
+
export function ensureDir(dir) {
|
|
123
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
124
|
+
}
|
|
125
|
+
/** Writes a file only when its content changes. Returns true when it wrote. */
|
|
126
|
+
export function writeIfChanged(file, content) {
|
|
127
|
+
if (readTextIfExists(file) === content)
|
|
128
|
+
return false;
|
|
129
|
+
ensureDir(path.dirname(file));
|
|
130
|
+
fs.writeFileSync(file, content);
|
|
131
|
+
return true;
|
|
132
|
+
}
|
|
133
|
+
/** Creates or updates a relative symbolic link. Returns true when it changed the link. */
|
|
134
|
+
export function linkIfChanged(linkPath, target) {
|
|
135
|
+
const relTarget = path.relative(path.dirname(linkPath), target) || '.';
|
|
136
|
+
try {
|
|
137
|
+
if (fs.lstatSync(linkPath).isSymbolicLink() && fs.readlinkSync(linkPath) === relTarget)
|
|
138
|
+
return false;
|
|
139
|
+
fs.rmSync(linkPath, { recursive: false, force: true });
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
// The link does not exist yet.
|
|
143
|
+
}
|
|
144
|
+
ensureDir(path.dirname(linkPath));
|
|
145
|
+
fs.symlinkSync(relTarget, linkPath, 'dir');
|
|
146
|
+
return true;
|
|
147
|
+
}
|
|
148
|
+
export function isSymlink(p) {
|
|
149
|
+
try {
|
|
150
|
+
return fs.lstatSync(p).isSymbolicLink();
|
|
151
|
+
}
|
|
152
|
+
catch {
|
|
153
|
+
return false;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
export function realpath(p) {
|
|
157
|
+
return fs.realpathSync(p);
|
|
158
|
+
}
|
|
159
|
+
/** Whether `from`, by default the folder harnesspm started in, is `dir` or inside it. Both are compared as real paths. */
|
|
160
|
+
export function insideDir(dir, from = process.cwd()) {
|
|
161
|
+
const real = (p) => {
|
|
162
|
+
try {
|
|
163
|
+
return fs.realpathSync(p);
|
|
164
|
+
}
|
|
165
|
+
catch {
|
|
166
|
+
return path.resolve(p);
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
const inner = real(from);
|
|
170
|
+
const outer = real(dir);
|
|
171
|
+
return inner === outer || inner.startsWith(outer.endsWith(path.sep) ? outer : outer + path.sep);
|
|
172
|
+
}
|
|
173
|
+
/** Compares versions like 1.2.10 and 1.10.0 by their numeric parts. */
|
|
174
|
+
export function compareVersions(a, b) {
|
|
175
|
+
const pa = a.split(/[.+-]/);
|
|
176
|
+
const pb = b.split(/[.+-]/);
|
|
177
|
+
for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
|
|
178
|
+
const x = pa[i] ?? '';
|
|
179
|
+
const y = pb[i] ?? '';
|
|
180
|
+
const nx = Number(x);
|
|
181
|
+
const ny = Number(y);
|
|
182
|
+
if (!Number.isNaN(nx) && !Number.isNaN(ny) && x !== '' && y !== '') {
|
|
183
|
+
if (nx !== ny)
|
|
184
|
+
return nx - ny;
|
|
185
|
+
}
|
|
186
|
+
else if (x !== y) {
|
|
187
|
+
return x < y ? -1 : 1;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
return 0;
|
|
191
|
+
}
|
|
192
|
+
/** The clone's exclude file and the project's path inside the work tree, or undefined outside a git repository. */
|
|
193
|
+
export function gitExclude(projectDir) {
|
|
194
|
+
const result = spawnSync('git', ['rev-parse', '--show-toplevel', '--show-prefix', '--git-path', 'info/exclude'], { cwd: projectDir, encoding: 'utf8' });
|
|
195
|
+
if (result.status !== 0)
|
|
196
|
+
return undefined;
|
|
197
|
+
const [root = projectDir, prefix = '', p = ''] = result.stdout.split('\n');
|
|
198
|
+
return { file: path.isAbsolute(p) ? p : path.join(projectDir, p), root, prefix };
|
|
199
|
+
}
|
|
200
|
+
/** The file that holds this clone's git excludes, or undefined outside a git repository. */
|
|
201
|
+
export function gitExcludeFile(projectDir) {
|
|
202
|
+
return gitExclude(projectDir)?.file;
|
|
203
|
+
}
|
|
204
|
+
/** An exclude entry for a path from the project folder, such as `CLAUDE.local.md`: anchored at the git root, as git reads it. */
|
|
205
|
+
export const excludeEntry = (prefix, rel) => `/${prefix}${rel.replace(/^\/+/, '')}`;
|
|
206
|
+
/** Adds one entry to the clone's exclude file, after everything else in it, unless it is there already. */
|
|
207
|
+
export function addExclude(projectDir, rel) {
|
|
208
|
+
const exclude = gitExclude(projectDir);
|
|
209
|
+
if (!exclude)
|
|
210
|
+
return;
|
|
211
|
+
const entry = excludeEntry(exclude.prefix, rel);
|
|
212
|
+
const text = readTextIfExists(exclude.file) ?? '';
|
|
213
|
+
if (text.split('\n').includes(entry))
|
|
214
|
+
return;
|
|
215
|
+
writeIfChanged(exclude.file, `${text.replace(/\s*$/, '')}${text.trim() ? '\n' : ''}${entry}\n`);
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* Which files below `dir` a docs unit counts, by their posix path relative to `dir` (spec 2.7): every file but
|
|
219
|
+
* the ones git ignores. An ignored file never reaches another clone, so counting it would make this machine's
|
|
220
|
+
* lock, index and check differ from everyone else's. Every file counts when git is missing, `dir` is outside a
|
|
221
|
+
* work tree, or git ignores `dir` itself, as it ignores an installed package in node_modules.
|
|
222
|
+
*/
|
|
223
|
+
export function gitKeeps(dir) {
|
|
224
|
+
// Exit 1: git ignores nothing here. 0 means it ignores the folder itself, 128 that there is no work tree.
|
|
225
|
+
if (spawnSync('git', ['check-ignore', '-q', '.'], { cwd: dir }).status !== 1)
|
|
226
|
+
return () => true;
|
|
227
|
+
const listed = spawnSync('git', ['ls-files', '-z', '--cached', '--others', '--exclude-standard'], { cwd: dir, encoding: 'utf8', maxBuffer: 256 * 1024 * 1024 });
|
|
228
|
+
if (listed.status !== 0)
|
|
229
|
+
return () => true;
|
|
230
|
+
const kept = new Set(listed.stdout.split('\0'));
|
|
231
|
+
return (rel) => kept.has(rel);
|
|
232
|
+
}
|
|
233
|
+
/** Whether `file` is `dir` or below it. */
|
|
234
|
+
export function isInside(dir, file) {
|
|
235
|
+
const rel = path.relative(dir, file);
|
|
236
|
+
return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
|
|
237
|
+
}
|
|
238
|
+
/** A fence line: its indent, its run of backticks or tildes, and the rest of the line. */
|
|
239
|
+
const FENCE = /^([ \t]*)(`{3,}|~{3,})(.*)$/;
|
|
240
|
+
/** An escaped character, a code span (backticks closed by a run of the same length within one paragraph), or backticks that open nothing. */
|
|
241
|
+
const CODE_SPAN = /\\[\s\S]|(`+)(?!`)(?:(?!\n[ \t]*\n)[\s\S])*?(?<!`)\1(?!`)|`+/g;
|
|
242
|
+
const blank = (text) => text.replace(/[^\r\n]/g, ' ');
|
|
243
|
+
/**
|
|
244
|
+
* A Markdown page with its code samples blanked out, so that a link in a sample is not read (spec 2.10):
|
|
245
|
+
* fenced code blocks and code spans, as CommonMark reads them. A fence that is never closed runs to the end of the page.
|
|
246
|
+
* A fence may be indented, as in a list item. Its closing fence is indented at most 3 columns more.
|
|
247
|
+
* Indented code blocks stay: telling one from a list item's paragraph needs a full Markdown parser.
|
|
248
|
+
* Blanks keep every other character where it was, so a match in the result is at the same place in the page.
|
|
249
|
+
*/
|
|
250
|
+
export function withoutCode(text) {
|
|
251
|
+
const lines = text.split('\n');
|
|
252
|
+
let open;
|
|
253
|
+
for (const [i, line] of lines.entries()) {
|
|
254
|
+
const fence = FENCE.exec(line.replace(/\r$/, ''));
|
|
255
|
+
if (open) {
|
|
256
|
+
if (fence && fence[2][0] === open.char && fence[2].length >= open.length && fence[3].trim() === '' && fence[1].length <= open.indent + 3)
|
|
257
|
+
open = undefined;
|
|
258
|
+
lines[i] = blank(line);
|
|
259
|
+
}
|
|
260
|
+
else if (fence && !(fence[2][0] === '`' && fence[3].includes('`'))) {
|
|
261
|
+
// The info string of a backtick fence has no backticks: such a line starts a code span instead.
|
|
262
|
+
open = { char: fence[2][0], length: fence[2].length, indent: fence[1].length };
|
|
263
|
+
lines[i] = blank(line);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
// Spaces keep the text around a span apart, so that `[a]` and `(b)` on each side of it do not become a link.
|
|
267
|
+
return lines.join('\n').replace(CODE_SPAN, (match, ticks) => (ticks === undefined ? match : blank(match)));
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* The links of a Markdown page outside its code samples that point at a file of its own package: neither a URL nor
|
|
271
|
+
* an absolute path. Each is the target without its fragment, and where that target starts in the page.
|
|
272
|
+
*/
|
|
273
|
+
export function relativeLinks(text) {
|
|
274
|
+
const links = [];
|
|
275
|
+
for (const match of withoutCode(text).matchAll(/\]\(([^)\s#]+)(?:#[^)]*)?\)/g)) {
|
|
276
|
+
const link = match[1];
|
|
277
|
+
if (!/^[a-z][a-z0-9+.-]*:/i.test(link) && !link.startsWith('/'))
|
|
278
|
+
links.push({ link, index: match.index + 2 });
|
|
279
|
+
}
|
|
280
|
+
return links;
|
|
281
|
+
}
|
|
282
|
+
/** Whether git ignores the folder `dir` itself. False outside a work tree, or when git is missing. */
|
|
283
|
+
export function gitIgnoresDir(dir) {
|
|
284
|
+
return spawnSync('git', ['check-ignore', '-q', '.'], { cwd: dir }).status === 0;
|
|
285
|
+
}
|
|
286
|
+
/**
|
|
287
|
+
* The file whose pattern makes git ignore `rel`, a path in `projectDir` that need not exist (a folder ends in `/`): a
|
|
288
|
+
* `.gitignore` or `.git/info/exclude` by its path from the git root, or a global excludes file by its absolute path.
|
|
289
|
+
* Null when git does not ignore it, undefined outside a work tree.
|
|
290
|
+
*/
|
|
291
|
+
export function gitIgnoreSource(projectDir, rel) {
|
|
292
|
+
// -z, so git does not quote a path with non-ASCII characters.
|
|
293
|
+
const result = spawnSync('git', ['check-ignore', '-z', '-v', '--stdin'], { cwd: projectDir, encoding: 'utf8', input: `${rel}\0` });
|
|
294
|
+
if (result.status === 1)
|
|
295
|
+
return null;
|
|
296
|
+
// Git also fails inside a work tree, as on an exclude file it cannot read, in a repository it calls unsafe, or when
|
|
297
|
+
// it is missing: then nothing is known to be ignored.
|
|
298
|
+
if (result.status !== 0)
|
|
299
|
+
return hasGitAbove(projectDir) ? null : undefined;
|
|
300
|
+
const [source = '', , pattern = ''] = result.stdout.split('\0');
|
|
301
|
+
return source !== '' && !pattern.startsWith('!') ? source : null;
|
|
302
|
+
}
|
|
303
|
+
/** Whether `dir` or a folder above it holds `.git`, whether or not git can read it. */
|
|
304
|
+
function hasGitAbove(dir) {
|
|
305
|
+
for (let current = path.resolve(dir);; current = path.dirname(current)) {
|
|
306
|
+
if (fs.existsSync(path.join(current, '.git')))
|
|
307
|
+
return true;
|
|
308
|
+
if (path.dirname(current) === current)
|
|
309
|
+
return false;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
/** Whether a file written at `rel` stays out of every commit: git ignores it, or there is no work tree. */
|
|
313
|
+
export function gitKeepsOut(projectDir, rel) {
|
|
314
|
+
return gitIgnoreSource(projectDir, rel) !== null;
|
|
315
|
+
}
|
|
316
|
+
export function listDir(dir) {
|
|
317
|
+
try {
|
|
318
|
+
return fs.readdirSync(dir).sort();
|
|
319
|
+
}
|
|
320
|
+
catch {
|
|
321
|
+
return [];
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
/**
|
|
325
|
+
* Who runs harnesspm (spec 6.2, rule 4). Claude Code marks model commands (`AI_AGENT=…_agent`) and hooks
|
|
326
|
+
* (`…_harness`). Codex sets `CODEX_CI=1` and `CODEX_TOOL_CALL_ID` only in commands the model runs.
|
|
327
|
+
*/
|
|
328
|
+
export function caller(env = process.env) {
|
|
329
|
+
const agent = env['AI_AGENT'] ?? '';
|
|
330
|
+
if (agent.endsWith('_agent'))
|
|
331
|
+
return 'model';
|
|
332
|
+
if (agent.endsWith('_harness'))
|
|
333
|
+
return 'hook';
|
|
334
|
+
if (agent === '' && env['CLAUDECODE'] === '1')
|
|
335
|
+
return 'model';
|
|
336
|
+
if (codexRun(env))
|
|
337
|
+
return 'model';
|
|
338
|
+
return 'person';
|
|
339
|
+
}
|
|
340
|
+
/** True when Codex's model runs the command: Codex marks only those (spec 6.2, rule 4). */
|
|
341
|
+
export function codexRun(env = process.env) {
|
|
342
|
+
return env['CODEX_CI'] === '1' || (env['CODEX_TOOL_CALL_ID'] ?? '') !== '';
|
|
343
|
+
}
|
|
344
|
+
/** True in a Claude Code cloud session, where the person has no terminal of their own (spec 9). */
|
|
345
|
+
export function inCloudSession(env = process.env) {
|
|
346
|
+
return env['CLAUDE_CODE_REMOTE'] === 'true';
|
|
347
|
+
}
|
|
348
|
+
/** `<host>/<path>` of a repository's `origin` remote, without `.git`, for SSH and HTTPS URLs. Undefined without one. */
|
|
349
|
+
export function remoteKey(projectDir) {
|
|
350
|
+
const result = spawnSync('git', ['remote', 'get-url', 'origin'], { cwd: projectDir, encoding: 'utf8' });
|
|
351
|
+
const url = (result.stdout ?? '').trim();
|
|
352
|
+
return result.status === 0 && url !== '' ? normalizeRemote(url) : undefined;
|
|
353
|
+
}
|
|
354
|
+
export function normalizeRemote(url) {
|
|
355
|
+
let rest = url.trim().replace(/\.git$/, '').replace(/\/$/, '');
|
|
356
|
+
const scp = /^[^@/]+@([^:/]+):(.+)$/.exec(rest);
|
|
357
|
+
if (scp)
|
|
358
|
+
return `${scp[1]}/${scp[2].replace(/^\/+/, '')}`;
|
|
359
|
+
rest = rest.replace(/^[a-z+]+:\/\//i, '').replace(/^[^@/]+@/, '');
|
|
360
|
+
const [hostPort, ...segments] = rest.split('/');
|
|
361
|
+
return [hostPort.replace(/:\d+$/, ''), ...segments].join('/');
|
|
362
|
+
}
|
|
363
|
+
/** The agent whose marker is in the environment: `claude`, `codex`, or undefined (spec 5.1). */
|
|
364
|
+
export function agentOf(env = process.env) {
|
|
365
|
+
if ((env['AI_AGENT'] ?? '').startsWith('claude-code') || env['CLAUDECODE'] === '1')
|
|
366
|
+
return 'claude';
|
|
367
|
+
if (env['CODEX_CI'] === '1' || (env['CODEX_TOOL_CALL_ID'] ?? '') !== '')
|
|
368
|
+
return 'codex';
|
|
369
|
+
return undefined;
|
|
370
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// Workspaces of a monorepo (spec 3.6): package.json "workspaces" or pnpm-workspace.yaml.
|
|
2
|
+
import { createRequire } from 'node:module';
|
|
3
|
+
import * as fs from 'node:fs';
|
|
4
|
+
import * as path from 'node:path';
|
|
5
|
+
import { isFile, isRecord, readJsonIfExists, readTextIfExists } from './util.js';
|
|
6
|
+
function patternsOf(projectDir) {
|
|
7
|
+
const pkg = readJsonIfExists(path.join(projectDir, 'package.json'));
|
|
8
|
+
const field = isRecord(pkg) ? pkg['workspaces'] : undefined;
|
|
9
|
+
const fromPackage = Array.isArray(field) ? field : isRecord(field) && Array.isArray(field['packages']) ? field['packages'] : [];
|
|
10
|
+
const pnpmText = readTextIfExists(path.join(projectDir, 'pnpm-workspace.yaml'));
|
|
11
|
+
// The YAML parser loads only for pnpm, so `reportRun`, which reaches this module, stays light (spec 14.9).
|
|
12
|
+
const pnpm = pnpmText !== undefined ? createRequire(import.meta.url)('yaml').parse(pnpmText) : undefined;
|
|
13
|
+
const fromPnpm = isRecord(pnpm) && Array.isArray(pnpm['packages']) ? pnpm['packages'] : [];
|
|
14
|
+
return [...fromPackage, ...fromPnpm].filter((p) => typeof p === 'string');
|
|
15
|
+
}
|
|
16
|
+
function segmentRegex(segment) {
|
|
17
|
+
return new RegExp(`^${segment.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '[^/]*').replace(/\?/g, '[^/]')}$`);
|
|
18
|
+
}
|
|
19
|
+
/** Folders that match a pattern such as `packages/*` or `apps/**`. */
|
|
20
|
+
function expand(root, pattern) {
|
|
21
|
+
const segments = pattern.replace(/^\.\//, '').replace(/\/$/, '').split('/').filter(Boolean);
|
|
22
|
+
const found = [];
|
|
23
|
+
const walk = (dir, index) => {
|
|
24
|
+
if (index === segments.length) {
|
|
25
|
+
found.push(dir);
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
const segment = segments[index];
|
|
29
|
+
let entries = [];
|
|
30
|
+
try {
|
|
31
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
const dirs = entries.filter((e) => e.isDirectory() && e.name !== 'node_modules' && !e.name.startsWith('.'));
|
|
37
|
+
if (segment === '**') {
|
|
38
|
+
walk(dir, index + 1);
|
|
39
|
+
for (const entry of dirs)
|
|
40
|
+
walk(path.join(dir, entry.name), index);
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
const regex = segmentRegex(segment);
|
|
44
|
+
for (const entry of dirs)
|
|
45
|
+
if (regex.test(entry.name))
|
|
46
|
+
walk(path.join(dir, entry.name), index + 1);
|
|
47
|
+
};
|
|
48
|
+
walk(root, 0);
|
|
49
|
+
return found;
|
|
50
|
+
}
|
|
51
|
+
/** Absolute folders of the workspaces, sorted, without the root. Empty for a single package. */
|
|
52
|
+
export function findWorkspaces(projectDir) {
|
|
53
|
+
const patterns = patternsOf(projectDir);
|
|
54
|
+
const include = new Set();
|
|
55
|
+
for (const pattern of patterns.filter((p) => !p.startsWith('!')))
|
|
56
|
+
for (const dir of expand(projectDir, pattern))
|
|
57
|
+
include.add(dir);
|
|
58
|
+
for (const pattern of patterns.filter((p) => p.startsWith('!')))
|
|
59
|
+
for (const dir of expand(projectDir, pattern.slice(1)))
|
|
60
|
+
include.delete(dir);
|
|
61
|
+
return [...include].filter((dir) => dir !== projectDir && isFile(path.join(dir, 'package.json'))).sort();
|
|
62
|
+
}
|