docks-kit 0.25.0 → 0.26.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 (38) hide show
  1. package/AGENTS.md +6 -6
  2. package/README.md +29 -9
  3. package/cli/dist/docks-kit.js +24688 -0
  4. package/cli/docs/command-guards.md +1 -1
  5. package/cli/docs/install.md +26 -6
  6. package/cli/docs/omp-context.md +1 -1
  7. package/cli/docs/omp-models.md +1 -1
  8. package/cli/src/agentDocs/agentFirstCheck.ts +786 -0
  9. package/cli/src/agentDocs/bridgeCheck.ts +226 -0
  10. package/cli/src/agentDocs/commands.ts +63 -0
  11. package/cli/src/agentDocs/prTemplate.ts +211 -0
  12. package/cli/src/agentDocs/services.ts +202 -0
  13. package/cli/src/agentDocs/shared.ts +730 -0
  14. package/cli/src/agentDocs/verifySkill.ts +136 -0
  15. package/cli/src/argv.ts +25 -1
  16. package/cli/src/commands/agentDocs.ts +29 -0
  17. package/cli/src/commands/plan.ts +29 -0
  18. package/cli/src/commands/skill.ts +29 -0
  19. package/cli/src/commands/update.ts +87 -28
  20. package/cli/src/generated/sotPayload.ts +50 -78
  21. package/cli/src/main.ts +12 -3
  22. package/cli/src/plan/bytes.ts +110 -0
  23. package/cli/src/plan/checkout.ts +341 -0
  24. package/cli/src/plan/commands.ts +1192 -0
  25. package/cli/src/plan/github.ts +816 -0
  26. package/cli/src/plan/records.ts +623 -0
  27. package/cli/src/plan/repository.ts +53 -0
  28. package/cli/src/plan/reviews.ts +292 -0
  29. package/cli/src/plan/services.ts +256 -0
  30. package/cli/src/plan/types.ts +164 -0
  31. package/cli/src/skills/commands.ts +142 -0
  32. package/cli/src/skills/config.json +30 -0
  33. package/cli/src/skills/files.ts +74 -0
  34. package/cli/src/skills/frontmatter.ts +148 -0
  35. package/cli/src/skills/guard.ts +366 -0
  36. package/cli/src/skills/kitGate.ts +406 -0
  37. package/cli/src/skills/rubric.ts +143 -0
  38. package/package.json +7 -4
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Shared shapes of the `docks-kit plan` command: the typed errors, the property reader for decoded JSON, and the issue
3
+ * records that the GitHub reads produce.
4
+ */
5
+ import { Effect, Predicate, Schema } from "effect";
6
+
7
+ /** A contract refusal, such as an invalid argument or a plan state that the command does not accept. */
8
+ export class PlanRefusal extends Schema.TaggedError<
9
+ PlanRefusal,
10
+ { readonly brand: unique symbol }
11
+ >()("PlanRefusal", {
12
+ message: Schema.String,
13
+ }) {}
14
+
15
+ /** gh could not run, exited with a failure, or printed output that is not the expected JSON. */
16
+ export class GhError extends Schema.TaggedError<GhError, { readonly brand: unique symbol }>()(
17
+ "GhError",
18
+ {
19
+ message: Schema.String,
20
+ },
21
+ ) {}
22
+
23
+ /** A GraphQL response with errors, without data, or with a malformed field. */
24
+ export class GraphqlError extends Schema.TaggedError<
25
+ GraphqlError,
26
+ { readonly brand: unique symbol }
27
+ >()("GraphqlError", {
28
+ message: Schema.String,
29
+ }) {}
30
+
31
+ /** git could not run or exited with a failure. */
32
+ export class GitError extends Schema.TaggedError<GitError, { readonly brand: unique symbol }>()(
33
+ "GitError",
34
+ {
35
+ message: Schema.String,
36
+ },
37
+ ) {}
38
+
39
+ /** A file operation failed. `message` is the Node error message; `code` is its error code, such as `ENOENT`. */
40
+ export class FileError extends Schema.TaggedError<FileError, { readonly brand: unique symbol }>()(
41
+ "FileError",
42
+ {
43
+ message: Schema.String,
44
+ code: Schema.optional(Schema.String),
45
+ },
46
+ ) {}
47
+
48
+ /** A child process could not start because Node refused its arguments. */
49
+ export class SpawnError extends Schema.TaggedError<SpawnError, { readonly brand: unique symbol }>()(
50
+ "SpawnError",
51
+ {
52
+ message: Schema.String,
53
+ },
54
+ ) {}
55
+
56
+ /** Every failure of a plan command. The command edge prints its message on stderr and exits 1. */
57
+ export type PlanFailure = PlanRefusal | GhError | GraphqlError | GitError | FileError | SpawnError;
58
+
59
+ /** Stop pure code with a refusal. Effect code wraps the call in `attempt`. */
60
+ export const fail = (message: string): never => {
61
+ throw new PlanRefusal({ message });
62
+ };
63
+
64
+ /** Run pure code that can throw a refusal, and move the refusal into the error channel. */
65
+ export const attempt = <A>(thunk: () => A): Effect.Effect<A, PlanRefusal> =>
66
+ Effect.try({
67
+ try: thunk,
68
+ catch: (error) =>
69
+ error instanceof PlanRefusal
70
+ ? error
71
+ : new PlanRefusal({ message: error instanceof Error ? error.message : String(error) }),
72
+ });
73
+
74
+ /** `value?.[key]` of plan.mjs: the property of an object, or undefined for any other value. */
75
+ export const field = (value: unknown, key: string): unknown =>
76
+ Predicate.hasProperty(value, key) ? value[key] : undefined;
77
+
78
+ export interface RepositoryInfo {
79
+ readonly nameWithOwner: string;
80
+ readonly visibility: string;
81
+ readonly defaultBranch: string | undefined;
82
+ }
83
+
84
+ export interface LabelNode {
85
+ readonly name: string;
86
+ readonly id: string;
87
+ }
88
+
89
+ export interface NamedLabel {
90
+ readonly name: string;
91
+ }
92
+
93
+ export interface Actor {
94
+ readonly login: string;
95
+ }
96
+
97
+ export interface IssueComment {
98
+ readonly fullDatabaseId: string;
99
+ readonly body: string;
100
+ readonly createdAt: string;
101
+ readonly author: Actor | null;
102
+ }
103
+
104
+ export interface PullRequestNode {
105
+ readonly number: number;
106
+ readonly url: string;
107
+ readonly state: string;
108
+ readonly mergedAt: string | null;
109
+ readonly baseRefName: string;
110
+ readonly repository: { readonly nameWithOwner: string };
111
+ }
112
+
113
+ export type CommitCloser = {
114
+ readonly __typename: "Commit";
115
+ readonly oid: string;
116
+ readonly associatedPullRequests?: unknown;
117
+ };
118
+
119
+ /** The closer of the latest close event. Any other GraphQL type is `Other`. */
120
+ export type Closer =
121
+ | ({ readonly __typename: "PullRequest" } & PullRequestNode)
122
+ | CommitCloser
123
+ | { readonly __typename: "Other" };
124
+
125
+ /** A plan list row and a sub-issue row. */
126
+ export interface IssueSummary {
127
+ readonly number: number;
128
+ readonly title: string;
129
+ readonly state: string;
130
+ readonly stateReason: string | null;
131
+ readonly labels: ReadonlyArray<NamedLabel>;
132
+ }
133
+
134
+ export interface ParentLink {
135
+ readonly number: number;
136
+ readonly repository: { readonly nameWithOwner: string };
137
+ }
138
+
139
+ /** The plan issue of a snapshot. A connection that the read did not select is empty or undefined. */
140
+ export interface PlanIssue {
141
+ readonly number: number;
142
+ readonly title: string;
143
+ readonly body: string;
144
+ readonly state: string;
145
+ readonly stateReason: string | null;
146
+ readonly url: string;
147
+ readonly labels: ReadonlyArray<LabelNode>;
148
+ readonly assignees: ReadonlyArray<Actor>;
149
+ readonly comments: ReadonlyArray<IssueComment>;
150
+ readonly history: ReadonlyArray<NamedLabel>;
151
+ readonly closer: Closer | null | undefined;
152
+ readonly closedEventAt: string | undefined;
153
+ readonly children: ReadonlyArray<IssueSummary>;
154
+ readonly parent: ParentLink | null | undefined;
155
+ /** The viewer id that a write claims an unassigned plan for. */
156
+ claimantId: string | undefined;
157
+ }
158
+
159
+ /** The fields that the status derivation reads; a plan issue and an issue summary both have them. */
160
+ export interface StatusSource {
161
+ readonly state: string;
162
+ readonly stateReason: string | null;
163
+ readonly labels: ReadonlyArray<NamedLabel>;
164
+ }
@@ -0,0 +1,142 @@
1
+ /**
2
+ * The dispatcher of `docks-kit skill guard|score`, which replaced the `validate|score` modes of the former skill-guard
3
+ * script of write-skill. Each command prints what the script printed and returns its exit status. A file error that
4
+ * the script did not catch (it ended with a stack trace and exit 1) prints `docks-kit skill: <Node error message>` and
5
+ * returns 1.
6
+ */
7
+ import { dirname, join } from "node:path";
8
+
9
+ import { Clock, Effect, Schema } from "effect";
10
+
11
+ import type { FileError } from "../plan/types";
12
+ import { SkillFiles } from "./files";
13
+ import {
14
+ type Finding,
15
+ frontFindings,
16
+ NESTED_REFERENCES,
17
+ scoreLine,
18
+ slopFindings,
19
+ walkSkillFiles,
20
+ } from "./guard";
21
+ import { scoreSkill, splitLines } from "./rubric";
22
+
23
+ const USAGE = "usage: docks-kit skill guard [--strict] <dir>... | score [--per-file] [root]";
24
+ const GUARD_USAGE = "usage: docks-kit skill guard [--strict] <skill-dir|skills-root> ...";
25
+
26
+ /** `score` without a root reads the project skills that omp loads. */
27
+ const DEFAULT_SCORE_ROOT = ".agents/skills";
28
+
29
+ /** The arguments do not form a command; the usage line goes to stderr with exit status 2. */
30
+ class SkillUsage extends Schema.TaggedError<SkillUsage, { readonly brand: unique symbol }>()(
31
+ "SkillUsage",
32
+ { usage: Schema.String },
33
+ ) {}
34
+
35
+ const writeStdout = (text: string): Effect.Effect<void> =>
36
+ Effect.sync(() => {
37
+ process.stdout.write(text);
38
+ });
39
+
40
+ const writeStderr = (text: string): Effect.Effect<void> =>
41
+ Effect.sync(() => {
42
+ process.stderr.write(text);
43
+ });
44
+
45
+ /** `score [--per-file] [root]`: one `<name> <score>` line per skill folder, sorted, or the total. */
46
+ const score = Effect.fn("skills.score")(function* (args: ReadonlyArray<string>) {
47
+ const files = yield* SkillFiles;
48
+ const nowMillis = yield* Clock.currentTimeMillis;
49
+ const perFile = args.includes("--per-file");
50
+ const root =
51
+ args.find((arg) => !arg.startsWith("--")) ||
52
+ join(yield* files.workingFolder, DEFAULT_SCORE_ROOT);
53
+ const names = (yield* files.readFolder(root)).map((entry) => entry.name).sort();
54
+ let total = 0;
55
+ for (const name of names) {
56
+ const folder = join(root, name);
57
+ if (!(yield* files.isDirectory(folder))) continue;
58
+ const file = join(folder, "SKILL.md");
59
+ if (!(yield* files.exists(file))) continue;
60
+ const points = scoreSkill(yield* files.readFile(file), nowMillis);
61
+ if (perFile) yield* writeStdout(`${name} ${points}\n`);
62
+ total += points;
63
+ }
64
+ if (!perFile) yield* writeStdout(`${total}\n`);
65
+ return 0;
66
+ });
67
+
68
+ /** `guard [--strict] <skill-dir|skills-root>...`: the report of each skill, then the verdict line. */
69
+ const guard = Effect.fn("skills.guard")(function* (args: ReadonlyArray<string>) {
70
+ const files = yield* SkillFiles;
71
+ const strict = args.includes("--strict");
72
+ const targets = args.filter((arg) => arg !== "--strict");
73
+ if (targets.length === 0) return yield* new SkillUsage({ usage: GUARD_USAGE });
74
+ const nowMillis = yield* Clock.currentTimeMillis;
75
+ let fails = 0;
76
+ let warns = 0;
77
+ let checked = 0;
78
+
79
+ const report = (finding: Finding): Effect.Effect<void> => {
80
+ if (finding.level === "fail") fails += 1;
81
+ else if (strict) fails += 1;
82
+ else warns += 1;
83
+ const label = finding.level === "fail" ? "FAIL" : strict ? "FAIL(strict)" : "WARN";
84
+ return writeStdout(` ${label}: ${finding.message}\n`);
85
+ };
86
+
87
+ const check = Effect.fnUntraced(function* (dir: string) {
88
+ yield* writeStdout(`== ${dir}\n`);
89
+ checked += 1;
90
+ const content = yield* files.readFile(join(dir, "SKILL.md"));
91
+ const lines = splitLines(content);
92
+ yield* Effect.forEach(frontFindings(dir, lines, nowMillis), report, { discard: true });
93
+ const references = join(dir, "references");
94
+ if ((yield* files.exists(references)) && (yield* files.isDirectory(references))) {
95
+ const entries = yield* files.readFolder(references);
96
+ if (entries.some((entry) => entry.isDirectory)) yield* report(NESTED_REFERENCES);
97
+ }
98
+ yield* Effect.forEach(slopFindings(lines), report, { discard: true });
99
+ yield* writeStdout(`${scoreLine(scoreSkill(content, nowMillis))}\n`);
100
+ });
101
+
102
+ for (const target of targets) {
103
+ if (yield* files.exists(join(target, "SKILL.md"))) yield* check(target);
104
+ else if ((yield* files.exists(target)) && (yield* files.isDirectory(target))) {
105
+ const found = yield* walkSkillFiles(target);
106
+ if (found.length === 0) {
107
+ yield* writeStderr(`FAIL: no SKILL.md found under ${target}\n`);
108
+ fails += 1;
109
+ }
110
+ for (const file of found) yield* check(dirname(file));
111
+ } else {
112
+ yield* writeStderr(`FAIL: not a directory: ${target}\n`);
113
+ fails += 1;
114
+ }
115
+ }
116
+ if (fails > 0) {
117
+ yield* writeStdout(
118
+ `skill-guard FAILED: ${fails} failure(s), ${warns} warning(s) across ${checked} skill(s)\n`,
119
+ );
120
+ return 1;
121
+ }
122
+ yield* writeStdout(`skill-guard PASSED: ${checked} skill(s), ${warns} warning(s)\n`);
123
+ return 0;
124
+ });
125
+
126
+ const printUsage = (error: SkillUsage): Effect.Effect<number> =>
127
+ writeStderr(`${error.usage}\n`).pipe(Effect.as(2));
128
+
129
+ const printCrash = (error: FileError): Effect.Effect<number> =>
130
+ writeStderr(`docks-kit skill: ${error.message}\n`).pipe(Effect.as(1));
131
+
132
+ /** Run `docks-kit skill <args>` and return its exit status. */
133
+ export const runSkill = Effect.fn("skills.run")(function* (args: ReadonlyArray<string>) {
134
+ const [command, ...rest] = args;
135
+ const outcome: Effect.Effect<number, SkillUsage | FileError, SkillFiles> =
136
+ command === "score"
137
+ ? score(rest)
138
+ : command === "guard"
139
+ ? guard(rest)
140
+ : Effect.fail(new SkillUsage({ usage: USAGE }));
141
+ return yield* outcome.pipe(Effect.catchTags({ SkillUsage: printUsage, FileError: printCrash }));
142
+ });
@@ -0,0 +1,30 @@
1
+ {
2
+ "pluginDir": "SoT/.omp/plugin",
3
+ "floors": {
4
+ "skills": 10,
5
+ "agents": 14
6
+ },
7
+ "reportSection": "## Report a problem with this skill\n\nWhen this skill gives a wrong, outdated, or unsafe instruction, or a script that it ships fails, report the problem in the public DocksDocks/docks-kit repository. Use the `report-skill-issue` skill of the docks-kit kit plugin for the report. If that skill is not installed, do not file anything: give the user a draft instead. The draft names this skill and the docks-kit version, quotes the instruction, and states what happened and what you expected. Leave out secrets and private names.\n",
8
+ "sharedFiles": [
9
+ {
10
+ "canonical": "SoT/.omp/plugin/skills/plan-workspace/references/pull-request-template.md",
11
+ "copies": ["SoT/.omp/plugin/skills/agent-first-setup/references/pull-request-template.md"]
12
+ },
13
+ {
14
+ "canonical": "SoT/.omp/plugin/skills/plan-workspace/references/verify-skill-template.md",
15
+ "copies": ["SoT/.omp/plugin/skills/agent-first-setup/references/verify-skill-template.md"]
16
+ },
17
+ {
18
+ "canonical": "SoT/.omp/plugin/skills/agent-first-setup/references/agents-md-template.md",
19
+ "copies": ["SoT/.omp/plugin/skills/claude-md-migration/references/agents-md-template.md"]
20
+ }
21
+ ],
22
+ "transformingSkills": [
23
+ "context-tree",
24
+ "claude-md-migration",
25
+ "skill-agent-pipeline",
26
+ "skill-maintenance",
27
+ "refactor",
28
+ "plan-workspace"
29
+ ]
30
+ }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * The file service of `docks-kit skill`. Each method mirrors one `fs` call of the former skill-guard script of
3
+ * write-skill, with the same symlink handling. A failed call carries the Node error message,
4
+ * which names the error code and the path. The command entry provides `SkillFiles.layer`.
5
+ */
6
+ import fs from "node:fs";
7
+
8
+ import { Context, Effect, Layer, Predicate } from "effect";
9
+
10
+ import { FileError } from "../plan/types";
11
+
12
+ /** One folder entry, as `readdirSync(..., { withFileTypes: true })` sees it: a symlink is not a directory. */
13
+ export interface SkillFolderEntry {
14
+ readonly name: string;
15
+ readonly isDirectory: boolean;
16
+ }
17
+
18
+ const errorCode = (error: unknown): string | undefined => {
19
+ const code = Predicate.hasProperty(error, "code") ? error.code : undefined;
20
+ return Predicate.isString(code) ? code : undefined;
21
+ };
22
+
23
+ /**
24
+ * The Node message of a failed call on `file`. Node leaves the path out of some messages, such as the EISDIR of a read;
25
+ * the path is then appended in Node's own form, `<message> '<path>'`.
26
+ */
27
+ function errorMessage(error: unknown, file: string): string {
28
+ if (!(error instanceof Error)) return String(error);
29
+ return Predicate.hasProperty(error, "path") && Predicate.isString(error.path)
30
+ ? error.message
31
+ : `${error.message} '${file}'`;
32
+ }
33
+
34
+ const fileOperation = <A>(file: string, operation: () => A): Effect.Effect<A, FileError> =>
35
+ Effect.try({
36
+ try: operation,
37
+ catch: (error) => new FileError({ message: errorMessage(error, file), code: errorCode(error) }),
38
+ });
39
+
40
+ export class SkillFiles extends Context.Service<
41
+ SkillFiles,
42
+ {
43
+ /** `fs.existsSync`, which follows symlinks and never fails. */
44
+ readonly exists: (file: string) => Effect.Effect<boolean>;
45
+ /** `fs.statSync(file).isDirectory()`, which follows symlinks. */
46
+ readonly isDirectory: (file: string) => Effect.Effect<boolean, FileError>;
47
+ /** The entries of a folder, in the order of the system. */
48
+ readonly readFolder: (
49
+ folder: string,
50
+ ) => Effect.Effect<ReadonlyArray<SkillFolderEntry>, FileError>;
51
+ /** The UTF-8 text of a file, a leading byte-order mark included. */
52
+ readonly readFile: (file: string) => Effect.Effect<string, FileError>;
53
+ /** `process.cwd()`. */
54
+ readonly workingFolder: Effect.Effect<string>;
55
+ }
56
+ >()("docks-kit/skills/SkillFiles") {
57
+ static readonly layer = Layer.succeed(
58
+ SkillFiles,
59
+ SkillFiles.of({
60
+ exists: (file) => Effect.sync(() => fs.existsSync(file)),
61
+ isDirectory: (file) => fileOperation(file, () => fs.statSync(file).isDirectory()),
62
+ readFolder: (folder) =>
63
+ fileOperation(folder, () =>
64
+ fs.readdirSync(folder, { withFileTypes: true }).map((entry): SkillFolderEntry => ({
65
+ name: entry.name,
66
+ isDirectory: entry.isDirectory(),
67
+ })),
68
+ ),
69
+ // Node's readFileSync with an encoding decodes the bytes as Buffer#toString does.
70
+ readFile: (file) => fileOperation(file, () => fs.readFileSync(file).toString("utf8")),
71
+ workingFolder: Effect.sync(() => process.cwd()),
72
+ }),
73
+ );
74
+ }
@@ -0,0 +1,148 @@
1
+ import { existsSync, readdirSync, statSync } from "node:fs";
2
+ import { basename, dirname, join, resolve } from "node:path";
3
+ import { parseDocument } from "yaml";
4
+ import config from "./config.json" with { type: "json" };
5
+
6
+ /**
7
+ * Shared parse and walk helpers for the kit plugin content checks. They port
8
+ * `scripts/lib/skills-parse.mjs`, `scripts/lib/skills-walk.mjs`, the
9
+ * frontmatter steps of `scripts/lib/validate-skills.mjs`, and the frontmatter
10
+ * helpers of `scripts/ci.mjs` from DocksDocks/docks.
11
+ */
12
+
13
+ /** The kit plugin folder below a repository root. */
14
+ export const pluginDir = (repoRoot: string): string => join(repoRoot, config.pluginDir);
15
+
16
+ /** The skills folder of the kit plugin below a repository root. */
17
+ export const skillsDir = (repoRoot: string): string => join(pluginDir(repoRoot), "skills");
18
+
19
+ /** The agents folder of the kit plugin below a repository root. */
20
+ export const agentsDir = (repoRoot: string): string => join(pluginDir(repoRoot), "agents");
21
+
22
+ /** A frontmatter value that YAML parsed into a mapping. */
23
+ export type FrontmatterMapping = { readonly [key: string]: unknown };
24
+
25
+ export type Extracted =
26
+ | { readonly ok: true; readonly text: string; readonly body: string }
27
+ | { readonly ok: false; readonly error: string };
28
+
29
+ export type Parsed =
30
+ | { readonly ok: true; readonly value: FrontmatterMapping }
31
+ | { readonly ok: false; readonly error: string };
32
+
33
+ const isMapping = (value: unknown): value is FrontmatterMapping =>
34
+ typeof value === "object" && value !== null && !Array.isArray(value);
35
+
36
+ /** Split a SKILL.md into its frontmatter text and its body, as the validator does. */
37
+ export function extractFrontmatter(content: string): Extracted {
38
+ const lines = content.split(/\r?\n/);
39
+ if (lines[0] !== "---") {
40
+ return { ok: false, error: "SKILL.md must start with YAML frontmatter fence `---`" };
41
+ }
42
+ const end = lines.findIndex((line, index) => index > 0 && line === "---");
43
+ if (end === -1) return { ok: false, error: "frontmatter fence is not closed" };
44
+ return {
45
+ ok: true,
46
+ text: lines.slice(1, end).join("\n"),
47
+ body: lines.slice(end + 1).join("\n"),
48
+ };
49
+ }
50
+
51
+ /** Parse frontmatter text as strict YAML with unique string keys. */
52
+ export function parseFrontmatter(text: string): Parsed {
53
+ const doc = parseDocument(text, {
54
+ prettyErrors: true,
55
+ strict: true,
56
+ uniqueKeys: true,
57
+ stringKeys: true,
58
+ });
59
+ if (doc.errors.length > 0) {
60
+ return { ok: false, error: doc.errors.map((error) => error.message).join("; ") };
61
+ }
62
+ let value: unknown;
63
+ try {
64
+ // `toJS` throws on a value that the parse step accepts, such as an alias
65
+ // to an anchor that does not exist.
66
+ value = doc.toJS();
67
+ } catch (error) {
68
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
69
+ }
70
+ if (!isMapping(value)) return { ok: false, error: "frontmatter must be a YAML mapping/object" };
71
+ return { ok: true, value };
72
+ }
73
+
74
+ /** Read a nested mapping value, or undefined when the key is not a mapping. */
75
+ export const mappingField = (
76
+ value: FrontmatterMapping,
77
+ key: string,
78
+ ): FrontmatterMapping | undefined => {
79
+ const field = value[key];
80
+ return isMapping(field) ? field : undefined;
81
+ };
82
+
83
+ /** The frontmatter block of a markdown file, or null when it has none. */
84
+ export const frontmatterBlock = (text: string): string | null =>
85
+ /^---\n([\s\S]*?)\n---(?:\n|$)/u.exec(text)?.[1] ?? null;
86
+
87
+ /** The keys of the top-level lines of a frontmatter block. */
88
+ export const frontmatterKeys = (block: string): ReadonlySet<string> =>
89
+ new Set(block.split("\n").flatMap((line) => /^([A-Za-z][\w-]*):/u.exec(line)?.[1] ?? []));
90
+
91
+ /** The `name` value of a frontmatter block, without quotes, or null when it has none. */
92
+ export const frontmatterName = (block: string): string | null =>
93
+ /^name:[ \t]*(.*)$/mu
94
+ .exec(block)?.[1]
95
+ ?.trim()
96
+ .replace(/^(["'])(.*)\1$/u, "$2") ?? null;
97
+
98
+ /** Each SKILL.md below `root`, sorted. The walk skips node_modules, .git, and symbolic links. */
99
+ export function findSkillFiles(root: string): Array<string> {
100
+ const out: Array<string> = [];
101
+ const walk = (dir: string): void => {
102
+ let entries;
103
+ try {
104
+ entries = readdirSync(dir, { withFileTypes: true });
105
+ } catch (error) {
106
+ throw new Error(`cannot read skills directory ${resolve(dir)}: ${String(error)}`, {
107
+ cause: error,
108
+ });
109
+ }
110
+ for (const entry of entries) {
111
+ if (entry.name === "node_modules" || entry.name === ".git" || entry.isSymbolicLink()) {
112
+ continue;
113
+ }
114
+ const full = join(dir, entry.name);
115
+ if (entry.isDirectory()) walk(full);
116
+ else if (entry.name === "SKILL.md") out.push(full);
117
+ }
118
+ };
119
+ walk(root);
120
+ return out.sort();
121
+ }
122
+
123
+ export interface SkillDir {
124
+ readonly name: string;
125
+ readonly dir: string;
126
+ readonly file: string;
127
+ }
128
+
129
+ /**
130
+ * Each `<root>/<skill>/` folder, sorted, also one without a SKILL.md. The
131
+ * scorer skips a folder without a SKILL.md, so a count from this list sees
132
+ * that folder. `statSync` follows symbolic links, as the scorer does.
133
+ */
134
+ export function skillCandidateDirs(root: string): Array<SkillDir> {
135
+ if (!existsSync(root)) return [];
136
+ return readdirSync(root)
137
+ .sort()
138
+ .map((name) => ({ name, dir: join(root, name), file: join(root, name, "SKILL.md") }))
139
+ .filter(({ dir }) => statSync(dir).isDirectory());
140
+ }
141
+
142
+ /** Each `<root>/<skill>/` folder, sorted, that holds a SKILL.md. */
143
+ export const skillDirs = (root: string): Array<SkillDir> =>
144
+ skillCandidateDirs(root).filter(({ file }) => existsSync(file));
145
+
146
+ /** The first SKILL.md below `root` whose folder is `name`, or null. */
147
+ export const findSkillByName = (root: string, name: string): string | null =>
148
+ findSkillFiles(root).find((file) => basename(dirname(file)) === name) ?? null;