@autotelic/jig-cli 0.0.0-stage → 0.1.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 (81) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +169 -2
  3. package/bin/jig.js +23 -0
  4. package/dist/baseline.d.ts +8 -0
  5. package/dist/baseline.d.ts.map +1 -0
  6. package/dist/baseline.js +30 -0
  7. package/dist/baseline.js.map +1 -0
  8. package/dist/cli.d.ts +2 -0
  9. package/dist/cli.d.ts.map +1 -0
  10. package/dist/cli.js +342 -0
  11. package/dist/cli.js.map +1 -0
  12. package/dist/commands.d.ts +50 -0
  13. package/dist/commands.d.ts.map +1 -0
  14. package/dist/commands.js +145 -0
  15. package/dist/commands.js.map +1 -0
  16. package/dist/config.d.ts +32 -0
  17. package/dist/config.d.ts.map +1 -0
  18. package/dist/config.js +59 -0
  19. package/dist/config.js.map +1 -0
  20. package/dist/engines.d.ts +85 -0
  21. package/dist/engines.d.ts.map +1 -0
  22. package/dist/engines.js +575 -0
  23. package/dist/engines.js.map +1 -0
  24. package/dist/exec.d.ts +16 -0
  25. package/dist/exec.d.ts.map +1 -0
  26. package/dist/exec.js +13 -0
  27. package/dist/exec.js.map +1 -0
  28. package/dist/gate.d.ts +46 -0
  29. package/dist/gate.d.ts.map +1 -0
  30. package/dist/gate.js +82 -0
  31. package/dist/gate.js.map +1 -0
  32. package/dist/git.d.ts +5 -0
  33. package/dist/git.d.ts.map +1 -0
  34. package/dist/git.js +39 -0
  35. package/dist/git.js.map +1 -0
  36. package/dist/gitattributes.d.ts +27 -0
  37. package/dist/gitattributes.d.ts.map +1 -0
  38. package/dist/gitattributes.js +63 -0
  39. package/dist/gitattributes.js.map +1 -0
  40. package/dist/index.d.ts +12 -0
  41. package/dist/index.d.ts.map +1 -0
  42. package/dist/index.js +12 -0
  43. package/dist/index.js.map +1 -0
  44. package/dist/init.d.ts +163 -0
  45. package/dist/init.d.ts.map +1 -0
  46. package/dist/init.js +1855 -0
  47. package/dist/init.js.map +1 -0
  48. package/dist/menu.d.ts +82 -0
  49. package/dist/menu.d.ts.map +1 -0
  50. package/dist/menu.js +388 -0
  51. package/dist/menu.js.map +1 -0
  52. package/dist/opencode.d.ts +66 -0
  53. package/dist/opencode.d.ts.map +1 -0
  54. package/dist/opencode.js +392 -0
  55. package/dist/opencode.js.map +1 -0
  56. package/dist/package-json.d.ts +13 -0
  57. package/dist/package-json.d.ts.map +1 -0
  58. package/dist/package-json.js +33 -0
  59. package/dist/package-json.js.map +1 -0
  60. package/dist/projections.d.ts +140 -0
  61. package/dist/projections.d.ts.map +1 -0
  62. package/dist/projections.js +186 -0
  63. package/dist/projections.js.map +1 -0
  64. package/dist/render.d.ts +21 -0
  65. package/dist/render.d.ts.map +1 -0
  66. package/dist/render.js +131 -0
  67. package/dist/render.js.map +1 -0
  68. package/dist/room.d.ts +16 -0
  69. package/dist/room.d.ts.map +1 -0
  70. package/dist/room.js +56 -0
  71. package/dist/room.js.map +1 -0
  72. package/dist/run.d.ts +10 -0
  73. package/dist/run.d.ts.map +1 -0
  74. package/dist/run.js +18 -0
  75. package/dist/run.js.map +1 -0
  76. package/extensions/jig.ts +465 -0
  77. package/package.json +78 -3
  78. package/skills/feedback-loop/SKILL.md +14 -0
  79. package/skills/intercom-setup/SKILL.md +20 -0
  80. package/skills/project-run/SKILL.md +18 -0
  81. package/skills/room/SKILL.md +17 -0
