@srobroek/harness-kit 0.0.0-stage → 1.0.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/src/index.ts ADDED
@@ -0,0 +1,20 @@
1
+ // Library entry: the generator functions the CLI wraps, for tests and tooling.
2
+ export { CONFIG_FILE, type Config, findRoot, type Harness, KNOWN_HARNESSES, KNOWN_KINDS, type Kind, loadConfig, resolveConfig } from "./config"
3
+ export {
4
+ assertSemver,
5
+ bareImports,
6
+ type Drift,
7
+ drift,
8
+ type HarnessInventory,
9
+ type Output,
10
+ type Plugin,
11
+ type PluginOption,
12
+ readPlugin,
13
+ readPlugins,
14
+ render,
15
+ stampVersion,
16
+ write,
17
+ } from "./generate"
18
+ export { type ValidateOptions, validateClaude } from "./validate-claude"
19
+ export { compareVersions, type Exec, PACKAGE_NAME, pinnedVersion, update, type UpdateResult } from "./update"
20
+ export { workflowRefWarnings } from "./workflow-refs"
package/src/update.ts ADDED
@@ -0,0 +1,68 @@
1
+ // `harness-kit update`: move the pinned @srobroek/harness-kit to the newest published version and regenerate.
2
+ // It never commits or pushes; the CI job that calls it does that.
3
+
4
+ import { spawnSync } from "node:child_process"
5
+ import { existsSync, readFileSync } from "node:fs"
6
+ import path from "node:path"
7
+ import { fail, isRecord } from "./util"
8
+
9
+ export const PACKAGE_NAME = "@srobroek/harness-kit"
10
+ const DEPENDENCY_FIELDS = ["dependencies", "devDependencies", "optionalDependencies"] as const
11
+
12
+ /** Run a command in `cwd`. `capture` returns its stdout; otherwise it inherits the terminal. Throws on a non-zero exit. */
13
+ export type Exec = (command: string, args: string[], options: { cwd: string; capture?: boolean }) => string
14
+
15
+ export const defaultExec: Exec = (command, args, { cwd, capture }) => {
16
+ const run = spawnSync(command, args, { cwd, encoding: "utf8", stdio: capture ? ["ignore", "pipe", "inherit"] : "inherit" })
17
+ if (run.error) throw new Error(`cannot run ${command}: ${run.error.message}`)
18
+ if (run.status !== 0) throw new Error(`${command} ${args.join(" ")} exited with ${run.status}`)
19
+ return run.stdout ?? ""
20
+ }
21
+
22
+ export type UpdateResult = { status: "current" | "outdated" | "updated"; from: string; to: string }
23
+
24
+ const VERSION = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?/
25
+
26
+ /** Negative when a < b, 0 when equal, positive when a > b. A prerelease sorts below its release. */
27
+ export function compareVersions(a: string, b: string): number {
28
+ const [pa, pb] = [VERSION.exec(a), VERSION.exec(b)]
29
+ if (!pa || !pb) throw new Error(`cannot compare versions "${a}" and "${b}"`)
30
+ for (let i = 1; i <= 3; i++) {
31
+ const diff = Number(pa[i]) - Number(pb[i])
32
+ if (diff !== 0) return diff
33
+ }
34
+ if (pa[4] === pb[4]) return 0
35
+ if (pa[4] === undefined) return 1
36
+ if (pb[4] === undefined) return -1
37
+ return pa[4] < pb[4] ? -1 : 1
38
+ }
39
+
40
+ /** The pinned version of the package in the first dependency field that lists it. */
41
+ export function pinnedVersion(root: string): string {
42
+ const file = path.join(root, "package.json")
43
+ if (!existsSync(file)) fail("package.json", `not found in ${root}`)
44
+ const manifest: unknown = JSON.parse(readFileSync(file, "utf8"))
45
+ for (const field of DEPENDENCY_FIELDS) {
46
+ const section = isRecord(manifest) ? manifest[field] : undefined
47
+ const spec = isRecord(section) ? section[PACKAGE_NAME] : undefined
48
+ if (typeof spec === "string") {
49
+ const version = spec.replace(/^[\^~=v]+/, "")
50
+ if (!VERSION.test(version)) fail("package.json", `${field}["${PACKAGE_NAME}"] is "${spec}", which is not a plain version`)
51
+ return version
52
+ }
53
+ }
54
+ return fail("package.json", `${PACKAGE_NAME} is not in dependencies, devDependencies or optionalDependencies`)
55
+ }
56
+
57
+ export function update(root: string, options: { check?: boolean; exec?: Exec } = {}): UpdateResult {
58
+ const exec = options.exec ?? defaultExec
59
+ const from = pinnedVersion(root)
60
+ const to = exec("npm", ["view", PACKAGE_NAME, "version"], { cwd: root, capture: true }).trim()
61
+ if (!VERSION.test(to)) throw new Error(`npm view returned "${to}", expected a version`)
62
+ if (compareVersions(to, from) <= 0) return { status: "current", from, to: from }
63
+ if (options.check) return { status: "outdated", from, to }
64
+ exec("npm", ["install", "--save-exact", `${PACKAGE_NAME}@${to}`], { cwd: root })
65
+ // The new release regenerates, not the copy that is running.
66
+ exec(path.join(root, "node_modules", ".bin", "harness-kit"), ["build", "--root", root], { cwd: root })
67
+ return { status: "updated", from, to }
68
+ }
package/src/util.ts ADDED
@@ -0,0 +1,15 @@
1
+ export function fail(where: string, message: string): never {
2
+ throw new Error(`${where}: ${message}`)
3
+ }
4
+
5
+ export const isRecord = (value: unknown): value is Record<string, unknown> =>
6
+ typeof value === "object" && value !== null && !Array.isArray(value)
7
+
8
+ export function nonEmptyString(where: string, field: string, value: unknown): string {
9
+ if (typeof value !== "string" || !value.trim()) fail(where, `"${field}" must be a non-empty string`)
10
+ return value
11
+ }
12
+
13
+ export function json(value: unknown): string {
14
+ return `${JSON.stringify(value, null, 2)}\n`
15
+ }
@@ -0,0 +1,53 @@
1
+ // Runs `claude plugin validate` on every Claude plugin tree and then on the marketplace.
2
+
3
+ import { spawnSync } from "node:child_process"
4
+ import { existsSync, readdirSync } from "node:fs"
5
+ import path from "node:path"
6
+ import type { Config } from "./config"
7
+
8
+ export type ValidateOptions = {
9
+ /** Overrides claude.strict from harness-kit.json. */
10
+ strict?: boolean
11
+ /** The claude executable. Defaults to node_modules/.bin/claude under the root, then `claude` on PATH. */
12
+ claudeBin?: string
13
+ }
14
+
15
+ function claudeBinary(root: string): string {
16
+ const local = path.join(root, "node_modules", ".bin", "claude")
17
+ return existsSync(local) ? local : "claude"
18
+ }
19
+
20
+ /** Claude plugin trees, as paths relative to the root. */
21
+ function claudeTrees(root: string): string[] {
22
+ const plugins = path.join(root, "plugins")
23
+ if (!existsSync(plugins)) return []
24
+ return readdirSync(plugins, { withFileTypes: true })
25
+ .filter((entry) => entry.isDirectory() && existsSync(path.join(plugins, entry.name, "claude")))
26
+ .map((entry) => path.join("plugins", entry.name, "claude"))
27
+ .sort()
28
+ }
29
+
30
+ /** Exit status: 0 when everything validates (or there is nothing to validate), 1 when the CLI rejects a target. */
31
+ export function validateClaude(root: string, config: Config, options: ValidateOptions = {}): number {
32
+ if (!config.harnesses.includes("claude")) {
33
+ console.log("claude is not enabled in harness-kit.json; nothing to validate")
34
+ return 0
35
+ }
36
+ const trees = claudeTrees(root)
37
+ // An empty marketplace makes the CLI warn, and --strict turns that into a failure, so skip it.
38
+ if (trees.length === 0) {
39
+ console.log("no Claude plugins yet; nothing to validate")
40
+ return 0
41
+ }
42
+ const strict = options.strict ?? config.claude.strict
43
+ const bin = options.claudeBin ?? claudeBinary(root)
44
+ for (const target of [...trees, "."]) {
45
+ console.log(`claude plugin validate${strict ? " --strict" : ""} ${target}`)
46
+ const run = spawnSync(bin, ["plugin", "validate", ...(strict ? ["--strict"] : []), target], { cwd: root, stdio: "inherit" })
47
+ if (run.error) {
48
+ throw new Error(`cannot run ${bin}: ${run.error.message} (install @anthropic-ai/claude-code as a devDependency)`)
49
+ }
50
+ if (run.status !== 0) return 1
51
+ }
52
+ return 0
53
+ }
@@ -0,0 +1,34 @@
1
+ // The reusable workflows and the npm package are released together under the same vX.Y.Z tag.
2
+ // This finds consumer workflow references that have drifted from the pinned package version.
3
+
4
+ import { existsSync, readdirSync, readFileSync } from "node:fs"
5
+ import path from "node:path"
6
+ import { pinnedVersion } from "./update"
7
+
8
+ const REF = /srobroek\/harness-kit\/\.github\/workflows\/[\w.-]+@([^\s"'#]+)/g
9
+
10
+ /** Warnings for `uses: srobroek/harness-kit/...@ref` lines whose ref is not `v<pinned package version>`. */
11
+ export function workflowRefWarnings(root: string): string[] {
12
+ let pinned: string
13
+ try {
14
+ pinned = pinnedVersion(root)
15
+ } catch {
16
+ return [] // no package.json pin: not a consumer, nothing to compare against
17
+ }
18
+ const dir = path.join(root, ".github", "workflows")
19
+ if (!existsSync(dir)) return []
20
+ const warnings: string[] = []
21
+ for (const name of readdirSync(dir).filter((file) => /\.ya?ml$/.test(file)).sort()) {
22
+ const lines = readFileSync(path.join(dir, name), "utf8").split("\n")
23
+ lines.forEach((line, index) => {
24
+ for (const match of line.matchAll(REF)) {
25
+ if (match[1] !== `v${pinned}`) {
26
+ warnings.push(
27
+ `.github/workflows/${name}:${index + 1} uses harness-kit workflow @${match[1]}, but @srobroek/harness-kit is pinned at ${pinned}; use @v${pinned}`,
28
+ )
29
+ }
30
+ }
31
+ })
32
+ }
33
+ return warnings
34
+ }
@@ -0,0 +1,14 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2023",
4
+ "module": "ESNext",
5
+ "moduleResolution": "bundler",
6
+ "strict": true,
7
+ "noUncheckedIndexedAccess": true,
8
+ "noEmit": true,
9
+ "skipLibCheck": true,
10
+ "types": ["bun"],
11
+ "resolveJsonModule": true,
12
+ "allowImportingTsExtensions": true
13
+ }
14
+ }