docks-kit 0.24.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 (49) hide show
  1. package/AGENTS.md +21 -136
  2. package/README.md +54 -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 +30 -9
  6. package/cli/docs/omp-context.md +1 -1
  7. package/cli/docs/omp-models.md +5 -4
  8. package/cli/docs/sync-layers.md +46 -75
  9. package/cli/docs/toolchain.md +4 -5
  10. package/cli/src/agentDocs/agentFirstCheck.ts +786 -0
  11. package/cli/src/agentDocs/bridgeCheck.ts +226 -0
  12. package/cli/src/agentDocs/commands.ts +63 -0
  13. package/cli/src/agentDocs/prTemplate.ts +211 -0
  14. package/cli/src/agentDocs/services.ts +202 -0
  15. package/cli/src/agentDocs/shared.ts +730 -0
  16. package/cli/src/agentDocs/verifySkill.ts +136 -0
  17. package/cli/src/argv.ts +25 -1
  18. package/cli/src/commands/agentDocs.ts +29 -0
  19. package/cli/src/commands/plan.ts +29 -0
  20. package/cli/src/commands/skill.ts +29 -0
  21. package/cli/src/commands/update.ts +90 -31
  22. package/cli/src/engine-native/DESIGN.md +5 -6
  23. package/cli/src/engine-native/engineCtx.ts +0 -3
  24. package/cli/src/engine-native/failures.ts +2 -2
  25. package/cli/src/engine-native/ompChild.ts +1 -1
  26. package/cli/src/engine-native/ompKitPlugin.ts +7 -16
  27. package/cli/src/engine-native/ompPlugins.ts +205 -221
  28. package/cli/src/engine-native/ompSync.ts +5 -14
  29. package/cli/src/generated/sotPayload.ts +308 -12
  30. package/cli/src/main.ts +12 -3
  31. package/cli/src/plan/bytes.ts +110 -0
  32. package/cli/src/plan/checkout.ts +341 -0
  33. package/cli/src/plan/commands.ts +1192 -0
  34. package/cli/src/plan/github.ts +816 -0
  35. package/cli/src/plan/records.ts +623 -0
  36. package/cli/src/plan/repository.ts +53 -0
  37. package/cli/src/plan/reviews.ts +292 -0
  38. package/cli/src/plan/services.ts +256 -0
  39. package/cli/src/plan/types.ts +164 -0
  40. package/cli/src/skills/commands.ts +142 -0
  41. package/cli/src/skills/config.json +30 -0
  42. package/cli/src/skills/files.ts +74 -0
  43. package/cli/src/skills/frontmatter.ts +148 -0
  44. package/cli/src/skills/guard.ts +366 -0
  45. package/cli/src/skills/kitGate.ts +406 -0
  46. package/cli/src/skills/rubric.ts +143 -0
  47. package/cli/tsconfig.json +1 -0
  48. package/package.json +7 -4
  49. package/cli/src/engine-native/ompMarketplace.ts +0 -140