package/dist/init.js ADDED
@@ -0,0 +1,1855 @@
1
+ import { existsSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { Effect, FileSystem, Option, Path, PlatformError } from "effect";
4
+ import { cutlistDefaultOutput, decodeCutlistConfig, parseJson, isRecord, } from "@autotelic/protocol";
5
+ import { emptyBaseline, readBaseline, writeBaseline } from "./baseline.js";
6
+ import { loadConfig } from "./config.js";
7
+ import { resolveEngineCommand } from "./engines.js";
8
+ import { exec } from "./exec.js";
9
+ import { GENERATED_BEGIN, GENERATED_END, generatedRules, mergeGitattributes, } from "./gitattributes.js";
10
+ import { packageJsonOf } from "./package-json.js";
11
+ /** joggle's own ledger: identities are `rule + file set`, so a moved line does not re-fail. */
12
+ const JOGGLE_BASELINE = ".joggle-baseline.json";
13
+ /** Whether a command resolves from the project or the ambient PATH. */
14
+ const onPath = (name) => (process.env.PATH ?? "").split(":").some((dir) => dir !== "" && existsSync(join(dir, name)));
15
+ const available = (input) => resolveEngineCommand(input) !== input.command || onPath(input.command);
16
+ /** The package manager, from the field a repo pins or the lockfile it committed. */
17
+ const packageManagerOf = (field, files) => {
18
+ if (field?.startsWith("pnpm@") === true)
19
+ return "pnpm";
20
+ if (field?.startsWith("yarn@") === true)
21
+ return "yarn";
22
+ if (field?.startsWith("bun@") === true)
23
+ return "bun";
24
+ if (field?.startsWith("npm@") === true)
25
+ return "npm";
26
+ if (files.includes("pnpm-lock.yaml") || files.includes("pnpm-workspace.yaml"))
27
+ return "pnpm";
28
+ if (files.includes("yarn.lock"))
29
+ return "yarn";
30
+ if (files.includes("bun.lockb") || files.includes("bun.lock"))
31
+ return "bun";
32
+ return "npm";
33
+ };
34
+ /** The command that runs jig, preferring the repo's own install. */
35
+ const jigCommandOf = (manager, local) => {
36
+ if (!local)
37
+ return "jig";
38
+ switch (manager) {
39
+ case "pnpm":
40
+ return "pnpm jig";
41
+ case "yarn":
42
+ return "yarn jig";
43
+ case "bun":
44
+ return "bunx jig";
45
+ case "npm":
46
+ return "npx jig";
47
+ }
48
+ };
49
+ /** The strictest oxlint script, preferring one that names a config and a gate. */
50
+ const oxlintScriptOf = (scripts) => {
51
+ const candidates = [];
52
+ for (const [name, command] of Object.entries(scripts)) {
53
+ if (!command.includes("oxlint") || command.includes("--fix"))
54
+ continue;
55
+ const tokens = command.split(/\s+/u);
56
+ const start = tokens.findIndex((token) => token === "oxlint" || token.endsWith("/oxlint"));
57
+ if (start < 0)
58
+ continue;
59
+ const rest = tokens.slice(start + 1);
60
+ const index = rest.findIndex((token) => token === "-c" || token === "--config");
61
+ const config = index >= 0 ? rest[index + 1] : undefined;
62
+ // Keep the script's own scope (`src`, `--ignore-pattern …`), but drop the
63
+ // config (jig passes it) and the format (jig asks for JSON).
64
+ const args = [];
65
+ for (let cursor = 0; cursor < rest.length; cursor += 1) {
66
+ const token = rest[cursor];
67
+ if (token === "-c" || token === "--config") {
68
+ cursor += 1;
69
+ continue;
70
+ }
71
+ if (token === "--format" || token === "-f") {
72
+ cursor += 1;
73
+ continue;
74
+ }
75
+ if (token === "--fix")
76
+ continue;
77
+ if (token !== undefined)
78
+ args.push(token);
79
+ }
80
+ const score = (config === undefined ? 0 : 2) + (/error|gate|strict/iu.test(name) ? 2 : 0);
81
+ candidates.push({ script: name, config, args, score });
82
+ }
83
+ return Option.fromUndefinedOr(candidates.sort((left, right) => right.score - left.score)[0]);
84
+ };
85
+ /** The oxlint config a repo keeps, preferring one whose name says "gate". */
86
+ const oxlintConfigOf = (files) => {
87
+ const configs = files.filter((name) => (name.includes("oxlint") || name === ".oxlintrc") &&
88
+ /\.(?:json|ts|js|mjs|cjs|mts|cts)$/u.test(name));
89
+ return Option.fromUndefinedOr(configs.sort((left, right) => {
90
+ const score = (name) => /error|gate|strict/iu.test(name) ? 2 : name === ".oxlintrc.json" ? 1 : 0;
91
+ return score(right) - score(left) || left.localeCompare(right);
92
+ })[0]);
93
+ };
94
+ /** Whether a config loads plumb, so the `plumb` engine is not a misnamed oxlint. */
95
+ const loadsPlumb = (text) => text.includes("@autotelic/plumb");
96
+ /** Whether a tsconfig exists at the root or one level under a common workspace directory. */
97
+ const hasTypeScript = (fs, path, root, files) => Effect.gen(function* () {
98
+ if (files.includes("tsconfig.json"))
99
+ return true;
100
+ for (const directory of ["apps", "packages", "services"]) {
101
+ if (!files.includes(directory))
102
+ continue;
103
+ const children = yield* Effect.orElseSucceed(fs.readDirectory(path.join(root, directory)), () => []);
104
+ for (const child of children) {
105
+ const exists = yield* Effect.orElseSucceed(fs.exists(path.join(root, directory, child, "tsconfig.json")), () => false);
106
+ if (exists)
107
+ return true;
108
+ }
109
+ }
110
+ return false;
111
+ });
112
+ /** The first sentence or two that describe the repository, from prose it already keeps. */
113
+ const repositorySummaryOf = (input) => Effect.gen(function* () {
114
+ for (const file of ["AGENTS.md", "README.md"]) {
115
+ if (!input.files.includes(file))
116
+ continue;
117
+ const text = yield* Effect.orElseSucceed(input.fs.readFileString(input.path.join(input.root, file)), () => "");
118
+ const lines = text.split("\n").map((line) => line.trim());
119
+ const project = lines.find((line) => line.startsWith("**Project**:"));
120
+ const stack = lines.find((line) => line.startsWith("**Stack**:"));
121
+ if (project !== undefined || stack !== undefined) {
122
+ return [project, stack]
123
+ .filter((line) => line !== undefined)
124
+ .join(" ")
125
+ .replaceAll("**", "")
126
+ .slice(0, 600);
127
+ }
128
+ const paragraph = text
129
+ .split(/\n\s*\n/u)
130
+ .map((part) => part.trim())
131
+ .find((part) => part.length > 0 && !part.startsWith("#") && !part.startsWith("!["));
132
+ if (paragraph !== undefined) {
133
+ return paragraph.replace(/\s+/gu, " ").slice(0, 600);
134
+ }
135
+ }
136
+ return input.fallback === undefined ? "" : input.fallback;
137
+ });
138
+ /* -------------------------------------------------------------------------- */
139
+ /* Cutlist */
140
+ /* -------------------------------------------------------------------------- */
141
+ /** Directories a UI scan never descends into. */
142
+ const NOT_UI = new Set([
143
+ ".git",
144
+ ".next",
145
+ ".turbo",
146
+ ".cache",
147
+ "build",
148
+ "coverage",
149
+ "dist",
150
+ "examples",
151
+ "fixtures",
152
+ "test",
153
+ "tests",
154
+ "node_modules",
155
+ "out",
156
+ "repos",
157
+ "tools",
158
+ ]);
159
+ /** Whether a directory exists. */
160
+ const existsAt = (input) => Effect.orElseSucceed(input.fs.exists(input.path.join(input.root, input.relative)), () => false);
161
+ /** The directories that look like UI roots: one holding `components` or `routes`. */
162
+ const uiRootsOf = (fs, path, root) => Effect.gen(function* () {
163
+ const found = [];
164
+ const walk = (relative, depth) => Effect.gen(function* () {
165
+ if (found.length >= 8 || depth > 4)
166
+ return;
167
+ const entries = yield* Effect.orElseSucceed(fs.readDirectory(relative === "" ? root : path.join(root, relative)), () => []);
168
+ // `routes` alone is an API: a server router has routes and no components.
169
+ // A UI root is the one that owns components.
170
+ if (entries.includes("components")) {
171
+ found.push(relative === "" ? "." : relative);
172
+ return;
173
+ }
174
+ for (const entry of entries) {
175
+ if (NOT_UI.has(entry))
176
+ continue;
177
+ const child = relative === "" ? entry : relative + "/" + entry;
178
+ const directory = yield* Effect.orElseSucceed(fs.stat(path.join(root, child)).pipe(Effect.map((info) => info.type === "Directory")), () => false);
179
+ if (directory)
180
+ yield* walk(child, depth + 1);
181
+ }
182
+ });
183
+ yield* walk("", 0);
184
+ return found;
185
+ });
186
+ /** The first file that exists among the candidates. */
187
+ const firstOf = (fs, path, root, candidates) => Effect.gen(function* () {
188
+ for (const candidate of candidates) {
189
+ if (yield* existsAt({ fs, path, root, relative: candidate }))
190
+ return candidate;
191
+ }
192
+ return undefined;
193
+ });
194
+ /** The alias targets a root's parent tsconfig declares, resolved to the repository. */
195
+ const aliasesOf = (fs, path, root, roots) => Effect.gen(function* () {
196
+ const normalise = (value) => {
197
+ const parts = [];
198
+ for (const part of value.split("/")) {
199
+ if (part === "" || part === ".")
200
+ continue;
201
+ if (part === "..") {
202
+ parts.pop();
203
+ continue;
204
+ }
205
+ parts.push(part);
206
+ }
207
+ return parts.join("/");
208
+ };
209
+ const found = new Map();
210
+ for (const entry of roots) {
211
+ const parent = entry.split("/").slice(0, -1).join("/");
212
+ // A root that *is* the app directory keeps its tsconfig inside it (`apps/web`),
213
+ // while a root one level down (`libs/ui/src`) keeps it in the parent. Reading only
214
+ // the parent made every `@/…` import in a flat app unresolved: on a 7k-file
215
+ // monorepo that was 3,484 orphans and a use-graph with almost no edges.
216
+ const candidates = [
217
+ entry === "." ? "tsconfig.json" : entry + "/tsconfig.json",
218
+ parent === "" ? "tsconfig.json" : parent + "/tsconfig.json",
219
+ ];
220
+ for (const file of candidates) {
221
+ const text = yield* Effect.orElseSucceed(fs.readFileString(path.join(root, file)), () => "");
222
+ const directory = file.includes("/") ? file.slice(0, file.lastIndexOf("/")) : "";
223
+ let matched = false;
224
+ for (const match of text.matchAll(/"([^"]+\/\*)"\s*:\s*\[\s*"([^"]+)"/gu)) {
225
+ const key = match[1];
226
+ const target = match[2];
227
+ if (key === undefined || target === undefined)
228
+ continue;
229
+ const resolved = normalise(directory === "" ? target : directory + "/" + target);
230
+ const list = found.get(key) ?? [];
231
+ if (!list.includes(resolved))
232
+ list.push(resolved);
233
+ found.set(key, list);
234
+ matched = true;
235
+ }
236
+ // The nearest config that declares paths wins; a config that only `extends`
237
+ // another contributes nothing here, so the parent is still read.
238
+ if (matched)
239
+ break;
240
+ }
241
+ }
242
+ return Object.fromEntries(found);
243
+ });
244
+ /** What one UI root's stylesheets and its tailwind config say about the design system. */
245
+ const tokensFor = (fs, path, root, roots) => Effect.gen(function* () {
246
+ const CONFIGS = ["tailwind.config.ts", "tailwind.config.js", "tailwind.config.mjs"];
247
+ const STYLES = [
248
+ "app/tailwind.css",
249
+ "app.css",
250
+ "styles/app.css",
251
+ "app/styles/app.css",
252
+ "tailwind.css",
253
+ ];
254
+ const scores = [];
255
+ for (const entry of roots) {
256
+ const parent = entry.split("/").slice(0, -1).join("/");
257
+ const config = yield* firstOf(fs, path, root, [entry, parent].flatMap((directory) => CONFIGS.map((name) => (directory === "" ? name : directory + "/" + name))));
258
+ const css = yield* firstOf(fs, path, root, STYLES.map((name) => entry + "/" + name));
259
+ const configText = config === undefined
260
+ ? ""
261
+ : yield* Effect.orElseSucceed(fs.readFileString(path.join(root, config)), () => "");
262
+ const cssText = css === undefined
263
+ ? ""
264
+ : yield* Effect.orElseSucceed(fs.readFileString(path.join(root, css)), () => "");
265
+ const properties = [...cssText.matchAll(/--[\w-]+\s*:/gu)].length;
266
+ const colours = [...configText.matchAll(/#[0-9a-f]{3,8}\b/giu)].length;
267
+ const rootLayer = /:root\s*\{/u.test(cssText);
268
+ scores.push({
269
+ entry,
270
+ from: config ?? css ?? "tailwind.config.ts",
271
+ vars: css === undefined || config === undefined ? undefined : css,
272
+ properties,
273
+ colours,
274
+ rootLayer,
275
+ // A token layer is the thing being chosen: `:root` plus the properties it declares,
276
+ // weighted against the palette its tailwind config carries. The first root alphabetically
277
+ // used to win, which on a two-app repo picked the app with 7 tokens over the one with 31.
278
+ score: (rootLayer ? 3 : 0) + properties + colours,
279
+ });
280
+ }
281
+ const best = [...scores].sort((left, right) => right.score - left.score || left.entry.localeCompare(right.entry))[0];
282
+ if (best === undefined)
283
+ return { config: { from: "tailwind.config.ts" } };
284
+ const config = best.vars === undefined ? { from: best.from } : { from: best.from, vars: best.vars };
285
+ const other = scores.find((candidate) => candidate.entry !== best.entry);
286
+ if (other === undefined || other.score === 0)
287
+ return { config };
288
+ // A two-app repo has two palettes and the draft describes one: say which one it left out,
289
+ // with the numbers, so a person can disagree with the choice instead of finding it at 7 tokens.
290
+ return {
291
+ config,
292
+ note: "tokens come from " +
293
+ best.entry +
294
+ " (" +
295
+ String(best.colours) +
296
+ " colour key(s), " +
297
+ String(best.properties) +
298
+ " custom propert" +
299
+ (best.properties === 1 ? "y" : "ies") +
300
+ (best.rootLayer ? ", a :root layer" : "") +
301
+ "); " +
302
+ other.entry +
303
+ " keeps its own palette (" +
304
+ String(other.colours) +
305
+ " colour key(s), " +
306
+ String(other.properties) +
307
+ " custom propert" +
308
+ (other.properties === 1 ? "y" : "ies") +
309
+ (other.rootLayer ? "" : ", behind [data-theme]") +
310
+ ") that this vocabulary does not describe",
311
+ };
312
+ });
313
+ /** A cutlist config inferred from common UI layouts, for a person to review. */
314
+ const cutlistDraftOf = (fs, path, root) => Effect.gen(function* () {
315
+ const roots = yield* uiRootsOf(fs, path, root);
316
+ if (roots.length === 0)
317
+ return undefined;
318
+ const anyUnder = (suffix) => Effect.map(Effect.forEach(roots, (entry) => existsAt({ fs, path, root, relative: entry + suffix })), (values) => values.some(Boolean));
319
+ const primitive = (yield* anyUnder("/components/ui")) ? ["components/ui"] : [];
320
+ const shared = (yield* anyUnder("/components")) ? ["components"] : [];
321
+ const local = (yield* anyUnder("/routes")) ? ["routes"] : [];
322
+ const alias = yield* aliasesOf(fs, path, root, roots);
323
+ const tokens = yield* tokensFor(fs, path, root, roots);
324
+ const draft = {
325
+ $schema: "https://autotelic.dev/tackle/protocol/cutlist.config.json",
326
+ roots,
327
+ tiers: { primitive, shared, local },
328
+ tokens: tokens.config,
329
+ ownership: { routeOwner: "first-segment", transitive: false },
330
+ // Spell the paths out: a reviewer should see what `build` will write, and
331
+ // `jig init` uses the same map for `.gitattributes`.
332
+ output: cutlistDefaultOutput,
333
+ };
334
+ const config = Object.keys(alias).length === 0 ? draft : { ...draft, alias };
335
+ return tokens.note === undefined ? { config } : { config, note: tokens.note };
336
+ });
337
+ /** The workspace directories a pnpm/npm workspace declares that actually hold a package. */
338
+ const workspaceDirsOf = (fs, path, root, files) => Effect.gen(function* () {
339
+ const text = files.includes("pnpm-workspace.yaml")
340
+ ? yield* Effect.orElseSucceed(fs.readFileString(path.join(root, "pnpm-workspace.yaml")), () => "")
341
+ : "";
342
+ const globs = [...text.matchAll(/^\s*-\s*["']?([^"'\s#]+)["']?\s*$/gmu)]
343
+ .map((match) => match[1])
344
+ .filter((glob) => glob !== undefined && glob.endsWith("/*"));
345
+ const found = [];
346
+ for (const glob of globs) {
347
+ const prefix = glob.slice(0, -2);
348
+ const entries = yield* Effect.orElseSucceed(fs.readDirectory(path.join(root, prefix)), () => []);
349
+ for (const entry of [...entries].sort((left, right) => left.localeCompare(right))) {
350
+ const relative = prefix + "/" + entry + "/package.json";
351
+ if (yield* existsAt({ fs, path, root, relative }))
352
+ found.push(prefix + "/" + entry);
353
+ }
354
+ }
355
+ return found;
356
+ });
357
+ /**
358
+ * The tiers a UI root is split into, most depended-upon first, and the directories each names.
359
+ *
360
+ * `support` is the tier that makes a routes split usable at all: `utils/`, `lib/`, `models/`,
361
+ * `hooks/` and `types/` are what a route imports, and a draft that leaves them in the root
362
+ * catch-all puts them ABOVE `routes` -- so every legitimate import from a route reads as
363
+ * upward. On the first adopter that was 731 of 856 findings.
364
+ *
365
+ * Support comes first, below the primitives, because `components/ui/Button` importing
366
+ * `~/utils/cn` is normal and must not be a direction finding. The trade is that a primitive
367
+ * may then import a model, which is what `forbid` and `layer-purity` are for: direction
368
+ * cannot say "foundational, but not for primitives".
369
+ */
370
+ const LAYER_TIERS = [
371
+ ["support", ["utils", "lib", "models", "hooks", "types"]],
372
+ ["primitive", ["components/ui"]],
373
+ ["shared", ["components"]],
374
+ ["local", ["routes"]],
375
+ ];
376
+ /**
377
+ * Layers proposed from the workspace, and nothing more.
378
+ *
379
+ * A repo with no `architecture` block gets none of joggle's `layer-direction`
380
+ * and `layer-purity` findings -- 184 real ones on the first adopter -- because nobody told it
381
+ * that a domain package may not import React. The *include* set is decidable: the workspace
382
+ * globs plus a package.json. The *order* and the `forbid` sets are judgement, so this draft
383
+ * writes neither, and a person adds `forbid` where it is true.
384
+ */
385
+ const architectureDraftOf = (fs, path, root, files) => Effect.gen(function* () {
386
+ const dirs = yield* workspaceDirsOf(fs, path, root, files);
387
+ if (dirs.length < 2)
388
+ return undefined;
389
+ // A UI root that owns `components/ui` -> `components` -> `routes` is three layers, not one:
390
+ // a single `services/ui/**` layer cannot see the direction the majority of findings live in.
391
+ //
392
+ // Each split goes BEFORE the root that contains it, and the root stays last as the
393
+ // catch-all. joggle's `layerOf` is `layers.find()`, so a root written first matched every
394
+ // file under it and the splits never applied -- `layer-direction` reported 0 on a tree with
395
+ // 122 real findings, which reads as a clean architecture.
396
+ const uiRoots = yield* uiRootsOf(fs, path, root);
397
+ // A support name is a directory (`types/**`) or its file (`types.ts`): the first adopter's
398
+ // `app/types.ts` is imported by 60 components and every route, so leaving it in the root
399
+ // catch-all kept 87 route imports reading as upward.
400
+ const globsOf = (entry, name) => Effect.gen(function* () {
401
+ const found = [];
402
+ if (yield* existsAt({ fs, path, root, relative: entry + "/" + name }))
403
+ found.push(name + "/**");
404
+ for (const extension of ["ts", "tsx"]) {
405
+ const file = name + "." + extension;
406
+ if (yield* existsAt({ fs, path, root, relative: entry + "/" + file }))
407
+ found.push(file);
408
+ }
409
+ return found;
410
+ });
411
+ const splitsOf = (entry) => Effect.map(Effect.forEach(LAYER_TIERS, ([tier, names]) => Effect.map(Effect.forEach(names, (name) => globsOf(entry, name)), (found) => {
412
+ const includes = found.flat();
413
+ return includes.length === 0 ? undefined : { tier, includes };
414
+ })), (values) => values.filter((value) => value !== undefined));
415
+ const plan = [];
416
+ const place = (entry) => Effect.gen(function* () {
417
+ for (const split of yield* splitsOf(entry)) {
418
+ plan.push({ entry, includes: split.includes, tier: split.tier });
419
+ }
420
+ plan.push({ entry, includes: [], tier: undefined });
421
+ });
422
+ // A UI root is often a directory INSIDE a workspace package (`services/ui/app` while the
423
+ // package is `services/ui`), and the package's own `services/ui/**` catches its files first.
424
+ // So a root's splits are placed before whichever layer would otherwise claim them -- its own
425
+ // catch-all, or the package that contains it.
426
+ const placed = new Set();
427
+ for (const dir of dirs) {
428
+ const roots = uiRoots
429
+ .filter((entry) => entry === dir || entry.startsWith(dir + "/"))
430
+ .sort((left, right) => right.length - left.length);
431
+ for (const root of roots) {
432
+ yield* place(root);
433
+ placed.add(root);
434
+ }
435
+ plan.push({ entry: dir, includes: [], tier: undefined });
436
+ }
437
+ for (const root of uiRoots) {
438
+ if (placed.has(root))
439
+ continue;
440
+ yield* place(root);
441
+ }
442
+ // Names come from the path, not from the last segment: two roots that both live in `app/`
443
+ // (`services/auth-ui/app`, `services/ui/app`) produced two layers called `app-shared`, which
444
+ // a finding cannot tell apart. A last segment that is `app` is scaffolding, so it is dropped
445
+ // and the name says which root it belongs to.
446
+ const names = new Set();
447
+ const nameOf = (entry, tier) => {
448
+ const segments = entry
449
+ .split("/")
450
+ .filter((segment) => segment !== "")
451
+ .map((segment) => (segment === "." ? "root" : segment));
452
+ const trimmed = segments.at(-1) === "app" ? segments.slice(0, -1) : segments;
453
+ const parts = trimmed.length === 0 ? ["root"] : trimmed;
454
+ for (let depth = 1; depth <= parts.length; depth += 1) {
455
+ const stem = parts.slice(-depth).join("-");
456
+ const candidate = tier === undefined ? stem : stem + "-" + tier;
457
+ if (!names.has(candidate)) {
458
+ names.add(candidate);
459
+ return candidate;
460
+ }
461
+ }
462
+ const fallback = entry.replaceAll("/", "-");
463
+ const candidate = tier === undefined ? fallback : fallback + "-" + tier;
464
+ names.add(candidate);
465
+ return candidate;
466
+ };
467
+ const layers = plan.map((entry) => ({
468
+ name: nameOf(entry.entry, entry.tier),
469
+ include: entry.includes.length === 0
470
+ ? [entry.entry + "/**"]
471
+ : entry.includes.map((suffix) => entry.entry + "/" + suffix),
472
+ }));
473
+ return { layers };
474
+ });
475
+ /** A repo's declared output paths with `cutlist`'s defaults filled in under them. */
476
+ const resolvedOutput = (declared) => {
477
+ const stated = new Map(Object.entries(declared ?? {}));
478
+ const at = (key) => stated.get(key) ?? cutlistDefaultOutput[key];
479
+ // `diagrams` is opt-in, so it is copied rather than defaulted: no path, no rendering.
480
+ return {
481
+ catalog: at("catalog"),
482
+ manifest: at("manifest"),
483
+ menuJson: at("menuJson"),
484
+ menu: at("menu"),
485
+ intent: at("intent"),
486
+ patterns: at("patterns"),
487
+ patternsJson: at("patternsJson"),
488
+ recipes: at("recipes"),
489
+ recipesJson: at("recipesJson"),
490
+ hooks: at("hooks"),
491
+ tokens: at("tokens"),
492
+ diagrams: declared?.diagrams,
493
+ };
494
+ };
495
+ /**
496
+ * The directory a configured `cutlist` engine runs in, from its own `--cwd`.
497
+ *
498
+ * A repo may catalogue a tree that is not the root -- this repository catalyses its own
499
+ * exemplar -- and cutlist reads its config from the directory it scans, not from the root.
500
+ * `""` means the root, where cutlist's own default applies.
501
+ */
502
+ const cutlistCwdOf = (configured) => {
503
+ const engine = configured.find((ref) => ref.id === "cutlist");
504
+ const args = engine?.args ?? [];
505
+ const index = args.findIndex((arg) => arg === "--cwd");
506
+ const directory = index < 0 ? "" : (args[index + 1] ?? "");
507
+ return directory === "." ? "" : directory.replace(/\/+$/u, "");
508
+ };
509
+ /** Cutlist's output paths, seen from the repository root rather than the directory it scans. */
510
+ const underDirectory = (output, directory) => {
511
+ if (directory === "")
512
+ return output;
513
+ const under = (path) => directory + "/" + path;
514
+ const moved = {
515
+ catalog: under(output.catalog),
516
+ manifest: under(output.manifest),
517
+ menuJson: under(output.menuJson),
518
+ menu: under(output.menu),
519
+ intent: under(output.intent),
520
+ patterns: under(output.patterns),
521
+ patternsJson: under(output.patternsJson),
522
+ recipes: under(output.recipes),
523
+ recipesJson: under(output.recipesJson),
524
+ hooks: under(output.hooks),
525
+ tokens: under(output.tokens),
526
+ };
527
+ const diagrams = output.diagrams;
528
+ return diagrams === undefined ? moved : { ...moved, diagrams: under(diagrams) };
529
+ };
530
+ /**
531
+ * The engines a plan carries: the ones the repo configured, plus what this run detected.
532
+ *
533
+ * A repo's own entry wins for the same id -- detection cannot reproduce the `args` a project
534
+ * chose (`--ignore-pattern examples/**`, a second `oxlint` config for one package) -- and a
535
+ * configured engine whose command no longer resolves is dropped, because an engine that
536
+ * cannot run makes a report look clean when nothing ran.
537
+ */
538
+ const mergeEngines = (input) => {
539
+ const kept = [];
540
+ for (const engine of input.configured) {
541
+ const command = engine.command ?? engine.id;
542
+ // `enabled: false` is the repo's own decision, and it needs no command to honour it.
543
+ if (engine.enabled === false || available({ root: input.root, command })) {
544
+ kept.push(engine);
545
+ continue;
546
+ }
547
+ input.notes.push("engine `" +
548
+ engine.id +
549
+ "` is configured but `" +
550
+ command +
551
+ "` does not resolve; it was dropped from the plan");
552
+ }
553
+ const ids = new Set(kept.map((engine) => engine.id));
554
+ return [...kept, ...input.detected.filter((engine) => !ids.has(engine.id))];
555
+ };
556
+ /**
557
+ * Read the repository, then decide what is worth enabling.
558
+ *
559
+ * @param root - The project root.
560
+ * @param options - The gate mode the caller asked for, and whether a write may replace the config.
561
+ * @returns the profile `init` writes from.
562
+ */
563
+ export const inspectRepo = (root, options = {}) => Effect.gen(function* () {
564
+ const fs = yield* FileSystem.FileSystem;
565
+ const path = yield* Path.Path;
566
+ const files = yield* Effect.orElseSucceed(fs.readDirectory(root), () => []);
567
+ const configFile = path.join(root, "jig.config.json");
568
+ const hasConfig = yield* Effect.orElseSucceed(fs.exists(configFile), () => false);
569
+ const existing = hasConfig ? yield* loadConfig(configFile) : undefined;
570
+ const packageJson = yield* packageJsonOf(root);
571
+ const packageManager = packageManagerOf(packageJson.packageManager, files);
572
+ const scripts = packageJson.scripts;
573
+ const dependencies = packageJson.dependencies;
574
+ const localJig = files.includes("node_modules") &&
575
+ (yield* Effect.orElseSucceed(fs.exists(path.join(root, "node_modules", ".bin", "jig")), () => false));
576
+ const notes = [];
577
+ // A kept config is the effective config: do not show a gate the applied file does not
578
+ // have. Only `--force` rewrites it, so only `--force` may change the gate here.
579
+ const gateMode = existing !== undefined && options.force !== true
580
+ ? existing.gate.mode
581
+ : (options.gateMode ?? existing?.gate.mode ?? "touched-files");
582
+ if (existing !== undefined &&
583
+ options.force !== true &&
584
+ options.gateMode !== undefined &&
585
+ options.gateMode !== existing.gate.mode) {
586
+ notes.push(`jig.config.json keeps its \`${existing.gate.mode}\` gate; pass --force to apply \`${options.gateMode}\``);
587
+ }
588
+ const jigPinned = localJig || dependencies["@autotelic/jig-cli"] !== undefined;
589
+ const jig = jigCommandOf(packageManager, jigPinned);
590
+ // The CLI has to be on the machine before any of this runs. A tree that builds jig is
591
+ // the honest source for it -- the package is not on npm -- and a repo that only depends
592
+ // on it wants the published one.
593
+ const jigSource = (yield* existsAt({
594
+ fs,
595
+ path,
596
+ root,
597
+ relative: "packages/jig-cli/package.json",
598
+ }))
599
+ ? "./packages/jig-cli"
600
+ : "@autotelic/jig-cli";
601
+ // Agent surfaces already wired: the prompt says "keep this", not "add another".
602
+ const hosts = new Set();
603
+ if (yield* existsAt({ fs, path, root, relative: ".pi/settings.json" }))
604
+ hosts.add("pi");
605
+ if (files.includes("opencode.json") ||
606
+ (yield* existsAt({ fs, path, root, relative: ".opencode/plugins" }))) {
607
+ hosts.add("opencode");
608
+ }
609
+ if (!jigPinned) {
610
+ notes.push("jig resolves from PATH; pin @autotelic/jig-cli as a devDependency so CI runs the same version");
611
+ }
612
+ // A repo that already gates these findings with its own ledger (an oxlint baseline, say)
613
+ // does not want a second one silently: two ledgers over one rule set means neither is the
614
+ // record of what was reviewed.
615
+ const ownLedger = existing?.gate.baseline ?? ".jig-baseline.json";
616
+ const otherLedgers = files.filter((file) => file !== ownLedger && file.endsWith(".json") && /baseline/iu.test(file));
617
+ if (otherLedgers.length > 0) {
618
+ notes.push("another ledger is already here (" +
619
+ otherLedgers.join(", ") +
620
+ "); jig keeps `" +
621
+ ownLedger +
622
+ "` — decide which one owns these findings before enabling the gate, because two " +
623
+ "ledgers over one rule set means neither is the record of what was reviewed");
624
+ }
625
+ const agentDocs = ["AGENTS.md", "CLAUDE.md", ".cursorrules"].filter((file) => files.includes(file));
626
+ const typescript = yield* hasTypeScript(fs, path, root, files);
627
+ const ci = yield* Effect.orElseSucceed(fs.exists(path.join(root, ".github", "workflows")), () => false);
628
+ const cutlist = yield* cutlistDraftOf(fs, path, root);
629
+ const cutlistDraft = cutlist?.config;
630
+ if (cutlist?.note !== undefined)
631
+ notes.push(cutlist.note);
632
+ const architectureDraft = yield* architectureDraftOf(fs, path, root, files);
633
+ const summary = yield* repositorySummaryOf({
634
+ fs,
635
+ path,
636
+ root,
637
+ files,
638
+ fallback: packageJson.description,
639
+ });
640
+ const liveJudgement = process.env.TYPESAFE_API_KEY !== undefined && process.env.TYPESAFE_API_KEY !== "";
641
+ const script = Option.getOrUndefined(oxlintScriptOf(scripts));
642
+ const config = script?.config ?? Option.getOrUndefined(oxlintConfigOf(files));
643
+ const configText = config === undefined
644
+ ? ""
645
+ : yield* Effect.orElseSucceed(fs.readFileString(path.join(root, config)), () => "");
646
+ const lint = config !== undefined || script !== undefined
647
+ ? { tool: "oxlint", config, script: script?.script }
648
+ : files.includes("eslint.config.mjs") ||
649
+ files.includes("eslint.config.js") ||
650
+ files.includes("eslint.config.cjs") ||
651
+ files.includes("eslint.config.ts") ||
652
+ files.includes("eslint.config.mts") ||
653
+ files.includes(".eslintrc.json") ||
654
+ files.includes(".eslintrc.yml") ||
655
+ files.includes(".eslintrc.yaml") ||
656
+ files.includes(".eslintrc.cjs") ||
657
+ files.includes(".eslintrc")
658
+ ? { tool: "eslint", config: undefined, script: undefined }
659
+ : files.includes("biome.json") || files.includes("biome.jsonc")
660
+ ? { tool: "biome", config: "biome.json", script: undefined }
661
+ : { tool: "none", config: undefined, script: undefined };
662
+ const commandNames = ["lint", "typecheck", "test", "format", "check"].filter((name) => scripts[name] !== undefined);
663
+ if (script?.script !== undefined &&
664
+ !commandNames.includes(script.script) &&
665
+ scripts[script.script] !== undefined) {
666
+ commandNames.push(script.script);
667
+ }
668
+ const commands = commandNames.map((name) => ({
669
+ name,
670
+ command: packageManager + " " + name,
671
+ }));
672
+ const detected = [];
673
+ if (lint.tool === "oxlint" && lint.config !== undefined) {
674
+ if (!available({ root, command: "oxlint" })) {
675
+ notes.push("plumb not enabled: oxlint is not installed here (pnpm add -D oxlint)");
676
+ }
677
+ else if (!loadsPlumb(configText)) {
678
+ notes.push("plumb not enabled: " + lint.config + " does not load @autotelic/plumb in jsPlugins");
679
+ }
680
+ else {
681
+ detected.push(script?.args === undefined || script.args.length === 0
682
+ ? { id: "plumb", kind: "oxlint-plugin", command: "oxlint", config: lint.config }
683
+ : {
684
+ id: "plumb",
685
+ kind: "oxlint-plugin",
686
+ command: "oxlint",
687
+ config: lint.config,
688
+ args: script.args,
689
+ });
690
+ if (resolveEngineCommand({ root, command: "oxlint" }) === "oxlint" &&
691
+ dependencies["oxlint"] === undefined) {
692
+ notes.push("oxlint resolves from PATH; pin it as a devDependency so CI uses the same version");
693
+ }
694
+ }
695
+ }
696
+ else if (lint.tool === "eslint" || lint.tool === "biome") {
697
+ notes.push("plumb not enabled: this repo lints with " + lint.tool + ", and plumb is an oxlint plugin");
698
+ }
699
+ else {
700
+ notes.push("plumb not enabled: no oxlint config found");
701
+ }
702
+ if (typescript) {
703
+ if (!available({ root, command: "joggle" })) {
704
+ notes.push("joggle not enabled: joggle is not installed here (pnpm add -D @autotelic/joggle)");
705
+ }
706
+ else {
707
+ // A replay is not a look, and an untyped check misses the Effect rules: both are
708
+ // correctness, not taste. `--typecheck` stays off on purpose -- its tsgo run ignores
709
+ // each package's tsconfig (`jsx`, `paths`) and reports tens of thousands of false
710
+ // errors on a monorepo. The engine owns its own baseline so the ratchet key is
711
+ // `rule + file set`, which does not churn when a line moves.
712
+ detected.push({
713
+ id: "joggle",
714
+ kind: "process",
715
+ command: "joggle",
716
+ config: "joggle.config.json",
717
+ args: [...(typescript ? ["--types"] : []), "--no-replay", "--baseline", JOGGLE_BASELINE],
718
+ });
719
+ if (resolveEngineCommand({ root, command: "joggle" }) === "joggle" &&
720
+ dependencies["@autotelic/joggle"] === undefined) {
721
+ notes.push("joggle resolves from PATH; pin @autotelic/joggle as a devDependency so CI uses the same version");
722
+ }
723
+ }
724
+ }
725
+ else {
726
+ notes.push("joggle not enabled: no tsconfig found");
727
+ }
728
+ const mapperConfig = ["tsconfig.json", "tsconfig.base.json"].find((file) => files.includes(file));
729
+ if (mapperConfig !== undefined) {
730
+ const text = yield* Effect.orElseSucceed(fs.readFileString(path.join(root, mapperConfig)), () => "");
731
+ if (text.includes("contentMappers")) {
732
+ notes.push("content mappers are declared in " +
733
+ mapperConfig +
734
+ ": joggle will report the extensions it cannot index; runExternalCode stays off until trusted");
735
+ }
736
+ }
737
+ // The configured paths, not the defaults, are what `.gitattributes` must describe: a
738
+ // repo that moved the artifact still gets its own files collapsed. The config is read
739
+ // where the engine scans, so a catalog generated under `examples/` is described too.
740
+ const cutlistDirectory = cutlistCwdOf(existing?.engines ?? []);
741
+ const cutlistPath = cutlistDirectory === "" ? "cutlist.config.json" : cutlistDirectory + "/cutlist.config.json";
742
+ const keepsCutlist = yield* existsAt({ fs, path, root, relative: cutlistPath });
743
+ const installedCutlist = keepsCutlist
744
+ ? decodeCutlistConfig(parseJson(yield* Effect.orElseSucceed(fs.readFileString(path.join(root, cutlistPath)), () => "")))
745
+ : undefined;
746
+ const cutlistExisting = installedCutlist === undefined || keepsCutlist !== true
747
+ ? undefined
748
+ : { path: cutlistPath, directory: cutlistDirectory };
749
+ const cutlistOutput = installedCutlist === undefined && cutlistDraft === undefined
750
+ ? undefined
751
+ : underDirectory(resolvedOutput(installedCutlist?.output ?? cutlistDraft?.output), cutlistDirectory);
752
+ if (files.includes("cutlist.config.json")) {
753
+ if (!available({ root, command: "cutlist" })) {
754
+ notes.push("cutlist not enabled: cutlist.config.json exists but the command is not installed");
755
+ }
756
+ else {
757
+ detected.push({ id: "cutlist", kind: "process", command: "cutlist" });
758
+ if (resolveEngineCommand({ root, command: "cutlist" }) === "cutlist" &&
759
+ dependencies["@autotelic/cutlist"] === undefined) {
760
+ notes.push("cutlist resolves from PATH; pin @autotelic/cutlist as a devDependency so CI uses the same version");
761
+ }
762
+ }
763
+ }
764
+ else if (cutlistDraft !== undefined) {
765
+ notes.push("cutlist not enabled: no cutlist.config.json, though this looks like a UI (" +
766
+ cutlistDraft.roots.join(", ") +
767
+ "); run `jig init --cutlist` to draft one");
768
+ }
769
+ // The room is the same product as the harness: a repo that keeps one -- or builds one --
770
+ // wants its commands in the docs, and a room without a config is "not initialised", not
771
+ // "configured".
772
+ const room = files.includes("room.config.json") ||
773
+ dependencies["@autotelic/room"] !== undefined ||
774
+ (yield* existsAt({ fs, path, root, relative: "packages/room/package.json" }));
775
+ if (room && !files.includes("room.config.json")) {
776
+ notes.push("room not initialised: no room.config.json; `" +
777
+ jig +
778
+ " room plan` prints the init it would run");
779
+ }
780
+ // A repo's engine list is a decision, not a detection artefact: a forced run adds what
781
+ // this run found and drops what no longer resolves, but it never erases an engine the
782
+ // repo configured.
783
+ const engines = mergeEngines({
784
+ configured: existing?.engines ?? [],
785
+ detected,
786
+ root,
787
+ notes,
788
+ });
789
+ return {
790
+ root,
791
+ // The manifest's name, not the directory's: `init` run from a worktree
792
+ // (`wt-jig-thorough`) used to bake the worktree's basename into JIG.md's first line, and
793
+ // every repo set up that way shipped it.
794
+ name: packageJson.name ?? path.basename(root),
795
+ packageManager,
796
+ run: packageManager,
797
+ jig,
798
+ facts: new Set([
799
+ ...(files.includes("pnpm-workspace.yaml") || files.includes("lerna.json")
800
+ ? ["workspaces"]
801
+ : []),
802
+ ...(typescript ? ["typescript"] : []),
803
+ ...(liveJudgement ? ["live-judgement"] : []),
804
+ ...(ci ? ["ci"] : []),
805
+ ...(hasConfig ? ["configured"] : []),
806
+ ...(room ? ["room"] : []),
807
+ ]),
808
+ agentDocs,
809
+ summary,
810
+ commands,
811
+ lint,
812
+ engines,
813
+ notes,
814
+ gateMode,
815
+ baseline: existing?.gate.baseline ?? ".jig-baseline.json",
816
+ cookbook: existing?.agent?.cookbook ?? "JIG.md",
817
+ onboarding: existing?.agent?.onboarding ?? "ONBOARD.md",
818
+ jigSource,
819
+ hosts,
820
+ cutlistDraft,
821
+ architectureDraft,
822
+ cutlistOutput,
823
+ cutlistExisting,
824
+ };
825
+ });
826
+ /** The config `init` writes: only the engines that resolved, and the friendly gate. */
827
+ export const configFor = (profile) => ({
828
+ $schema: "https://autotelic.dev/tackle/protocol/jig.config.json",
829
+ engines: profile.engines,
830
+ gate: { mode: profile.gateMode, baseline: profile.baseline, failOn: "any-new" },
831
+ report: { format: "text", maxWarnings: -1 },
832
+ agent: { cookbook: profile.cookbook, onboarding: profile.onboarding },
833
+ });
834
+ /**
835
+ * Re-draft `architecture.layers`, keep the judgement written into them.
836
+ *
837
+ * Keyed by layer name, because the name is the only stable handle: an include glob moves when
838
+ * the draft learns a tier (a `routes` split becoming `support` + `routes` moved every include
839
+ * in the first adopter), and a `forbid` was written against a name. A layer the draft no
840
+ * longer proposes is reported rather than dropped in silence -- its forbidden dependency is a
841
+ * decision, and losing it makes `layer-purity` read 0 on rules nobody removed.
842
+ *
843
+ * Everything outside `architecture.layers` is carried through untouched: `rules`,
844
+ * `evidence`, `unavailable`, and whatever a later joggle adds.
845
+ */
846
+ export const mergeArchitecture = (input) => {
847
+ const architecture = isRecord(input.existing.architecture) ? input.existing.architecture : {};
848
+ const declared = Array.isArray(architecture.layers) ? architecture.layers : [];
849
+ const previous = new Map();
850
+ for (const layer of declared) {
851
+ if (!isRecord(layer) || typeof layer.name !== "string")
852
+ continue;
853
+ const forbid = Array.isArray(layer.forbid)
854
+ ? layer.forbid.filter((entry) => typeof entry === "string")
855
+ : [];
856
+ if (forbid.length > 0)
857
+ previous.set(layer.name, forbid);
858
+ }
859
+ const drafted = new Set(input.draft.map((layer) => layer.name));
860
+ const forbidsKept = [];
861
+ const layers = input.draft.map((layer) => {
862
+ const forbid = previous.get(layer.name);
863
+ if (forbid === undefined)
864
+ return { name: layer.name, include: layer.include };
865
+ forbidsKept.push(layer.name);
866
+ return { name: layer.name, include: layer.include, forbid };
867
+ });
868
+ const forbidsDropped = [...previous.keys()].filter((name) => !drafted.has(name));
869
+ return {
870
+ file: { ...input.existing, architecture: { ...architecture, layers } },
871
+ forbidsKept,
872
+ forbidsDropped,
873
+ };
874
+ };
875
+ /** One line per engine, for the summary and the generated docs. */
876
+ const engineSummary = (profile) => profile.engines.length === 0
877
+ ? "none — see the notes below"
878
+ : profile.engines
879
+ .map((engine) => engine.config === undefined ? engine.id : `${engine.id} (${engine.config})`)
880
+ .join(", ");
881
+ /** The room's commands, for the repositories that run one. */
882
+ const roomSection = (profile) => profile.facts.has("room")
883
+ ? `## The room
884
+
885
+ \`jig room\` is this repo's listener: one ledger per Linear project, a daemon on each
886
+ machine, and a review job that runs \`${profile.jig}\`, a Pi, and one fenced post.
887
+
888
+ - \`${profile.jig} room plan\` — read the repo, the token, and the rooms; print the init it would run
889
+ - \`${profile.jig} room init\` — write \`room.config.json\` and register the room
890
+ - \`${profile.jig} room doctor\` — prove the loop: config, identity, celld, pi, the forward, the room
891
+ - \`${profile.jig} room dev\` — run the room locally with \`celld dev\`
892
+ - \`${profile.jig} room webhook\` — print the \`gh webhook forward\` command for this room
893
+ - \`${profile.jig} room daemon\` — claim jobs, run reviews, deliver into the durable session
894
+ - \`${profile.jig} room session\` — the room's durable conversation (--json, --say, --watch, --note)
895
+ - \`${profile.jig} room work --pr N\` — a worktree, an app, and an attachable Pi session
896
+ - \`${profile.jig} room board\` — jobs, chits, and presence
897
+
898
+ \`${profile.jig} room doctor\` names the prerequisites this machine is missing — \`celld\`,
899
+ the \`gh webhook\` extension, a Linear token at \`~/.linearis/token\`, \`pi\` on PATH — so the
900
+ list never goes stale here. \`hc\` (herdr-core) is only needed by \`room work\`.
901
+
902
+ `
903
+ : "";
904
+ /** One blank line between sections, however the template was assembled. */
905
+ const tighten = (text) => text.replace(/\n{3,}/gu, "\n\n");
906
+ /** The durable cookbook: what the commands are, and what the gate means. */
907
+ export const cookbookFor = (profile) => tighten(`# JIG.md
908
+
909
+ The conformance harness for ${profile.name}. \`jig\` runs the engines this repo
910
+ configures, merges their output into one report, and holds the ratchet: a run fails
911
+ on new findings, not on debt this repo has already accepted.
912
+ ${profile.summary === "" ? "" : "\n" + profile.summary + "\n"}
913
+
914
+ ## Commands
915
+
916
+ | Command | What it does |
917
+ | --- | --- |
918
+ | \`${profile.jig} check\` | every engine, one report, fail on what is new |
919
+ | \`${profile.jig} check --limit 50\` | the census and the first 50 findings |
920
+ | \`${profile.jig} engines\` | what is configured, and whether each command resolves |
921
+ | \`${profile.jig} baseline\` | accept the current findings; the ledger only shrinks after that |
922
+ | \`${profile.jig} explain <rule>\` | everything jig knows about one rule, here, now |
923
+ ${profile.facts.has("room") ? "| `" + profile.jig + " room board` | the room: jobs, chits, and presence |\n" : ""}${profile.engines.some((engine) => engine.id === "cutlist") ? "| `" + profile.jig + " menu` | the component catalog cutlist built |\n" : ""}${profile.commands.length === 0 ? "" : "\n## The repo's own commands\n\n" + profile.commands.map((command) => "- `" + command.command + "` — the repo's " + command.name + " script").join("\n") + "\n"}
924
+
925
+ ## What runs
926
+
927
+ - engines: ${engineSummary(profile)}
928
+ - gate: \`${profile.gateMode}\`, failing on \`any-new\` identity
929
+ - baseline: \`${profile.baseline}\`
930
+ ${profile.notes.length === 0 ? "" : "\nNotes:\n" + profile.notes.map((note) => "- " + note).join("\n") + "\n"}
931
+ ${roomSection(profile)}${profile.gateMode === "touched-files"
932
+ ? "Only findings in the change in front of you fail a run. Existing debt is reported,\nnot enforced, until you touch it."
933
+ : "Every finding in the repository fails a run. Accept the current debt deliberately\nwith `" +
934
+ profile.jig +
935
+ " baseline`, or switch the gate to `touched-files`."}
936
+
937
+ ${profile.facts.has("ci") ? "## CI\n\nRun `" + profile.jig + " check --format github` in the pull-request workflow. The gate holds new identities only, so the first run explains the debt instead of failing on it. For machine output (`--format json`, `sarif`, `github`), use `" + profile.run + " exec jig`: `" + profile.run + " jig` prepends the package manager's own engine warning to stdout and corrupts the document.\n\n" : ""}## Judgement
938
+
939
+ joggle judges candidates with the TypeSafe model. ${profile.facts.has("live-judgement") ? "A TYPESAFE_API_KEY is present in this environment, so a run can judge." : "No TYPESAFE_API_KEY is present in this environment, so unjudged candidates are counted, not printed. Set the key to judge, or keep the count in CI."}
940
+
941
+ ## Reading a finding
942
+
943
+ A finding is a place, a sentence, and a rule id. \`${profile.jig} explain <rule>\` shows
944
+ the rule's findings here, the help text, and whether it is one you can fix now.
945
+
946
+ A **note** on an engine means "not looked at": a missing command, a skipped rule, or
947
+ candidates the model did not judge. It is never "clean".
948
+
949
+ ## The one rule
950
+
951
+ Do not run \`${profile.jig} baseline\` to make a run green without reading what it
952
+ accepts. The baseline is a reviewed ledger, not a mute button.
953
+ `);
954
+ /**
955
+ * How a person types a tool in this repo: through the package manager when the project has
956
+ * its own copy, plainly when a global one is the only one there is. `jig engines` already
957
+ * resolves this for spawning; the next steps a human reads must agree with it, or the paste
958
+ * tells them to type a command that is not on PATH.
959
+ */
960
+ const invocationOf = (input) => resolveEngineCommand({ root: input.profile.root, command: input.tool }) === input.tool
961
+ ? input.tool + " " + input.args
962
+ : input.profile.run + " exec " + input.tool + " " + input.args;
963
+ /** The `init` invocation that reproduces this plan, including the gate it chose. */
964
+ const initCommandFor = (profile) => `${profile.jig} init${profile.gateMode === "all" ? " --gate all" : ""}${profile.cutlistDraft === undefined ? "" : " --cutlist"}`;
965
+ // Keyed by manager so the compiler, not a reader, proves every case is covered: the
966
+ // global install verb, the devDependency verb, and where the bins land are each different.
967
+ const GLOBAL_INSTALL = {
968
+ bun: (spec) => `bun add -g ${spec}`,
969
+ npm: (spec) => `npm install -g ${spec}`,
970
+ pnpm: (spec) => `pnpm add -g ${spec}`,
971
+ yarn: (spec) => `yarn global add ${spec}`,
972
+ };
973
+ const DEV_INSTALL = {
974
+ bun: "bun add -D",
975
+ npm: "npm install -D",
976
+ pnpm: "pnpm add -D",
977
+ yarn: "yarn add -D",
978
+ };
979
+ /** Installing a devDependency here: a pnpm workspace root refuses it without `-w`. */
980
+ const devInstallOf = (profile) => profile.packageManager === "pnpm" && profile.facts.has("workspaces")
981
+ ? "pnpm add -Dw"
982
+ : DEV_INSTALL[profile.packageManager];
983
+ const GLOBAL_BIN_HINT = {
984
+ bun: "`bun` links bins into `$HOME/.bun/bin`: add it to PATH, open a new shell, and try again",
985
+ npm: "add `$(npm prefix -g)/bin` to PATH, open a new shell, and try again",
986
+ pnpm: "run `pnpm setup` (it puts `pnpm bin -g` on PATH), open a new shell, and try again",
987
+ yarn: "add `$(yarn global bin)` to PATH, open a new shell, and try again",
988
+ };
989
+ /**
990
+ * The agent door: one prompt, pasted whole, that sets the harness up end to end.
991
+ *
992
+ * The shape is the one that works -- Alchemy's and rat-stack's: a line of intent, one
993
+ * named command per step, the doc to read before acting, and an explicit place to stop
994
+ * and ask. Nothing is left as "see the README": a prompt that stops at "run init" leaves
995
+ * the person to discover the CLI install, the agent wiring, and the room alone. `JIG.md`
996
+ * stays the reference; this is the door.
997
+ */
998
+ export const onboardingFor = (profile) => {
999
+ let counted = 0;
1000
+ const section = (title) => `## ${(counted += 1)}. ${title}`;
1001
+ const summary = profile.summary === "" ? "" : "\n\n" + profile.summary;
1002
+ const source = profile.jigSource.startsWith(".")
1003
+ ? `\n\n\`${profile.jigSource}\` is this checkout: build it first (\`${profile.run} build\`, or \`${profile.run} --filter @autotelic/jig-cli build\`), and build again after a change to the CLI -- the installed bin runs \`dist/\`, not the source.`
1004
+ : "";
1005
+ const engines = profile.engines.length === 0 ? "none yet" : engineSummary(profile);
1006
+ const readFirst = [
1007
+ `- \`${profile.cookbook}\` — the commands, the gate, and what a note means. Read it before you run anything.`,
1008
+ `- \`jig.config.json\` — engines: ${engines}; gate: \`${profile.gateMode}\`; baseline: \`${profile.baseline}\`.`,
1009
+ ...(profile.agentDocs.length === 0
1010
+ ? []
1011
+ : [
1012
+ `- ${profile.agentDocs.map((doc) => "`" + doc + "`").join(", ")} — how this repository wants to be worked in.`,
1013
+ ]),
1014
+ ].join("\n");
1015
+ const initialise = [
1016
+ profile.facts.has("configured")
1017
+ ? `\`jig.config.json\` is already here, and nothing needs applying: a re-run keeps it. \`${initCommandFor(profile)} --force\` rewrites the config and the two docs — never the baseline — so run that only when the plan changes.`
1018
+ : `This repository is not initialised yet. Run \`${initCommandFor(profile)}\`: it writes \`jig.config.json\`, an empty \`${profile.baseline}\`, \`${profile.cookbook}\`, and \`${profile.onboarding}\`.`,
1019
+ profile.cutlistDraft === undefined
1020
+ ? ""
1021
+ : `The same command drafts \`cutlist.config.json\`, because this tree looks like a UI. Review the vocabulary it infers, run \`${invocationOf({ profile, tool: "cutlist", args: "build" })}\`, and commit the catalog: \`jig check\` runs the engine as \`cutlist build --check\`, which compares the tree against the catalog on disk, so a catalog that is ignored or stale passes only on the machine that built it. Then re-run with \`--force\`. A draft is not enabled before a person has read it.`,
1022
+ `Init writes each engine's own ledger too (joggle's is born accepted, and is never rewritten), so day one is "nothing new" rather than a pile nobody has judged.`,
1023
+ 'A known-broken engine does not have to be removed: set `"advisory": true` on its entry in `jig.config.json` and its findings stay in the report and the baseline while the gate ignores them, or `"enabled": false` to keep it out of a run. Both survive `init --force`, which keeps a configured engine\'s own fields.',
1024
+ `The same run installs the agent skills into \`.agents/skills/\` — \`room\`, \`intercom-setup\`, \`feedback-loop\`, \`project-run\`. pi and OpenCode both read that directory, so there is no second install; a skill someone edits is kept, and \`--force\` replaces it.`,
1025
+ profile.architectureDraft === undefined
1026
+ ? ""
1027
+ : `The same run drafts \`architecture.layers\` in \`joggle.config.json\` from this workspace: includes only, in directory order, with \`layer-direction\`/\`layer-purity\` off, because neither the order nor the \`forbid\` sets can be inferred from a tree. A UI root is split into \`support\` (\`utils\`/\`lib\`/\`models\`/\`hooks\`/\`types\`), primitives, shared components and routes, in that order: a route may import support and so may a primitive, which is what keeps a routes split from reading as 731 upward imports. The splits come before the root they belong to, and each root stays last as the catch-all. Order the rest by what depends on what, add \`forbid\` where it is true, and check every \`forbid\` against the manifest of the layer that forbids it -- forbidding a dependency a package is built on reports that package's own imports as violations -- then turn those two rules on. Until then a clean architecture report means nothing looked.`,
1028
+ `Then \`${profile.jig} check --limit 20\`: read the census before the findings. An engine marked \`skipped\`, \`replayed\`, or "candidates not judged" did not look, and a note is never a pass.`,
1029
+ "Secrets are the environment and the host owns them: if a run needs a key this session was not started with, say so and stop. Never add a loader, and never nest a second `doppler run` from this directory -- it resolves the project from the working directory's `doppler.yaml`, so the layer you think you added is not the one that wins.",
1030
+ ]
1031
+ .filter((line) => line !== "")
1032
+ .join("\n\n");
1033
+ const piWired = profile.hosts.has("pi");
1034
+ const opencodeWired = profile.hosts.has("opencode");
1035
+ const wire = [
1036
+ piWired
1037
+ ? "- **pi** is already wired here (`.pi/settings.json`): run `pi update --extensions` rather than adding a second entry."
1038
+ : `- **pi**: \`pi install ${profile.jigSource} --local\` writes \`.pi/settings.json\`, and the package's extension adds \`jig_check\`, \`jig_engines\`, \`jig_onboard\`, \`jig_init\`, and \`jig_menu\`.`,
1039
+ opencodeWired
1040
+ ? '- **OpenCode** is already wired here: keep the existing `"plugin"` entry or `.opencode/plugins/` file rather than adding another.'
1041
+ : '- **opencode 2**: add `"@autotelic/jig-cli/opencode"` to the `"plugin"` array in `opencode.json`. **opencode 1.x** reads plugin files, not that array: add `.opencode/plugins/jig.ts` containing `export { default } from "@autotelic/jig-cli/opencode"`. Either way the surface adds `jig_check`, `jig_engines`, `jig_menu`, `jig_onboard`, and `jig_init`.',
1042
+ // A repo that denies every tool by default makes a plugin that adds tools invisible, and
1043
+ // the failure looks like "the plugin did not load" rather than "the tools are off".
1044
+ opencodeWired
1045
+ ? ""
1046
+ : '- If that OpenCode config denies tools wholesale (`"tools": { "*": false }`), allow `jig.*` explicitly or the plugin\'s tools stay invisible.',
1047
+ piWired || opencodeWired ? "" : "Ask me which host I use if neither file exists.",
1048
+ ]
1049
+ .filter((line) => line !== "")
1050
+ .join("\n");
1051
+ const room = () => profile.facts.has("room")
1052
+ ? `${section("The room — **STOP and ask**")}
1053
+
1054
+ This repository keeps a project room: one ledger per Linear project, a daemon on this
1055
+ machine, and a review job that runs jig, a Pi, and one fenced post.
1056
+
1057
+ \`\`\`sh
1058
+ ${profile.jig} room plan # read it, then show me the init line and wait
1059
+ ${profile.jig} room init # only after I approve: writes room.config.json, registers the room
1060
+ ${profile.jig} room doctor # names what is missing on this machine
1061
+ ${profile.jig} room dev # the room, locally
1062
+ ${profile.jig} room webhook | sh # forward GitHub events to it
1063
+ ${profile.jig} room daemon # its own terminal: claims jobs, wakes the session
1064
+ \`\`\`
1065
+
1066
+ Ask before installing anything doctor names. What the checks mean:
1067
+
1068
+ - \`celld\` — the room itself: \`curl -fsSL https://celld.dev/install.sh | sh\`
1069
+ - \`gh webhook\` — the GitHub forward: \`gh extension install cli/gh-webhook\`
1070
+ - a Linear token at \`~/.linearis/token\` (\`linearis\`), when this room watches Linear
1071
+ - \`pi\` — the review and the session wake both run it, so it has to be on PATH
1072
+
1073
+ \`hc\` (herdr-core) is only needed by \`${profile.jig} room work\`, and the wake needs the machine
1074
+ awake: a sleeping laptop is a hosting problem, not a bug.
1075
+
1076
+ `
1077
+ : "";
1078
+ const notes = () => profile.notes.length === 0
1079
+ ? ""
1080
+ : `${section("What this scan already found")}
1081
+
1082
+ ${profile.notes.map((note) => "- " + note).join("\n")}`;
1083
+ return tighten(`# ${profile.onboarding}
1084
+
1085
+ > Paste this whole file into your coding agent at the root of \`${profile.name}\`. It sets the
1086
+ > harness up end to end; nothing here is applied until the agent runs it.
1087
+ ${profile.jigSource.startsWith(".") ? ">\n> This repository is where `jig` comes from. To set up a *different* repository, send the\n> person [`ADOPT.md`](./ADOPT.md) instead: it starts from this checkout and ends in theirs.\n" : ""}
1088
+
1089
+ Set \`${profile.name}\` up with \`jig\`, the conformance harness this repository configures: every
1090
+ engine in one report, and a gate that fails on what is new.${summary}
1091
+
1092
+ Run the steps in order, running the commands yourself. When a step says **STOP and ask**,
1093
+ stop and wait for me.
1094
+
1095
+ ${section("Put `jig` on this machine")}
1096
+
1097
+ The CLI is the one thing that belongs to the machine rather than the repository.
1098
+
1099
+ \`\`\`sh
1100
+ ${GLOBAL_INSTALL[profile.packageManager](profile.jigSource)}
1101
+ jig --version
1102
+ \`\`\`
1103
+
1104
+ If \`jig\` is not found, the global bin directory is not on PATH: ${GLOBAL_BIN_HINT[profile.packageManager]}.${source}
1105
+
1106
+ If the install itself fails with a 404, the package is not on the registry yet: ask me for a checkout and link it instead (\`${devInstallOf(profile)} link:<checkout>/packages/jig-cli\`), then point pi at the linked copy (\`pi install ./node_modules/@autotelic/jig-cli --local\`) — an unpublished name is treated as a relative path.
1107
+
1108
+ ${section("Read what this repository already decided")}
1109
+
1110
+ ${readFirst}
1111
+
1112
+ ${profile.facts.has("configured") ? "" : "`" + profile.cookbook + "` and `jig.config.json` do not exist yet: step 4 writes them, and what is written is the plan's defaults. Read both the moment they land.\n\n"}Then run \`${profile.jig} engines\` and confirm every configured engine resolves.
1113
+
1114
+ ${section("Install what is missing — **STOP and ask**")}
1115
+
1116
+ Engines are devDependencies here, never global installs: \`${devInstallOf(profile)} <package>\`, then \`${profile.jig} engines\` again. Before you install anything, tell me the engine, the package, and what the census says is missing.
1117
+
1118
+ ${section("Initialise, then read the census")}
1119
+
1120
+ ${initialise}
1121
+
1122
+ ${section("Commit it, or say it is local-only — **STOP and ask**")}
1123
+
1124
+ \`git status\` after init: the harness is config, two docs, a ledger, and a generated block. If any of them is *ignored* here, stop and tell me, because a harness git cannot see gates this machine and nothing else — no CI, no reviewer, no second machine.
1125
+
1126
+ Two things make it real, and both are your call, not mine to assume:
1127
+
1128
+ - \`${profile.jig} init --unignore\` removes the exact \`.gitignore\` lines that hide the harness. It reports a path hidden by a *pattern* instead of editing the pattern, so tell me which of those you want changed.
1129
+ - \`${profile.jig} init --hooks\` writes \`.git/hooks/pre-commit\` running \`jig check --gate touched-files\`: only the change in front of you. The hook prints a line and exits 0 when this machine has no CLI, and it will not replace a hook that is already there.
1130
+
1131
+ Do not run either one without asking: one changes what git tracks for everyone, the other changes what every commit does.
1132
+
1133
+ ${section("Wire this agent")}
1134
+
1135
+ ${wire}
1136
+
1137
+ ${room()}${section("Report, then stop")}
1138
+
1139
+ Tell me what you installed, what \`${profile.jig} init\` wrote and kept, the census, and the first findings. Then wait for me.
1140
+
1141
+ ${section("Never, without asking me")}
1142
+
1143
+ - \`${profile.jig} baseline\` — it accepts every current finding, and an unreviewed baseline is debt made invisible.
1144
+ - Changing the gate ${profile.gateMode === "all" ? "back to `touched-files`" : "to `all`"}, or adding an ignore to get green.
1145
+ - Installing an engine, or anything else globally. Step 1 is the one exception.
1146
+ ${profile.facts.has("room") ? "- `" + profile.jig + " room init`, which registers the room against Linear.\n" : ""}- Changing \`jig.config.json\` by hand instead of re-running \`init\`.
1147
+
1148
+ ${notes()}
1149
+
1150
+ An engine marked \`skipped\`, \`replayed\`, or "no command" is a hole in the census, not a pass and not a finding to fix in the code.
1151
+ `);
1152
+ };
1153
+ /** What happened to cutlist: a config it already keeps, a draft it wants reviewed, or nothing. */
1154
+ const cutlistSummary = (result) => {
1155
+ if (result.cutlistConfig === "written") {
1156
+ return result.dryRun
1157
+ ? "draft would be written — review it after applying"
1158
+ : "draft written — review, build, then re-run init --force";
1159
+ }
1160
+ const existing = result.profile.cutlistExisting;
1161
+ return existing === undefined ? result.cutlistConfig : `configured (${existing.path})`;
1162
+ };
1163
+ /** The human summary `init` prints, before the next steps. */
1164
+ export const summaryFor = (result) => {
1165
+ const { profile } = result;
1166
+ const action = result.dryRun ? "would write" : "wrote";
1167
+ const keptAction = result.dryRun ? "would keep" : "kept";
1168
+ const lines = [
1169
+ `${result.dryRun ? "jig: plan for" : "jig: initialised"} ${profile.root}`,
1170
+ "",
1171
+ ` package manager ${profile.packageManager}`,
1172
+ ` workspaces ${profile.facts.has("workspaces") ? "yes" : "no"}`,
1173
+ ` typescript ${profile.facts.has("typescript") ? "yes" : "no"}`,
1174
+ ` lint ${profile.lint.config ?? profile.lint.tool}${profile.lint.script === undefined ? "" : " via `" + profile.run + " " + profile.lint.script + "`"}`,
1175
+ ` agent docs ${profile.agentDocs.length === 0 ? "none found" : profile.agentDocs.join(", ") + " (left untouched)"}`,
1176
+ ` engines ${engineSummary(profile)}`,
1177
+ ` gate ${profile.gateMode}`,
1178
+ ` baseline ${profile.baseline} (${result.accepted} accepted finding(s))`,
1179
+ ` cutlist ${cutlistSummary(result)}`,
1180
+ ...(result.gitattributes === "absent"
1181
+ ? []
1182
+ : [` gitattributes ${result.gitattributes} (generated block only)`]),
1183
+ ` ${action.padEnd(16)} ${result.written.length === 0 ? "nothing" : result.written.join(", ")}`,
1184
+ ...(result.kept.length === 0 ? [] : [` ${keptAction.padEnd(16)} ${result.kept.join(", ")}`]),
1185
+ ...(result.hooks === "absent" ? [] : [` hook pre-commit ${result.hooks}`]),
1186
+ ...(result.skills.length === 0
1187
+ ? []
1188
+ : [
1189
+ ` ${"skills".padEnd(16)} ${result.skills
1190
+ .map((skill) => `${skill.name} (${skill.state})`)
1191
+ .join(", ")}`,
1192
+ ]),
1193
+ ...(result.ignore.some((entry) => entry.status === "removed")
1194
+ ? [
1195
+ ` unignored ${result.ignore
1196
+ .filter((entry) => entry.status === "removed")
1197
+ .map((entry) => entry.path)
1198
+ .join(", ")} (the harness can be committed)`,
1199
+ ]
1200
+ : []),
1201
+ ...result.engineBaselines.map((baseline) => ` ${"engine ledger".padEnd(16)} ${baseline.path} — ${baseline.action}${baseline.accepted === 0 ? "" : ` ${baseline.accepted} finding(s)`}`),
1202
+ ...(result.ignore.filter((entry) => entry.status !== "removed").length === 0
1203
+ ? []
1204
+ : [
1205
+ ` ${"gitignored".padEnd(16)} ${result.ignore
1206
+ .filter((entry) => entry.status !== "removed")
1207
+ .map((entry) => entry.path)
1208
+ .join(", ")} — local-only: no CI can run what git cannot see`,
1209
+ ]),
1210
+ ...profile.notes.map((note) => ` note ${note}`),
1211
+ "",
1212
+ "Next:",
1213
+ ...(result.dryRun
1214
+ ? [
1215
+ ` 1. ${profile.jig} init${profile.gateMode === "all" ? " --gate all" : ""}${result.cutlistConfig === "written" ? " --cutlist" : ""} write this plan after approval`,
1216
+ ` 2. ${profile.jig} engines confirm each command resolves`,
1217
+ ` 3. ${profile.jig} check --limit 20 census, then the first 20 findings`,
1218
+ ` 4. paste ${profile.onboarding} into your agent`,
1219
+ ]
1220
+ : profile.engines.length === 0
1221
+ ? [" 1. install at least one engine (see the notes above)", " 2. re-run jig init --force"]
1222
+ : [
1223
+ ` 1. ${profile.jig} engines confirm each command resolves`,
1224
+ ` 2. ${profile.jig} check --limit 20 census, then the first 20 findings`,
1225
+ ...(result.cutlistConfig === "written"
1226
+ ? [
1227
+ ` 3. ${invocationOf({ profile, tool: "cutlist", args: "build" })} review the catalog, commit it, then re-run jig init --force`,
1228
+ ` 4. paste ${profile.onboarding} into your agent`,
1229
+ ]
1230
+ : [` 3. paste ${profile.onboarding} into your agent`]),
1231
+ ]),
1232
+ ];
1233
+ return lines.join("\n");
1234
+ };
1235
+ /**
1236
+ * The generated JSON a run owns, in the order a formatter note should name them.
1237
+ *
1238
+ * `cutlist.config.json` is deliberately absent. It is written once as a draft and is a
1239
+ * person's file from then on -- `init` keeps it, `--force` included -- so exempting it from a
1240
+ * formatter would exile the one config in the harness a human is meant to edit. `jig.config.json`
1241
+ * and `joggle.config.json` are the opposite: written on every `--force`, reviewed through
1242
+ * `git diff`, never hand-edited in place.
1243
+ */
1244
+ const GENERATED_JSON = ["jig.config.json", "joggle.config.json"];
1245
+ /** Whether a formatter's ignore list already exempts a generated file. */
1246
+ const exemptedBy = (patterns, file) => patterns.some((pattern) => {
1247
+ const trimmed = pattern
1248
+ .replace(/^!/u, "")
1249
+ .replace(/\/?\*+$/u, "")
1250
+ .replace(/\/$/u, "");
1251
+ return trimmed !== "" && (file === trimmed || file.startsWith(trimmed + "/"));
1252
+ });
1253
+ /**
1254
+ * The repository's formatter and the ignore list it would consult for a generated file.
1255
+ *
1256
+ * Only the shapes a repo actually uses here: oxfmt's `ignorePatterns`, a `.prettierignore`,
1257
+ * or biome's `files.ignore`. Guessing wider would mean guessing at a formatter's semantics.
1258
+ */
1259
+ const formatterOf = (input) => Effect.gen(function* () {
1260
+ const read = (file) => Effect.orElseSucceed(input.fs.readFileString(input.path.join(input.root, file)), () => undefined);
1261
+ const listed = (value, key) => {
1262
+ if (!isRecord(value))
1263
+ return [];
1264
+ const found = value[key];
1265
+ return Array.isArray(found)
1266
+ ? found.filter((entry) => typeof entry === "string")
1267
+ : [];
1268
+ };
1269
+ const oxfmt = yield* read(".oxfmtrc.json");
1270
+ if (oxfmt !== undefined) {
1271
+ return { file: ".oxfmtrc.json", patterns: listed(parseJson(oxfmt), "ignorePatterns") };
1272
+ }
1273
+ const prettier = yield* read(".prettierignore");
1274
+ if (prettier !== undefined) {
1275
+ return {
1276
+ file: ".prettierignore",
1277
+ patterns: prettier
1278
+ .split("\n")
1279
+ .map((line) => line.trim())
1280
+ .filter((line) => line !== "" && !line.startsWith("#")),
1281
+ };
1282
+ }
1283
+ const biome = yield* read("biome.json");
1284
+ if (biome !== undefined) {
1285
+ const value = parseJson(biome);
1286
+ const files = isRecord(value) && isRecord(value.files) ? value.files : {};
1287
+ return { file: "biome.json", patterns: listed(files, "ignore") };
1288
+ }
1289
+ return undefined;
1290
+ });
1291
+ /** The plan as data, for a host that wants to reason about it rather than read prose. */
1292
+ export const initJson = (result, prompt) => {
1293
+ const profile = { ...result.profile, facts: [...result.profile.facts] };
1294
+ const plan = {
1295
+ dryRun: result.dryRun,
1296
+ written: result.written,
1297
+ kept: result.kept,
1298
+ joggleConfig: result.joggleConfig,
1299
+ cutlistConfig: result.cutlistConfig,
1300
+ gitattributes: result.gitattributes,
1301
+ accepted: result.accepted,
1302
+ };
1303
+ return JSON.stringify(prompt === undefined ? { profile, plan } : { profile, plan, prompt }, null, 2);
1304
+ };
1305
+ /**
1306
+ * The written paths git here refuses to track.
1307
+ *
1308
+ * `jig init` writes a config, two docs, a ledger, and a generated block. A repository can
1309
+ * ignore every one of them -- the first adopter we ran against ignores all seven -- and then
1310
+ * the harness is local-only: no CI runs it, the baseline never reaches a reviewer, and
1311
+ * `JIG.md`'s "run `jig check --format github` in the pull-request workflow" cannot be done.
1312
+ * `init` cannot change the ignore rules; it can refuse to call that a clean write.
1313
+ *
1314
+ * @param input - The repository root and the paths to test.
1315
+ * @returns The paths git reports as ignored; empty when git cannot answer.
1316
+ */
1317
+ const ignoredByGit = (input) => input.files.length === 0
1318
+ ? Effect.succeed([])
1319
+ : Effect.match(exec({ binary: "git", args: ["check-ignore", "--", ...input.files], cwd: input.root }), {
1320
+ onFailure: () => [],
1321
+ onSuccess: (outcome) => outcome.code === 0
1322
+ ? outcome.stdout
1323
+ .split("\n")
1324
+ .map((line) => line.trim())
1325
+ .filter((line) => line !== "")
1326
+ : [],
1327
+ });
1328
+ /**
1329
+ * Where the bundled skills live. `src` and `dist` sit at the same depth in the package, so one
1330
+ * relative hop reaches them from a source run and from the installed binary alike.
1331
+ */
1332
+ const skillsSource = (path) => path.join(import.meta.dirname, "..", "skills");
1333
+ /**
1334
+ * Copy the bundled skills into the repository's portable location.
1335
+ *
1336
+ * `.agents/skills` is the one directory pi and OpenCode both discover, so an adopter gets the
1337
+ * workflows without installing this package. Content is compared, not timestamps: a re-run on an
1338
+ * untouched tree reports `kept` and writes nothing.
1339
+ *
1340
+ * @param input - Filesystem, path, repo root, whether to write.
1341
+ * @returns One entry per skill, in directory order.
1342
+ */
1343
+ const installSkills = (input) => Effect.gen(function* () {
1344
+ const source = skillsSource(input.path);
1345
+ // `readDirectory` yields plain names here, not dirent tuples.
1346
+ const names = yield* Effect.orElseSucceed(input.fs.readDirectory(source), () => []);
1347
+ const installed = [];
1348
+ for (const name of [...names].sort((left, right) => left.localeCompare(right))) {
1349
+ const body = yield* Effect.orElseSucceed(input.fs.readFileString(input.path.join(source, name, "SKILL.md")), () => "");
1350
+ if (body === "")
1351
+ continue;
1352
+ const target = input.path.join(input.root, ".agents", "skills", name, "SKILL.md");
1353
+ const existing = yield* Effect.orElseSucceed(input.fs.readFileString(target), () => "");
1354
+ if (existing === body) {
1355
+ installed.push({ name, state: "kept" });
1356
+ continue;
1357
+ }
1358
+ // A skill someone edited is theirs: only --force replaces it, and a skip says so.
1359
+ if (existing !== "" && !input.force) {
1360
+ installed.push({ name, state: "kept" });
1361
+ input.notes.push(".agents/skills/" + name + "/SKILL.md differs from the shipped skill; it was left alone");
1362
+ continue;
1363
+ }
1364
+ if (input.write) {
1365
+ yield* Effect.orElseSucceed(input.fs.makeDirectory(input.path.dirname(target), { recursive: true }), () => undefined);
1366
+ yield* Effect.orElseSucceed(input.fs.writeFileString(target, body), () => undefined);
1367
+ installed.push({ name, state: "written" });
1368
+ }
1369
+ else {
1370
+ installed.push({ name, state: "would write" });
1371
+ }
1372
+ }
1373
+ return installed;
1374
+ });
1375
+ /** The line a generated hook carries, so a re-run recognises its own work. */
1376
+ const HOOK_MARKER = "# jig: generated pre-commit";
1377
+ /**
1378
+ * The pre-commit hook: jig's scoped gate, and a loud step-aside when the CLI is absent.
1379
+ *
1380
+ * `--gate touched-files` is exactly "the change in front of you", so the hook needs no new mode.
1381
+ * The guard matters more than the check: in a repository whose harness is gitignored, a
1382
+ * contributor without the CLI would fail every commit, and a hook that fails for them is how a
1383
+ * good gate becomes a hostile one.
1384
+ *
1385
+ * @param input - The command that runs jig here, and whether this is a plan.
1386
+ * @returns The hook body.
1387
+ */
1388
+ const preCommitHook = (input) => {
1389
+ const binary = input.jig.split(" ")[0] ?? input.jig;
1390
+ return [
1391
+ "#!/bin/sh",
1392
+ HOOK_MARKER + " -- the scoped gate. Delete this file to disable it.",
1393
+ "#",
1394
+ "# It runs the change in front of you, never the whole repository. With no CLI on this",
1395
+ "# machine it says so and exits 0: a hook that fails for a contributor who has not installed",
1396
+ "# the harness is how a local-only gate becomes a hostile one.",
1397
+ "if ! command -v " + binary + " >/dev/null 2>&1; then",
1398
+ ' echo "jig: no ' + input.jig + ' on this machine; pre-commit check skipped" >&2',
1399
+ " exit 0",
1400
+ "fi",
1401
+ "exec " + input.jig + " check --gate touched-files",
1402
+ "",
1403
+ ].join("\n");
1404
+ };
1405
+ /** The root-level harness files whose ignore lines \`--unignore\` may remove. */
1406
+ const unignorable = (profile) => [
1407
+ "jig.config.json",
1408
+ "joggle.config.json",
1409
+ profile.cutlistExisting?.path ?? "cutlist.config.json",
1410
+ profile.baseline,
1411
+ profile.cookbook,
1412
+ profile.onboarding,
1413
+ ].filter((path) => !path.includes("/"));
1414
+ /**
1415
+ * Remove the exact lines that hide the harness, and say what a pattern still hides.
1416
+ *
1417
+ * A line can be deleted safely; a glob cannot, so this never guesses at one -- it reports it and
1418
+ * leaves the decision to a person. Editing `.gitignore` changes what git tracks for everyone, so
1419
+ * it happens only when asked.
1420
+ *
1421
+ * @param input - The root, the candidate paths, and whether this is a plan.
1422
+ * @returns The lines removed, and the ones a pattern hides.
1423
+ */
1424
+ const unignoreHarness = (input) => Effect.gen(function* () {
1425
+ const fs = yield* FileSystem.FileSystem;
1426
+ const path = yield* Path.Path;
1427
+ const file = path.join(input.root, ".gitignore");
1428
+ const text = yield* Effect.orElseSucceed(fs.readFileString(file), () => "");
1429
+ if (text === "")
1430
+ return { removed: [], patterned: [] };
1431
+ const lines = text.split("\n");
1432
+ const removed = [];
1433
+ const kept = lines.filter((line) => {
1434
+ const trimmed = line.trim();
1435
+ if (!input.paths.includes(trimmed))
1436
+ return true;
1437
+ removed.push(trimmed);
1438
+ return false;
1439
+ });
1440
+ if (removed.length > 0 && !input.dryRun) {
1441
+ yield* Effect.orElseSucceed(fs.writeFileString(file, kept.join("\n")), () => undefined);
1442
+ }
1443
+ // Everything else that still ignores a candidate came from a pattern, not a line.
1444
+ const leftover = yield* ignoredByGit({ root: input.root, files: input.paths });
1445
+ return { removed, patterned: leftover.filter((path) => !removed.includes(path)) };
1446
+ });
1447
+ /** Write one generated file unless it already exists, and record which happened. */
1448
+ const writeIfAbsent = (input) => Effect.gen(function* () {
1449
+ const target = input.path.join(input.root, input.file);
1450
+ const exists = yield* Effect.orElseSucceed(input.fs.exists(target), () => false);
1451
+ if (exists && !input.force) {
1452
+ input.kept.push(input.file);
1453
+ return;
1454
+ }
1455
+ if (input.write)
1456
+ yield* input.fs.writeFileString(target, input.body);
1457
+ input.written.push(input.file);
1458
+ });
1459
+ /**
1460
+ * Inspect a repository and write the harness it should have.
1461
+ *
1462
+ * @param root - The project root.
1463
+ * @param options - Gate mode, and whether generated files may be rewritten.
1464
+ * @returns the profile, and what was written versus kept.
1465
+ */
1466
+ export const initialise = (root, options = {}) => Effect.gen(function* () {
1467
+ const fs = yield* FileSystem.FileSystem;
1468
+ const path = yield* Path.Path;
1469
+ let profile = yield* inspectRepo(root, {
1470
+ gateMode: options.gateMode,
1471
+ force: options.force,
1472
+ });
1473
+ const written = [];
1474
+ const kept = [];
1475
+ const force = options.force === true;
1476
+ const dryRun = options.dryRun === true;
1477
+ yield* writeIfAbsent({
1478
+ fs,
1479
+ path,
1480
+ root,
1481
+ file: "jig.config.json",
1482
+ body: `${JSON.stringify(configFor(profile), null, 2)}\n`,
1483
+ force,
1484
+ write: !dryRun,
1485
+ written,
1486
+ kept,
1487
+ });
1488
+ let cutlistConfig = "absent";
1489
+ if (profile.cutlistDraft !== undefined) {
1490
+ const target = path.join(root, "cutlist.config.json");
1491
+ if (yield* Effect.orElseSucceed(fs.exists(target), () => false)) {
1492
+ cutlistConfig = "kept";
1493
+ kept.push("cutlist.config.json");
1494
+ }
1495
+ else if (options.cutlist === true) {
1496
+ if (!dryRun) {
1497
+ yield* fs.writeFileString(target, `${JSON.stringify(profile.cutlistDraft, null, 2)}\n`);
1498
+ }
1499
+ cutlistConfig = "written";
1500
+ written.push("cutlist.config.json");
1501
+ profile = {
1502
+ ...profile,
1503
+ notes: [
1504
+ ...profile.notes.filter((note) => !note.startsWith("cutlist not enabled")),
1505
+ "cutlist draft written: review cutlist.config.json, run `" +
1506
+ invocationOf({ profile, tool: "cutlist", args: "build" }) +
1507
+ "`, then re-run `jig init --force` to enable it",
1508
+ ],
1509
+ };
1510
+ }
1511
+ }
1512
+ // `.gitattributes` is shared with the repo, so this merges one marked block and
1513
+ // never replaces the file. The fact that it does not need the artifact to exist is
1514
+ // what lets it run before the first build.
1515
+ let gitattributes = "absent";
1516
+ if (profile.cutlistOutput !== undefined) {
1517
+ const target = path.join(root, ".gitattributes");
1518
+ const existing = yield* Effect.orElseSucceed(fs.readFileString(target), () => undefined);
1519
+ const merged = mergeGitattributes(existing, generatedRules(profile.cutlistOutput));
1520
+ gitattributes = merged.action;
1521
+ if (merged.action === "malformed") {
1522
+ kept.push(".gitattributes");
1523
+ profile = {
1524
+ ...profile,
1525
+ notes: [
1526
+ ...profile.notes,
1527
+ `.gitattributes has a "${GENERATED_BEGIN}" block with no "${GENERATED_END}"; add it and re-run init`,
1528
+ ],
1529
+ };
1530
+ }
1531
+ else if (merged.action === "unchanged") {
1532
+ kept.push(".gitattributes");
1533
+ }
1534
+ else {
1535
+ if (!dryRun)
1536
+ yield* fs.writeFileString(target, merged.body);
1537
+ written.push(".gitattributes");
1538
+ }
1539
+ }
1540
+ // The baseline is a reviewed ledger. Even `--force` does not replace it.
1541
+ const baseline = path.join(root, profile.baseline);
1542
+ if (yield* Effect.orElseSucceed(fs.exists(baseline), () => false)) {
1543
+ kept.push(profile.baseline);
1544
+ }
1545
+ else {
1546
+ if (!dryRun)
1547
+ yield* writeBaseline(baseline, emptyBaseline);
1548
+ written.push(profile.baseline);
1549
+ }
1550
+ yield* writeIfAbsent({
1551
+ fs,
1552
+ path,
1553
+ root,
1554
+ file: profile.cookbook,
1555
+ body: cookbookFor(profile),
1556
+ force,
1557
+ write: !dryRun,
1558
+ written,
1559
+ kept,
1560
+ });
1561
+ yield* writeIfAbsent({
1562
+ fs,
1563
+ path,
1564
+ root,
1565
+ file: profile.onboarding,
1566
+ body: onboardingFor(profile),
1567
+ force,
1568
+ write: !dryRun,
1569
+ written,
1570
+ kept,
1571
+ });
1572
+ const accepted = yield* readBaseline(baseline).pipe(Effect.map((value) => value.identities.length), Effect.orElseSucceed(() => 0));
1573
+ let joggleConfig = "absent";
1574
+ if (profile.engines.some((engine) => engine.id === "joggle")) {
1575
+ const target = path.join(root, "joggle.config.json");
1576
+ const draft = profile.architectureDraft?.layers;
1577
+ if (yield* Effect.orElseSucceed(fs.exists(target), () => false)) {
1578
+ // `--force` re-drafts the includes and keeps the judgement written into them. The
1579
+ // committed vocabulary is the draft plus the forbids someone checked against a
1580
+ // manifest, so a draft that learns a tier (a routes split gaining `support`) has to
1581
+ // reach a repo that already has the file -- otherwise the only way to get it is to
1582
+ // delete a reviewed file, and a stale draft reads as a clean architecture.
1583
+ const text = yield* Effect.orElseSucceed(fs.readFileString(target), () => "");
1584
+ const parsed = parseJson(text);
1585
+ if (options.force === true && draft !== undefined && isRecord(parsed)) {
1586
+ const merged = mergeArchitecture({ existing: parsed, draft });
1587
+ if (merged.forbidsDropped.length > 0) {
1588
+ profile = {
1589
+ ...profile,
1590
+ notes: [
1591
+ ...profile.notes,
1592
+ `the architecture draft no longer proposes ${merged.forbidsDropped.join(", ")}; ` +
1593
+ "their `forbid` sets were dropped -- check the layers before trusting `layer-purity`",
1594
+ ],
1595
+ };
1596
+ }
1597
+ if (!dryRun) {
1598
+ yield* fs.writeFileString(target, `${JSON.stringify(merged.file, null, 2)}\n`);
1599
+ }
1600
+ joggleConfig = "written";
1601
+ written.push("joggle.config.json");
1602
+ }
1603
+ else {
1604
+ joggleConfig = "kept";
1605
+ kept.push("joggle.config.json");
1606
+ }
1607
+ }
1608
+ else {
1609
+ // A repository without a model key should not print every unjudged candidate
1610
+ // as a warning. `count` keeps the census honest and the output usable; a repo
1611
+ // with a key can change it to `report` when it wants the candidates listed.
1612
+ // The repository summary is the one piece of prose a judged rule can use, and
1613
+ // it is already written down in the repo's own agent docs or README.
1614
+ // JSON.stringify drops the undefined keys, so an absent draft or summary never reaches
1615
+ // the file -- and the object keeps its literal type instead of widening to a dictionary.
1616
+ const starter = {
1617
+ unavailable: "count",
1618
+ architecture: profile.architectureDraft,
1619
+ // The draft is includes only: the order and the `forbid` sets are judgement, so the
1620
+ // rules that would read them stay off until someone sets them. An alphabetical draft
1621
+ // that silently reports 0 is worse than no draft at all.
1622
+ rules: profile.architectureDraft === undefined
1623
+ ? undefined
1624
+ : { "joggle/layer-direction": "off", "joggle/layer-purity": "off" },
1625
+ evidence: profile.summary === "" ? undefined : { repository: profile.summary },
1626
+ };
1627
+ if (!dryRun) {
1628
+ yield* fs.writeFileString(target, `${JSON.stringify(starter, null, 2)}\n`);
1629
+ }
1630
+ joggleConfig = "written";
1631
+ written.push("joggle.config.json");
1632
+ }
1633
+ }
1634
+ // Born accepted: an engine with its own ledger gets one written once, so day one is
1635
+ // "nothing new" instead of a pile a person must judge before the gate means anything.
1636
+ // Never rewritten, for the same reason `.jig-baseline.json` is never rewritten.
1637
+ const engineBaselines = [];
1638
+ const joggle = profile.engines.find((engine) => engine.id === "joggle");
1639
+ // Only when the effective config will actually read it: a ledger nothing references is a
1640
+ // second answer waiting to disagree with the first.
1641
+ const wantsLedger = (joggle?.args ?? []).includes("--baseline");
1642
+ if (joggle !== undefined && wantsLedger) {
1643
+ const target = path.join(root, JOGGLE_BASELINE);
1644
+ const exists = yield* Effect.orElseSucceed(fs.exists(target), () => false);
1645
+ if (exists) {
1646
+ kept.push(JOGGLE_BASELINE);
1647
+ engineBaselines.push({ id: "joggle", path: JOGGLE_BASELINE, accepted: 0, action: "kept" });
1648
+ }
1649
+ else if (dryRun) {
1650
+ engineBaselines.push({
1651
+ id: "joggle",
1652
+ path: JOGGLE_BASELINE,
1653
+ accepted: 0,
1654
+ action: "would accept",
1655
+ });
1656
+ }
1657
+ else {
1658
+ const outcome = yield* Effect.orElseSucceed(exec({
1659
+ binary: resolveEngineCommand({ root, command: "joggle" }),
1660
+ args: ["check", ...(joggle.args ?? []), "--update-baseline", JOGGLE_BASELINE],
1661
+ cwd: root,
1662
+ }), () => undefined);
1663
+ const wrote = yield* Effect.orElseSucceed(fs.exists(target), () => false);
1664
+ if (!wrote) {
1665
+ profile = {
1666
+ ...profile,
1667
+ notes: [
1668
+ ...profile.notes,
1669
+ "joggle did not write " +
1670
+ JOGGLE_BASELINE +
1671
+ (outcome === undefined
1672
+ ? " (the command did not start)"
1673
+ : " (exit " + String(outcome.code) + ")") +
1674
+ "; run `joggle check --update-baseline " +
1675
+ JOGGLE_BASELINE +
1676
+ "` by hand",
1677
+ ],
1678
+ };
1679
+ }
1680
+ else {
1681
+ const text = yield* Effect.orElseSucceed(fs.readFileString(target), () => "");
1682
+ const parsed = parseJson(text);
1683
+ const identities = isRecord(parsed) && Array.isArray(parsed["identities"]) ? parsed["identities"] : [];
1684
+ written.push(JOGGLE_BASELINE);
1685
+ engineBaselines.push({
1686
+ id: "joggle",
1687
+ path: JOGGLE_BASELINE,
1688
+ accepted: identities.length,
1689
+ action: "written",
1690
+ });
1691
+ }
1692
+ }
1693
+ }
1694
+ // The write is done; whether anyone can commit it is a separate question, and one the
1695
+ // person only learns when the branch is pushed and the config is not in it.
1696
+ // Ask about the rulebooks too: a ledger git can see while its config it cannot is worse
1697
+ // than a local-only harness -- the record travels and the rules that produced it do not.
1698
+ const rulebooks = [
1699
+ "jig.config.json",
1700
+ ...(profile.engines.some((engine) => engine.id === "joggle") ? ["joggle.config.json"] : []),
1701
+ ...(profile.cutlistExisting === undefined ? [] : [profile.cutlistExisting.path]),
1702
+ ];
1703
+ const ledgers = [
1704
+ profile.baseline,
1705
+ ...(profile.engines.some((engine) => engine.id === "joggle") ? [JOGGLE_BASELINE] : []),
1706
+ ];
1707
+ const ignored = yield* ignoredByGit({
1708
+ root,
1709
+ files: [
1710
+ ...new Set([
1711
+ ...written,
1712
+ ...kept,
1713
+ profile.baseline,
1714
+ ...rulebooks,
1715
+ // The catalog is an engine's committed input, not a build artifact: `cutlist
1716
+ // build --check` compares against it, so an ignored one silently passes here and
1717
+ // fails everywhere else.
1718
+ ...(profile.cutlistOutput === undefined ? [] : [profile.cutlistOutput.catalog]),
1719
+ ]),
1720
+ ],
1721
+ });
1722
+ const ignoredSet = new Set(ignored);
1723
+ const committable = [...written, ...kept];
1724
+ const hiddenRulebook = rulebooks.find((file) => ignoredSet.has(file));
1725
+ const visibleLedger = ledgers.find((file) => committable.includes(file) && !ignoredSet.has(file));
1726
+ const split = hiddenRulebook === undefined || visibleLedger === undefined
1727
+ ? undefined
1728
+ : "`" +
1729
+ visibleLedger +
1730
+ "` can be committed while `" +
1731
+ hiddenRulebook +
1732
+ "` cannot: the record travels, the rules that produced it do not";
1733
+ const unignored = options.unignore === true
1734
+ ? yield* unignoreHarness({
1735
+ root,
1736
+ paths: unignorable(profile),
1737
+ dryRun,
1738
+ })
1739
+ : { removed: [], patterned: [] };
1740
+ const unignoreNote = unignored.removed.length === 0
1741
+ ? []
1742
+ : [
1743
+ `${dryRun ? "would remove" : "removed"} ${String(unignored.removed.length)} ignore line(s) (${unignored.removed.join(", ")}): the harness can be committed now`,
1744
+ ];
1745
+ const patternNote = unignored.patterned.length === 0
1746
+ ? []
1747
+ : [
1748
+ `${unignored.patterned.join(", ")} ${unignored.patterned.length === 1 ? "is" : "are"} hidden by a pattern rather than a line; nothing here removes a glob -- un-ignore ${unignored.patterned.length === 1 ? "it" : "them"} by hand if that is what you want`,
1749
+ ];
1750
+ const added = [
1751
+ ...(ignored.length === 0
1752
+ ? []
1753
+ : [
1754
+ `${ignored.length} path(s) here are gitignored (${ignored.join(", ")}): the harness is local-only, so it gates this machine and nothing else`,
1755
+ ]),
1756
+ ...unignoreNote,
1757
+ ...patternNote,
1758
+ ...(split === undefined ? [] : [split]),
1759
+ ];
1760
+ const noted = added.length === 0 ? profile : { ...profile, notes: [...profile.notes, ...added] };
1761
+ // The scoped hook is opt-in: a hook enabled before a baseline is committed fails the first
1762
+ // push for everyone, and a hook that fires where the harness is gitignored is worse.
1763
+ let hooks = "absent";
1764
+ // A note list computed in inspectRepo is a readonly array; the hook outcome is decided here.
1765
+ const hookNotes = [];
1766
+ if (options.hooks === true) {
1767
+ const hooksDir = path.join(root, ".git", "hooks");
1768
+ const inside = yield* Effect.orElseSucceed(fs.exists(path.join(root, ".git")), () => false);
1769
+ if (!inside) {
1770
+ hooks = "not-a-repo";
1771
+ hookNotes.push("--hooks was given but this is not a git repository; nothing was written to .git/hooks");
1772
+ }
1773
+ else {
1774
+ const target = path.join(hooksDir, "pre-commit");
1775
+ const body = preCommitHook({ jig: profile.jig });
1776
+ const existing = yield* Effect.orElseSucceed(fs.readFileString(target), () => undefined);
1777
+ if (existing !== undefined && !existing.includes(HOOK_MARKER)) {
1778
+ hooks = "foreign";
1779
+ hookNotes.push(".git/hooks/pre-commit already exists and is not jig's; it was left alone");
1780
+ }
1781
+ else if (existing === body) {
1782
+ hooks = "kept";
1783
+ }
1784
+ else if (dryRun) {
1785
+ hooks = "would write";
1786
+ }
1787
+ else {
1788
+ yield* Effect.orElseSucceed(fs.makeDirectory(hooksDir, { recursive: true }), () => undefined);
1789
+ yield* Effect.orElseSucceed(fs.writeFileString(target, body), () => undefined);
1790
+ yield* Effect.orElseSucceed(fs.chmod(target, 0o755), () => undefined);
1791
+ hooks = "written";
1792
+ written.push(".git/hooks/pre-commit");
1793
+ }
1794
+ }
1795
+ }
1796
+ // Opt-in, like the hook: a repository that already keeps skills of its own keeps them, because
1797
+ // only a file this wrote is a file this would replace.
1798
+ // Part of init, not a second install step: the skills are files in the repo, and both hosts
1799
+ // read .agents/skills, so onboarding them is onboarding the harness.
1800
+ const skills = options.skills === false
1801
+ ? []
1802
+ : yield* installSkills({ fs, path, root, write: !dryRun, force, notes: hookNotes });
1803
+ for (const skill of skills) {
1804
+ if (skill.state === "written")
1805
+ written.push(".agents/skills/" + skill.name + "/SKILL.md");
1806
+ }
1807
+ const withNotes = hookNotes.length === 0 ? noted : { ...noted, notes: [...noted.notes, ...hookNotes] };
1808
+ // A generated file's bytes belong to the generator -- the rule the exemplar's catalog
1809
+ // already lives under, because `cutlist build --check` hashes it. A formatter that reflows
1810
+ // these turns every `init --force` into a two-way rewrite on a file nobody edited, so the
1811
+ // exemption is named rather than assumed, and only when the list does not already say so.
1812
+ const generated = GENERATED_JSON.filter((file) => written.includes(file));
1813
+ const formatter = generated.length === 0 ? undefined : yield* formatterOf({ fs, path, root });
1814
+ const missing = formatter === undefined
1815
+ ? []
1816
+ : generated.filter((file) => !exemptedBy(formatter.patterns, file));
1817
+ const titles = formatter === undefined || missing.length === 0
1818
+ ? withNotes
1819
+ : {
1820
+ ...withNotes,
1821
+ notes: [
1822
+ ...withNotes.notes,
1823
+ missing.join(", ") +
1824
+ (missing.length === 1 ? " is" : " are") +
1825
+ " generated: a formatter that reflows " +
1826
+ (missing.length === 1 ? "it" : "them") +
1827
+ " makes every `init --force` a two-way rewrite. Add " +
1828
+ (missing.length === 1 ? "it" : "them") +
1829
+ " to " +
1830
+ formatter.file +
1831
+ "'s ignore list -- a generated file's bytes belong to the generator, the same rule as the catalog.",
1832
+ ],
1833
+ };
1834
+ return {
1835
+ profile: titles,
1836
+ written,
1837
+ kept,
1838
+ ignore: [
1839
+ ...unignored.removed.map((path) => ({ path, status: "removed" })),
1840
+ ...unignored.patterned.map((path) => ({ path, status: "pattern" })),
1841
+ ...ignored
1842
+ .filter((path) => !unignored.removed.includes(path) && !unignored.patterned.includes(path))
1843
+ .map((path) => ({ path, status: "hidden" })),
1844
+ ],
1845
+ engineBaselines,
1846
+ joggleConfig,
1847
+ cutlistConfig,
1848
+ gitattributes,
1849
+ dryRun,
1850
+ accepted,
1851
+ hooks,
1852
+ skills,
1853
+ };
1854
+ });
1855
+ //# sourceMappingURL=init.js.map