@@ -0,0 +1,226 @@
1
+ /**
2
+ * `docks-kit agent-docs bridge-check audit | verify [--expect <path>]...`: audit the agent-doc layout before
3
+ * claude-md-migration writes (Step 2), and verify the migration after the writes (Step 6). Both commands read only;
4
+ * they write no file. The meaning of each line and the reaction to it live in the SKILL.md of claude-md-migration.
5
+ * Run it from any folder inside the repository, or from the project folder outside git.
6
+ *
7
+ * Output lines:
8
+ * audit four `EXISTS <entry>` or `MISSING <entry>` lines, in the order AGENTS.md, CLAUDE.md (root),
9
+ * .claude/CLAUDE.md, CLAUDE.local.md; then the legacy entries of the root .claude folder (see
10
+ * `legacyClaudeLines`); then one `legacy: <path>` line for each CLAUDE.md and .claude/CLAUDE.md, root and
11
+ * nested (the root ones also when git ignores them), or `legacy link: <path>` for one that is a symlink to
12
+ * the AGENTS.md of its folder; one `personal: <path>` line for each CLAUDE.local.md; and
13
+ * `plugin author: yes (.omp-plugin/marketplace.json)`, `plugin author: yes (package.json omp object)`, or
14
+ * `plugin author: no`.
15
+ * verify `BROKEN: AGENTS.md missing`; `BROKEN: legacy CLAUDE.md still present: <path>`; `BROKEN: <path> missing`
16
+ * for each --expect path that is no file; `HANDOFF context-tree: unrouted node <path>`;
17
+ * `HANDOFF context-tree: dead route <path>`; `VOLATILE time-relative|bare-count <file>:<line>` and
18
+ * `VOLATILE line-anchor <file>:<line> (<path> exists)` for every AGENTS.md. No output means the migration
19
+ * is complete. `HANDOFF` and `VOLATILE` lines are report items, not failures.
20
+ * Either command prints `ERROR <part>: file listing failed (see the message above)` for a listing that fails, and
21
+ * `ERROR <part>: cannot read <file>` for a file that is there but cannot be read, in place of the lines of that
22
+ * part. The cause is on stderr. Paths are relative to the repository root, without a leading `./`. No listing enters
23
+ * node_modules. The CLAUDE.local.md listing, and every listing outside git, walks the folder and skips each .git,
24
+ * node_modules, vendor, dist, build, out, target, and .next folder.
25
+ *
26
+ * Exit status: 2 after an ERROR line, 1 for a usage error, otherwise 0.
27
+ */
28
+ import { Effect, Predicate } from "effect";
29
+
30
+ import {
31
+ agentsDocs,
32
+ BRIDGE_PRUNE,
33
+ durableDocScan,
34
+ EXCLUDE_NODE_MODULES,
35
+ guarded,
36
+ isAgentsLink,
37
+ isFile,
38
+ legacyClaudeLines,
39
+ type Listing,
40
+ listFiles,
41
+ ROOT_CONTEXT_FILES,
42
+ ROOT_PERSONAL_FILES,
43
+ readText,
44
+ repositoryRoot,
45
+ routingGaps,
46
+ UsageError,
47
+ withRootFiles,
48
+ } from "./shared";
49
+ import { AgentDocsFiles, printLines } from "./services";
50
+
51
+ const USAGE = "usage: docks-kit agent-docs bridge-check audit | verify [--expect <path>]...";
52
+ // The Step 2 entries in output order.
53
+ const AUDIT_FILES: ReadonlyArray<string> = [
54
+ "AGENTS.md",
55
+ "CLAUDE.md",
56
+ ".claude/CLAUDE.md",
57
+ "CLAUDE.local.md",
58
+ ];
59
+ const AUDIT_LABELS: Readonly<Record<string, string>> = { "CLAUDE.md": "CLAUDE.md (root)" };
60
+ const PLUGIN_CATALOG = ".omp-plugin/marketplace.json";
61
+ const PACKAGE_MANIFEST = "package.json";
62
+
63
+ /** The repository: its root and whether git answers for it. */
64
+ interface Repository {
65
+ readonly root: string;
66
+ readonly inGit: boolean;
67
+ }
68
+
69
+ const listing = (repo: Repository): Listing => ({
70
+ root: repo.root,
71
+ prune: BRIDGE_PRUNE,
72
+ inGit: repo.inGit,
73
+ });
74
+
75
+ /**
76
+ * Every CLAUDE.md and .claude/CLAUDE.md, root and nested; gitignored build output is skipped, but the root ones count
77
+ * also when git ignores them, because omp loads them. The walk outside git keeps each regular file and each symlink
78
+ * that resolves to a file, so a nested legacy link is listed and a dangling one is not; the git listing keeps
79
+ * symlinks, as `git ls-files` did.
80
+ */
81
+ const legacyFiles = Effect.fn("bridgeCheck.legacyFiles")(function* (repo: Repository) {
82
+ const pathspecs = [":(glob)**/CLAUDE.md", EXCLUDE_NODE_MODULES];
83
+ const files = yield* listFiles({ ...listing(repo), pathspecs, excludeStandard: true });
84
+ return yield* withRootFiles(
85
+ repo.inGit ? files : yield* Effect.filter(files, (file) => isFile(file)),
86
+ ROOT_CONTEXT_FILES,
87
+ );
88
+ });
89
+
90
+ /** CLAUDE.local.md is usually gitignored, so the walk finds it also inside git. */
91
+ const personalFiles = Effect.fn("bridgeCheck.personalFiles")(function* (repo: Repository) {
92
+ const pathspecs = [":(glob)**/CLAUDE.local.md"];
93
+ const files = yield* listFiles({ ...listing(repo), pathspecs, inGit: false, filesOnly: true });
94
+ return yield* withRootFiles(files, ROOT_PERSONAL_FILES);
95
+ });
96
+
97
+ /** The parsed JSON text, or null when it does not parse. */
98
+ function parsedJson(text: string): unknown {
99
+ try {
100
+ return JSON.parse(text);
101
+ } catch {
102
+ return null;
103
+ }
104
+ }
105
+
106
+ /**
107
+ * The plugin-author line: an omp plugin catalog, or a package.json with an `omp` object, makes the repository the
108
+ * source of an omp plugin. A package.json that does not parse has no `omp` object.
109
+ */
110
+ const pluginAuthorLine = Effect.fn("bridgeCheck.pluginAuthorLine")(function* () {
111
+ if (yield* isFile(PLUGIN_CATALOG)) return `plugin author: yes (${PLUGIN_CATALOG})`;
112
+ const text = yield* readText(PACKAGE_MANIFEST);
113
+ const manifest = text === null ? null : parsedJson(text);
114
+ const omp = Predicate.hasProperty(manifest, "omp") ? manifest.omp : undefined;
115
+ // Predicate.isObject holds for no array and no null, as the script's check does.
116
+ return Predicate.isObject(omp)
117
+ ? `plugin author: yes (${PACKAGE_MANIFEST} omp object)`
118
+ : "plugin author: no";
119
+ });
120
+
121
+ /** The root .claude entries are only reported; agent-first-setup cleans them up. */
122
+ const auditLines = Effect.fn("bridgeCheck.auditLines")(function* (repo: Repository) {
123
+ const lines: Array<string> = [];
124
+ for (const file of AUDIT_FILES)
125
+ lines.push(`${(yield* isFile(file)) ? "EXISTS" : "MISSING"} ${AUDIT_LABELS[file] ?? file}`);
126
+ lines.push(
127
+ ...(yield* guarded("legacy entries:", legacyClaudeLines())),
128
+ ...(yield* guarded(
129
+ "legacy:",
130
+ Effect.flatMap(legacyFiles(repo), (files) =>
131
+ Effect.forEach(files, (file) =>
132
+ Effect.map(isAgentsLink(file), (link) =>
133
+ link ? `legacy link: ${file}` : `legacy: ${file}`,
134
+ ),
135
+ ),
136
+ ),
137
+ )),
138
+ ...(yield* guarded(
139
+ "personal:",
140
+ Effect.map(personalFiles(repo), (files) => files.map((file) => `personal: ${file}`)),
141
+ )),
142
+ ...(yield* guarded(
143
+ "plugin author:",
144
+ Effect.map(pluginAuthorLine(), (line) => [line]),
145
+ )),
146
+ );
147
+ return lines;
148
+ });
149
+
150
+ /** The root routing belongs to context-tree; this skill only reports it. */
151
+ const routingLines = Effect.fn("bridgeCheck.routingLines")(function* (repo: Repository) {
152
+ const { unroutedNodes, deadRoutes } = yield* routingGaps(listing(repo));
153
+ return [
154
+ ...unroutedNodes.map((node) => `HANDOFF context-tree: unrouted node ${node}`),
155
+ ...deadRoutes.map((route) => `HANDOFF context-tree: dead route ${route}`),
156
+ ];
157
+ });
158
+
159
+ const verifyLines = Effect.fn("bridgeCheck.verifyLines")(function* (
160
+ repo: Repository,
161
+ expectedFiles: ReadonlyArray<string>,
162
+ ) {
163
+ return [
164
+ ...((yield* isFile("AGENTS.md")) ? [] : ["BROKEN: AGENTS.md missing"]),
165
+ ...(yield* guarded(
166
+ "legacy:",
167
+ Effect.map(legacyFiles(repo), (files) =>
168
+ files.map((file) => `BROKEN: legacy CLAUDE.md still present: ${file}`),
169
+ ),
170
+ )),
171
+ ...(yield* Effect.filter(expectedFiles, (file) =>
172
+ Effect.map(isFile(file), (found) => !found),
173
+ )).map((file) => `BROKEN: ${file} missing`),
174
+ ...(yield* guarded("routing:", routingLines(repo))),
175
+ ...(yield* guarded(
176
+ "volatile:",
177
+ Effect.flatMap(agentsDocs(listing(repo)), (docs) =>
178
+ durableDocScan(docs, { findingLabel: "VOLATILE", errorLabel: "volatile:" }),
179
+ ),
180
+ )),
181
+ ];
182
+ });
183
+
184
+ /** The paths of `--expect <path>` pairs, or null when an argument is no such pair. */
185
+ function parseExpectedFiles(args: ReadonlyArray<string>): Array<string> | null {
186
+ const files: Array<string> = [];
187
+ for (let i = 0; i < args.length; i += 2) {
188
+ const file = args[i + 1];
189
+ if (args[i] !== "--expect" || !file) return null;
190
+ files.push(file);
191
+ }
192
+ return files;
193
+ }
194
+
195
+ interface ParsedArguments {
196
+ readonly command: "audit" | "verify";
197
+ readonly expectedFiles: ReadonlyArray<string>;
198
+ }
199
+
200
+ /** The command and its expected files, or null for a usage error. */
201
+ function parseArguments(args: ReadonlyArray<string>): ParsedArguments | null {
202
+ const [command, ...rest] = args;
203
+ if (command === "audit" && rest.length === 0) return { command, expectedFiles: [] };
204
+ const expectedFiles = command === "verify" ? parseExpectedFiles(rest) : null;
205
+ return expectedFiles === null ? null : { command: "verify", expectedFiles };
206
+ }
207
+
208
+ /** Run `bridge-check <args>` and return its exit status; a usage error fails with UsageError. */
209
+ export const runBridgeCheck = Effect.fn("bridgeCheck.run")(function* (args: ReadonlyArray<string>) {
210
+ const parsed = parseArguments(args);
211
+ if (parsed === null) return yield* new UsageError({ usage: USAGE });
212
+ const files = yield* AgentDocsFiles;
213
+ const gitRoot = yield* repositoryRoot();
214
+ const repo: Repository = {
215
+ root: gitRoot ?? (yield* files.workingFolder),
216
+ inGit: gitRoot !== null,
217
+ };
218
+ // Every check reads paths relative to the root, as the skill runs its blocks from there.
219
+ yield* files.changeFolder(repo.root);
220
+ const lines =
221
+ parsed.command === "audit"
222
+ ? yield* auditLines(repo)
223
+ : yield* verifyLines(repo, parsed.expectedFiles);
224
+ yield* printLines(lines);
225
+ return lines.some((line) => line.startsWith("ERROR")) ? 2 : 0;
226
+ });
@@ -0,0 +1,63 @@
1
+ /**
2
+ * The dispatcher of `docks-kit agent-docs <helper> <command> [args]`. Each helper prints what its former script
3
+ * printed and returns its exit status; this edge maps each tagged failure to the stderr and stdout lines and the exit
4
+ * status of that script.
5
+ */
6
+ import { Effect } from "effect";
7
+
8
+ import type { FileError, SpawnError } from "../plan/types";
9
+ import { type AgentRefusal, type AgentUnreadable, runAgentFirst } from "./agentFirstCheck";
10
+ import { runBridgeCheck } from "./bridgeCheck";
11
+ import { runPrTemplate } from "./prTemplate";
12
+ import { writeStderr, writeStdout } from "./services";
13
+ import { UsageError } from "./shared";
14
+ import { runVerifySkill } from "./verifySkill";
15
+
16
+ const USAGE =
17
+ "usage: docks-kit agent-docs pr-template|verify-skill|agent-first|bridge-check <command> [args]";
18
+
19
+ const HELPERS = {
20
+ "pr-template": runPrTemplate,
21
+ "verify-skill": runVerifySkill,
22
+ "agent-first": runAgentFirst,
23
+ "bridge-check": runBridgeCheck,
24
+ } as const;
25
+
26
+ const isHelper = (word: string | undefined): word is keyof typeof HELPERS =>
27
+ word !== undefined && Object.hasOwn(HELPERS, word);
28
+
29
+ const printUsage = (error: UsageError): Effect.Effect<number> =>
30
+ writeStderr(`${error.usage}\n`).pipe(Effect.as(1));
31
+
32
+ const printRefusal = (error: AgentRefusal): Effect.Effect<number> =>
33
+ writeStdout(`ERROR convert-agent ${error.file}: ${error.reason}; port it by hand\n`).pipe(
34
+ Effect.as(2),
35
+ );
36
+
37
+ const printUnreadable = (error: AgentUnreadable): Effect.Effect<number> =>
38
+ writeStderr(`agent-first-check: cannot read ${error.file} (${error.detail})\n`).pipe(
39
+ Effect.andThen(writeStdout(`ERROR convert-agent ${error.file}: cannot read the file\n`)),
40
+ Effect.as(2),
41
+ );
42
+
43
+ // The scripts ended with an uncaught exception, exit status 1, when the working folder could not change to the
44
+ // repository root or the runtime refused git's arguments.
45
+ const printCrash = (error: FileError | SpawnError): Effect.Effect<number> =>
46
+ writeStderr(`agent-docs: ${error.message}\n`).pipe(Effect.as(1));
47
+
48
+ /** Run `docks-kit agent-docs <args>` and return its exit status. */
49
+ export const runAgentDocs = Effect.fn("agentDocs.run")(function* (args: ReadonlyArray<string>) {
50
+ const [helper, ...rest] = args;
51
+ const outcome = isHelper(helper)
52
+ ? HELPERS[helper](rest)
53
+ : Effect.fail(new UsageError({ usage: USAGE }));
54
+ return yield* outcome.pipe(
55
+ Effect.catchTags({
56
+ UsageError: printUsage,
57
+ AgentRefusal: printRefusal,
58
+ AgentUnreadable: printUnreadable,
59
+ FileError: printCrash,
60
+ SpawnError: printCrash,
61
+ }),
62
+ );
63
+ });
@@ -0,0 +1,211 @@
1
+ /**
2
+ * `docks-kit agent-docs pr-template detect | gate`: find the pull-request templates that GitHub reads, and gate the
3
+ * write of a new `.github/pull_request_template.md`. GitHub reads a template from the root, from `docs/`, or from
4
+ * `.github/`: a file named `pull_request_template`, `pull_request_template.md`, or `pull_request_template.txt` in any
5
+ * letter case, or a `PULL_REQUEST_TEMPLATE` folder that holds a `.md` or `.txt` file. The rules and the meaning of each
6
+ * line live in the plan-workspace reference `pull-request-template.md`.
7
+ *
8
+ * Output lines:
9
+ * detect one `pull-request template: <path> (<kind>)` line for each usable entry, one
10
+ * `pull-request template: unusable <path> (<reason>)` line for each unusable entry, and
11
+ * `pull-request template: none` when no entry is usable. Folders in the order `.`, `docs`, `.github`;
12
+ * inside a folder, by byte order of the name. Paths are relative to the repository root.
13
+ * gate exactly one of `target occupied: write nothing`, `target free`, or
14
+ * `no write: a usable template exists, or .github is a symlink`.
15
+ * Either command prints `ERROR pull-request template check failed (see the message above)` when the check cannot
16
+ * finish, for example outside a git repository; the cause is on stderr.
17
+ *
18
+ * Exit status: 2 after an ERROR line, 1 for a usage error, otherwise 0.
19
+ */
20
+ import path from "node:path";
21
+
22
+ import { Effect } from "effect";
23
+
24
+ import { byteOrder, UsageError } from "./shared";
25
+ import {
26
+ AgentDocsFiles,
27
+ AgentDocsGit,
28
+ errorDetail,
29
+ type FolderEntry,
30
+ printLines,
31
+ writeStderr,
32
+ } from "./services";
33
+
34
+ const USAGE = "usage: docks-kit agent-docs pr-template detect | gate";
35
+ const ERROR_LINE = "ERROR pull-request template check failed (see the message above)";
36
+ const NONE_LINE = "pull-request template: none";
37
+ const TEMPLATE_FOLDERS: ReadonlyArray<string> = [".", "docs", ".github"];
38
+ const TEMPLATE_NAMES: ReadonlySet<string> = new Set([
39
+ "pull_request_template",
40
+ "pull_request_template.md",
41
+ "pull_request_template.txt",
42
+ ]);
43
+ // Only this name makes a folder a template folder; a folder with a file name is unusable.
44
+ const FOLDER_NAME = "pull_request_template";
45
+ // Any entry with a supported name occupies the target, also an unusable one.
46
+ const TARGET_OCCUPIED =
47
+ /^pull-request template: (unusable )?\.github\/pull_request_template\.md \(/iu;
48
+
49
+ /** The detect lines; on `ok: false`, the lines found before the failure, whose cause is on stderr. */
50
+ export interface PrTemplateResult {
51
+ readonly ok: boolean;
52
+ readonly lines: ReadonlyArray<string>;
53
+ }
54
+
55
+ interface Classified {
56
+ readonly usable: boolean;
57
+ readonly line: string;
58
+ }
59
+
60
+ /**
61
+ * The repository root that `git rev-parse --show-toplevel` prints for `cwd`, or null when git fails; git's own
62
+ * message then is on stderr.
63
+ */
64
+ const gitRoot = Effect.fn("prTemplate.gitRoot")(function* (cwd: string) {
65
+ const git = yield* AgentDocsGit;
66
+ const result = yield* git.run(["rev-parse", "--show-toplevel"], cwd);
67
+ if (result.error !== undefined) {
68
+ yield* writeStderr(
69
+ `pr-template: cannot run git rev-parse (${result.error.message}); install git and retry\n`,
70
+ );
71
+ return null;
72
+ }
73
+ yield* writeStderr(result.stderr);
74
+ return result.status === 0 ? result.stdout.replace(/\n+$/u, "") : null;
75
+ });
76
+
77
+ /**
78
+ * The entries of a folder, or null after a message on stderr: an unreadable folder leaves the answer open, so the
79
+ * caller must not report "none".
80
+ */
81
+ const readFolder = Effect.fn("prTemplate.readFolder")(function* (folder: string, shown: string) {
82
+ const files = yield* AgentDocsFiles;
83
+ return yield* files
84
+ .readFolder(folder)
85
+ .pipe(
86
+ Effect.catchTag("FileError", (error) =>
87
+ writeStderr(
88
+ `pr-template: cannot list the folder ${shown} (${errorDetail(error)}); make it readable and run the check again\n`,
89
+ ).pipe(Effect.as<ReadonlyArray<FolderEntry> | null>(null)),
90
+ ),
91
+ );
92
+ });
93
+
94
+ /**
95
+ * A template folder is usable when it holds a regular `.md` or `.txt` file itself; a symlink inside the folder does
96
+ * not count. Null when the folder cannot be read.
97
+ */
98
+ const holdsTemplateFile = Effect.fn("prTemplate.holdsTemplateFile")(function* (
99
+ folder: string,
100
+ shown: string,
101
+ ) {
102
+ const entries = yield* readFolder(folder, shown);
103
+ if (entries === null) return null;
104
+ return entries.some((entry) => entry.kind === "file" && /\.(md|txt)$/iu.test(entry.name));
105
+ });
106
+
107
+ /** Classify one entry with a supported name; null when a folder inside it cannot be read. */
108
+ const classify = Effect.fn("prTemplate.classify")(function* (
109
+ root: string,
110
+ shown: string,
111
+ name: string,
112
+ ) {
113
+ const files = yield* AgentDocsFiles;
114
+ const file = path.join(root, shown);
115
+ const via = (yield* files.isSymlink(file)) ? "symlink to " : "";
116
+ const stat = yield* files.stat(file);
117
+ let classified: Classified;
118
+ if (stat === "file") {
119
+ classified = { usable: true, line: `pull-request template: ${shown} (${via}file)` };
120
+ } else if (stat === "directory" && name.toLowerCase() === FOLDER_NAME) {
121
+ const holds = yield* holdsTemplateFile(file, `${shown}/`);
122
+ if (holds === null) return null;
123
+ classified = holds
124
+ ? { usable: true, line: `pull-request template: ${shown} (${via}folder)` }
125
+ : {
126
+ usable: false,
127
+ line: `pull-request template: unusable ${shown} (${via}folder without a .md or .txt file)`,
128
+ };
129
+ } else if (stat === "directory") {
130
+ classified = {
131
+ usable: false,
132
+ line: `pull-request template: unusable ${shown} (${via}folder with a file name)`,
133
+ };
134
+ } else if (via) {
135
+ classified = {
136
+ usable: false,
137
+ line: `pull-request template: unusable ${shown} (broken symlink)`,
138
+ };
139
+ } else {
140
+ classified = {
141
+ usable: false,
142
+ line: `pull-request template: unusable ${shown} (not a regular file)`,
143
+ };
144
+ }
145
+ return classified;
146
+ });
147
+
148
+ /**
149
+ * The detect lines for the repository at `root` (absolute), or at the git root of the current folder when `root` is
150
+ * null.
151
+ */
152
+ export const prTemplateLines = Effect.fn("prTemplate.lines")(function* (root: string | null) {
153
+ const files = yield* AgentDocsFiles;
154
+ const top = root ?? (yield* gitRoot(yield* files.workingFolder));
155
+ const lines: Array<string> = [];
156
+ const failed = (): PrTemplateResult => ({ ok: false, lines });
157
+ if (top === null) return failed();
158
+ let usable = false;
159
+ for (const dir of TEMPLATE_FOLDERS) {
160
+ const folder = path.join(top, dir);
161
+ if ((yield* files.stat(folder)) !== "directory") continue;
162
+ // `find <dir>` does not descend into a starting point that is a symlink, so a linked `docs` or `.github` lists
163
+ // no entry.
164
+ if (yield* files.isSymlink(folder)) continue;
165
+ const entries = yield* readFolder(folder, dir);
166
+ if (entries === null) return failed();
167
+ // The supported names are ASCII, so byte order is the order of the default sort.
168
+ const names = entries
169
+ .map((entry) => entry.name)
170
+ .filter((name) => TEMPLATE_NAMES.has(name.toLowerCase()))
171
+ .sort(byteOrder);
172
+ for (const name of names) {
173
+ const entry = yield* classify(top, `${dir}/${name}`, name);
174
+ if (entry === null) return failed();
175
+ usable ||= entry.usable;
176
+ lines.push(entry.line);
177
+ }
178
+ }
179
+ if (!usable) lines.push(NONE_LINE);
180
+ const result: PrTemplateResult = { ok: true, lines };
181
+ return result;
182
+ });
183
+
184
+ /** The write gate for `.github/pull_request_template.md`: one line from the detect lines. */
185
+ const gateLine = Effect.fn("prTemplate.gateLine")(function* (
186
+ top: string,
187
+ lines: ReadonlyArray<string>,
188
+ ) {
189
+ const files = yield* AgentDocsFiles;
190
+ if (lines.some((line) => TARGET_OCCUPIED.test(line))) return "target occupied: write nothing";
191
+ if (lines.at(-1) === NONE_LINE && !(yield* files.isSymlink(path.join(top, ".github"))))
192
+ return "target free";
193
+ return "no write: a usable template exists, or .github is a symlink";
194
+ });
195
+
196
+ /** Run `pr-template <args>` and return its exit status; a usage error fails with UsageError. */
197
+ export const runPrTemplate = Effect.fn("prTemplate.run")(function* (args: ReadonlyArray<string>) {
198
+ const [command, ...rest] = args;
199
+ if ((command !== "detect" && command !== "gate") || rest.length > 0)
200
+ return yield* new UsageError({ usage: USAGE });
201
+ const files = yield* AgentDocsFiles;
202
+ const top = yield* gitRoot(yield* files.workingFolder);
203
+ const result = top === null ? { ok: false, lines: [] } : yield* prTemplateLines(top);
204
+ if (top === null || !result.ok) {
205
+ // The shell wrapper dropped the lines found before the failure; print only the ERROR line.
206
+ yield* printLines([ERROR_LINE]);
207
+ return 2;
208
+ }
209
+ yield* printLines(command === "detect" ? result.lines : [yield* gateLine(top, result.lines)]);
210
+ return 0;
211
+ });