monkeyshape 0.0.0-stage → 0.2.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 (66) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +54 -2
  3. package/config/biome.base.json +71 -0
  4. package/config/tsconfig.base.json +31 -0
  5. package/docs/workflow.md +131 -0
  6. package/package.json +68 -4
  7. package/skills/handoff/SKILL.md +54 -0
  8. package/skills/milestone/SKILL.md +107 -0
  9. package/skills/review-pr/SKILL.md +135 -0
  10. package/skills/roadmap/SKILL.md +66 -0
  11. package/skills/track/SKILL.md +75 -0
  12. package/src/adapters/baseline.ts +55 -0
  13. package/src/adapters/config.ts +25 -0
  14. package/src/adapters/init.ts +176 -0
  15. package/src/adapters/process.ts +38 -0
  16. package/src/adapters/reviews.ts +170 -0
  17. package/src/adapters/skills.ts +113 -0
  18. package/src/adapters/tracks.ts +616 -0
  19. package/src/adapters/workspace.ts +281 -0
  20. package/src/api/monkeyshape.ts +8 -0
  21. package/src/cli/main.ts +359 -0
  22. package/src/core/arch.ts +224 -0
  23. package/src/core/budgets.ts +187 -0
  24. package/src/core/check.ts +122 -0
  25. package/src/core/coverage.ts +118 -0
  26. package/src/core/decisions.ts +65 -0
  27. package/src/core/garden.ts +41 -0
  28. package/src/core/glob.ts +22 -0
  29. package/src/core/handoff.ts +183 -0
  30. package/src/core/hooks.ts +60 -0
  31. package/src/core/jsonc.ts +26 -0
  32. package/src/core/layout.ts +123 -0
  33. package/src/core/markdown.ts +93 -0
  34. package/src/core/model.ts +100 -0
  35. package/src/core/parse.ts +41 -0
  36. package/src/core/paths.ts +19 -0
  37. package/src/core/ratchet.ts +75 -0
  38. package/src/core/refs.ts +214 -0
  39. package/src/core/report.ts +67 -0
  40. package/src/core/rules/ast.ts +50 -0
  41. package/src/core/rules/decodeStrict.ts +60 -0
  42. package/src/core/rules/effectRunAtEdge.ts +33 -0
  43. package/src/core/rules/engine.ts +150 -0
  44. package/src/core/rules/noErrorSpread.ts +28 -0
  45. package/src/core/rules/noNondeterminism.ts +65 -0
  46. package/src/core/rules/noThrow.ts +79 -0
  47. package/src/core/rules/registry.ts +15 -0
  48. package/src/core/scaffold.ts +90 -0
  49. package/src/core/scope.ts +120 -0
  50. package/src/core/skills.ts +291 -0
  51. package/src/core/tracks.ts +358 -0
  52. package/src/helpers/decodeStrict.ts +8 -0
  53. package/src/schemas/config.ts +221 -0
  54. package/src/schemas/errors.ts +31 -0
  55. package/template/.github/pull_request_template.md +11 -0
  56. package/template/.github/workflows/ci.yml +22 -0
  57. package/template/AGENTS.md +37 -0
  58. package/template/CLAUDE.md +1 -0
  59. package/template/DECISIONS.md +8 -0
  60. package/template/README.md +14 -0
  61. package/template/docs/roadmap.md +14 -0
  62. package/template/gitignore +7 -0
  63. package/template/notes/.gitkeep +0 -0
  64. package/template/plan/.gitkeep +0 -0
  65. package/template/shape.config.ts +26 -0
  66. package/template/test/toolchain.test.ts +7 -0
@@ -0,0 +1,100 @@
1
+ /** The data every check reads and the findings it returns. Pure: no I/O lives here. */
2
+
3
+ export type CheckName = "arch" | "refs" | "budgets" | "coverage" | "rules" | "skills";
4
+
5
+ export interface Violation {
6
+ /**
7
+ * `prerequisites` are failures of the environment a check needs (a required integration
8
+ * that can't run). They are never baselined and never skipped by `--only`.
9
+ */
10
+ readonly check: CheckName | "prerequisites";
11
+ /** Namespaced, e.g. `rules/no-throw`. Baselines and reports key on it. */
12
+ readonly rule: string;
13
+ /** Repo-relative path, `/`-separated. */
14
+ readonly file: string;
15
+ readonly line?: number;
16
+ readonly message: string;
17
+ }
18
+
19
+ /** What the checks see of the repo, loaded once by the workspace adapter. */
20
+ export interface Snapshot {
21
+ /** Tracked and untracked-but-not-ignored files, repo-relative. */
22
+ readonly files: ReadonlyArray<string>;
23
+ /** Contents of the files checks read (sources, docs, configs), by path. */
24
+ readonly texts: ReadonlyMap<string, string>;
25
+ readonly packageScripts: ReadonlySet<string>;
26
+ /** bd memories by key, when `integrations.beads` is ok. */
27
+ readonly memories: ReadonlyMap<string, string> | undefined;
28
+ /** Every bead id, open or closed, when `integrations.beads` is ok. */
29
+ readonly beadIds: ReadonlySet<string> | undefined;
30
+ /** Files in a tsconfig program, as `tsc --listFilesOnly` reports them, when tsc ran. */
31
+ readonly typechecked: ReadonlySet<string> | undefined;
32
+ /** Files biome processes, as biome itself reports them, when biome ran. */
33
+ readonly linted: ReadonlySet<string> | undefined;
34
+ readonly integrations: Integrations;
35
+ readonly skills: SkillsSnapshot;
36
+ }
37
+
38
+ /** File bytes keyed by path relative to a skills directory: `<skill>/SKILL.md`. Bytes, so a
39
+ * skill's images or binaries are copied and compared exactly. */
40
+ export type SkillFiles = ReadonlyMap<string, Uint8Array>;
41
+
42
+ /** What sits at `.claude/skills`: `target` is the link's own text, unresolved. */
43
+ export type SkillsLink =
44
+ | { readonly kind: "missing" }
45
+ | { readonly kind: "link"; readonly target: string }
46
+ | { readonly kind: "directory" }
47
+ | { readonly kind: "other" };
48
+
49
+ /** The installed skills, read from disk, and the ones the running monkeyshape ships. */
50
+ export interface SkillsSnapshot {
51
+ readonly link: SkillsLink;
52
+ /** Files under `.agents/skills`. */
53
+ readonly installed: SkillFiles;
54
+ /** Files under `.claude/skills` when it is a real directory; empty otherwise. */
55
+ readonly claudeDirectory: SkillFiles;
56
+ /** Files under the package's `skills/`. */
57
+ readonly shipped: SkillFiles;
58
+ }
59
+
60
+ /**
61
+ * How an optional tool fared. `absent`: the repo doesn't use it. `unavailable`: it isn't
62
+ * installed here (bd in CI). `failed`: it ran and broke, which is never silently skipped.
63
+ */
64
+ export type Integration =
65
+ | { readonly state: "ok" }
66
+ | { readonly state: "absent" }
67
+ | { readonly state: "unavailable"; readonly reason: string }
68
+ | { readonly state: "failed"; readonly reason: string };
69
+
70
+ export interface Integrations {
71
+ readonly beads: Integration;
72
+ readonly tsc: Integration;
73
+ readonly biome: Integration;
74
+ }
75
+
76
+ export const TS_SOURCE = /\.(ts|tsx|mts|cts)$/;
77
+
78
+ export const isTsSource = (path: string): boolean =>
79
+ TS_SOURCE.test(path) && !path.endsWith(".d.ts");
80
+
81
+ /** Every directory that contains a file, plus the files themselves. */
82
+ export const pathIndex = (files: ReadonlyArray<string>): ReadonlySet<string> => {
83
+ const index = new Set<string>();
84
+ for (const file of files) {
85
+ index.add(file);
86
+ const segments = file.split("/");
87
+ for (let i = 1; i < segments.length; i++) index.add(segments.slice(0, i).join("/"));
88
+ }
89
+ return index;
90
+ };
91
+
92
+ export const lineCount = (text: string): number =>
93
+ text.length === 0 ? 0 : text.split("\n").length - (text.endsWith("\n") ? 1 : 0);
94
+
95
+ /** 1-based line of a UTF-16 offset. */
96
+ export const lineAt = (text: string, offset: number): number => {
97
+ let line = 1;
98
+ for (let i = 0; i < offset && i < text.length; i++) if (text.charCodeAt(i) === 10) line++;
99
+ return line;
100
+ };
@@ -0,0 +1,41 @@
1
+ /** One parse per file, shared by the arch, rules and refs checks. */
2
+ import { type Comment, type Program, parseSync } from "oxc-parser";
3
+
4
+ export interface Parsed {
5
+ readonly path: string;
6
+ readonly text: string;
7
+ readonly program: Program;
8
+ readonly comments: ReadonlyArray<Comment>;
9
+ /** Static, re-export and literal dynamic import specifiers (type-only included). */
10
+ readonly imports: ReadonlyArray<string>;
11
+ readonly syntaxErrors: ReadonlyArray<string>;
12
+ }
13
+
14
+ const cache = new Map<string, Parsed>();
15
+
16
+ export const parse = (path: string, text: string): Parsed => {
17
+ const cached = cache.get(path);
18
+ if (cached !== undefined && cached.text === text) return cached;
19
+ const lang = path.endsWith("x") ? "tsx" : "ts";
20
+ const result = parseSync(path, text, { lang, preserveParens: false });
21
+ const imports: Array<string> = [];
22
+ for (const entry of result.module.staticImports) imports.push(entry.moduleRequest.value);
23
+ for (const entry of result.module.staticExports)
24
+ for (const item of entry.entries)
25
+ if (item.moduleRequest !== null) imports.push(item.moduleRequest.value);
26
+ for (const entry of result.module.dynamicImports) {
27
+ const literal = text.slice(entry.moduleRequest.start, entry.moduleRequest.end);
28
+ const match = /^["'`]([^"'`$]+)["'`]$/.exec(literal);
29
+ if (match?.[1] !== undefined) imports.push(match[1]);
30
+ }
31
+ const parsed: Parsed = {
32
+ path,
33
+ text,
34
+ program: result.program,
35
+ comments: result.comments,
36
+ imports: [...new Set(imports)],
37
+ syntaxErrors: result.errors.map((error) => error.message),
38
+ };
39
+ cache.set(path, parsed);
40
+ return parsed;
41
+ };
@@ -0,0 +1,19 @@
1
+ /** POSIX path helpers for repo-relative paths. Kept here so core needs no host module. */
2
+
3
+ export const dirname = (path: string): string => {
4
+ const index = path.lastIndexOf("/");
5
+ return index === -1 ? "" : path.slice(0, index);
6
+ };
7
+
8
+ /** Joins and normalizes; a result escaping the root keeps its leading `..` segments. */
9
+ export const join = (...parts: ReadonlyArray<string>): string => {
10
+ const out: Array<string> = [];
11
+ for (const segment of parts.join("/").split("/")) {
12
+ if (segment === "" || segment === ".") continue;
13
+ if (segment === ".." && out.length > 0 && out[out.length - 1] !== "..") out.pop();
14
+ else out.push(segment);
15
+ }
16
+ return out.join("/");
17
+ };
18
+
19
+ export const basename = (path: string): string => path.slice(path.lastIndexOf("/") + 1);
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Ratchets let a rule land before the code is clean: existing violations are counted per
3
+ * rule and file in a baseline, and counts may only go down. A count above the baseline
4
+ * fails; a count below it fails too (the ratchet is loose) until `mshape baseline
5
+ * --tighten` lowers it, so fixed violations can't silently come back.
6
+ */
7
+ import type { Violation } from "./model.ts";
8
+
9
+ export type Counts = Readonly<Record<string, Readonly<Record<string, number>>>>;
10
+
11
+ export interface RatchetResult {
12
+ readonly failing: ReadonlyArray<Violation>;
13
+ readonly loose: ReadonlyArray<{
14
+ readonly rule: string;
15
+ readonly file: string;
16
+ readonly allowed: number;
17
+ readonly found: number;
18
+ }>;
19
+ readonly grandfathered: number;
20
+ }
21
+
22
+ export const count = (violations: ReadonlyArray<Violation>): Counts => {
23
+ const counts: Record<string, Record<string, number>> = {};
24
+ for (const v of violations) {
25
+ const byFile = counts[v.rule] ?? {};
26
+ byFile[v.file] = (byFile[v.file] ?? 0) + 1;
27
+ counts[v.rule] = byFile;
28
+ }
29
+ return counts;
30
+ };
31
+
32
+ export const applyBaseline = (
33
+ violations: ReadonlyArray<Violation>,
34
+ baseline: Counts,
35
+ unevaluated: ReadonlySet<string> = new Set(),
36
+ ): RatchetResult => {
37
+ const current = count(violations);
38
+ const failing: Array<Violation> = [];
39
+ const loose: Array<RatchetResult["loose"][number]> = [];
40
+ let grandfathered = 0;
41
+ for (const v of violations) {
42
+ const allowed = baseline[v.rule]?.[v.file] ?? 0;
43
+ const found = current[v.rule]?.[v.file] ?? 0;
44
+ if (found > allowed)
45
+ failing.push(
46
+ allowed === 0
47
+ ? v
48
+ : { ...v, message: `${v.message} (baseline allows ${allowed} here, found ${found})` },
49
+ );
50
+ else grandfathered++;
51
+ }
52
+ for (const [rule, files] of Object.entries(baseline))
53
+ for (const [file, allowed] of Object.entries(files)) {
54
+ const found = current[rule]?.[file] ?? 0;
55
+ if (found < allowed && !unevaluated.has(rule)) loose.push({ rule, file, allowed, found });
56
+ }
57
+ return { failing, loose, grandfathered };
58
+ };
59
+
60
+ /** Lowers counts to what is found now; never raises one or adds a new entry. */
61
+ export const tighten = (
62
+ baseline: Counts,
63
+ violations: ReadonlyArray<Violation>,
64
+ unevaluated: ReadonlySet<string> = new Set(),
65
+ ): Counts => {
66
+ const current = count(violations);
67
+ const next: Record<string, Record<string, number>> = {};
68
+ for (const [rule, files] of Object.entries(baseline))
69
+ for (const [file, allowed] of Object.entries(files)) {
70
+ // Not counted on this machine: keep the entry rather than mistake it for fixed.
71
+ const kept = unevaluated.has(rule) ? allowed : Math.min(allowed, current[rule]?.[file] ?? 0);
72
+ if (kept > 0) next[rule] = { ...next[rule], [file]: kept };
73
+ }
74
+ return next;
75
+ };
@@ -0,0 +1,214 @@
1
+ /**
2
+ * References in prose must resolve, and prose may only point at things a check keeps true.
3
+ * Docs: backticked paths, `bun run` scripts, decision slugs and relative links must exist, and
4
+ * each backticked span sits on one line, where it can be checked;
5
+ * normative docs may not link into notes/, plan/ or handoffs. Code comments: no links into
6
+ * those either, no `§N` citations, decision slugs must exist, bead ids only in `TODO(id)`.
7
+ */
8
+ import type { ResolvedConfig } from "../schemas/config.ts";
9
+ import { parseDecisions, SLUG } from "./decisions.ts";
10
+ import { matchesAny } from "./glob.ts";
11
+ import { fencedLines, opensCodeSpan } from "./markdown.ts";
12
+ import { isTsSource, lineAt, pathIndex, type Snapshot, type Violation } from "./model.ts";
13
+ import { parse } from "./parse.ts";
14
+ import { basename, dirname, join } from "./paths.ts";
15
+
16
+ /**
17
+ * A specific note or handoff, or a section of the milestone plan or the roadmap. Naming the
18
+ * directories or the files is fine: "the roadmap is `docs/roadmap.md`" points, it doesn't cite.
19
+ */
20
+ const NON_NORMATIVE =
21
+ /(^|[\s(`'"/])(?:\.{1,2}\/)*(?:(?:notes|\.handoffs)\/[\w.-]+|(?:plan\/[\w.-]+|docs\/roadmap\.md)#)/;
22
+ const SECTION_CITATION = /§\s*\d/;
23
+ const DECISION_REF = /\bD-[a-z0-9]+(?:-[a-z0-9]+)*\b/g;
24
+ const KNOWN_EXTENSION =
25
+ /\.(ts|tsx|mts|cts|js|mjs|json|jsonc|jsonl|md|yaml|yml|toml|sh|txt|lock|grit|java|py)$/;
26
+
27
+ const violation = (rule: string, file: string, line: number, message: string): Violation => ({
28
+ check: "refs",
29
+ rule: `refs/${rule}`,
30
+ file,
31
+ line,
32
+ message,
33
+ });
34
+
35
+ /** Blanks fenced code blocks (keeping line numbers): examples there are not claims. */
36
+ export const stripFences = (text: string): string => {
37
+ const lines = text.split("\n");
38
+ const { fenced } = fencedLines(lines);
39
+ return lines.map((line, i) => (fenced[i] ? "" : line)).join("\n");
40
+ };
41
+
42
+ /** Anything shaped like `prefix-id` or `prefix-id.3`; only ids beads actually knows count. */
43
+ const BEAD_CANDIDATE = /\b[a-z0-9]+(?:-[a-z0-9]+)*-[a-z0-9]+(?:\.[0-9]+)*\b/g;
44
+
45
+ /** Bare source file names are worth resolving; other bare names are usually runtime files or other packages' docs. */
46
+ const BARE_FILE = /^[\w.-]+\.(ts|tsx|mts|cts)$/;
47
+
48
+ /** Whether a backticked span reads as a repo path we can check, and the path to check. */
49
+ export const pathCandidate = (span: string): string | undefined => {
50
+ const token = span.replace(/:\d+(:\d+)?$/, "");
51
+ if (/\s/.test(token) || token.length < 3) return undefined;
52
+ if (/^(https?:|mailto:|~|-|@|\$|<|node:|bun:)/.test(token)) return undefined;
53
+ if (/[*?{}<>[\]()|=,;"'!]/.test(token) || token.includes("...")) return undefined;
54
+ if (/^\.[\w.]+$/.test(token) || token.startsWith("node_modules/")) return undefined;
55
+ if (!token.includes("/") && !BARE_FILE.test(token)) return undefined;
56
+ return token.replace(/\/$/, "");
57
+ };
58
+
59
+ export const checkRefs = (config: ResolvedConfig, snapshot: Snapshot): ReadonlyArray<Violation> => {
60
+ const violations: Array<Violation> = [];
61
+ const index = pathIndex(snapshot.files);
62
+ const files = new Set(snapshot.files);
63
+ const basenames = new Set(snapshot.files.map(basename));
64
+ const topLevel = new Set(snapshot.files.map((file) => file.split("/")[0] ?? ""));
65
+ const decisions = new Set(
66
+ parseDecisions(snapshot.texts.get("DECISIONS.md") ?? "").map((d) => d.slug),
67
+ );
68
+ const forbidden = config.refs.forbidden.map((f) => ({
69
+ regex: new RegExp(f.pattern),
70
+ reason: f.reason,
71
+ }));
72
+ const beads = snapshot.beadIds;
73
+
74
+ /** Git lists a submodule as one entry; anything below it is the submodule's business. */
75
+ const inSubmodule = (path: string): boolean => {
76
+ const segments = path.split("/");
77
+ return segments.some((_, i) => i > 0 && files.has(segments.slice(0, i).join("/")));
78
+ };
79
+ const pathExists = (doc: string, path: string): boolean => {
80
+ const fromRoot = join(path);
81
+ const fromDoc = join(dirname(doc), path);
82
+ if (index.has(fromRoot) || index.has(fromDoc) || inSubmodule(fromRoot) || inSubmodule(fromDoc))
83
+ return true;
84
+ // A bare file name (`rules.ts`) refers to some file of that name.
85
+ return !path.includes("/") && basenames.has(path);
86
+ };
87
+ /** Paths whose first segment isn't in the repo are probably package subpaths (`effect/Schema`). */
88
+ const checkable = (path: string): boolean =>
89
+ KNOWN_EXTENSION.test(path) || path.startsWith(".") || topLevel.has(path.split("/")[0] ?? "");
90
+
91
+ const checkCommon = (file: string, line: number, text: string) => {
92
+ if (SECTION_CITATION.test(text))
93
+ violations.push(
94
+ violation(
95
+ "section-citation",
96
+ file,
97
+ line,
98
+ "cites a `§N` section. Cite something a check keeps true: a path, a test or a D-slug.",
99
+ ),
100
+ );
101
+ for (const { regex, reason } of forbidden)
102
+ if (regex.test(text))
103
+ violations.push(violation("forbidden", file, line, `matches /${regex.source}/: ${reason}`));
104
+ for (const match of text.matchAll(DECISION_REF))
105
+ if (SLUG.test(match[0]) && !decisions.has(match[0]))
106
+ violations.push(
107
+ violation(
108
+ "unknown-decision",
109
+ file,
110
+ line,
111
+ `'${match[0]}' is not an entry in DECISIONS.md`,
112
+ ),
113
+ );
114
+ };
115
+
116
+ for (const doc of snapshot.files) {
117
+ if (!doc.endsWith(".md") || !matchesAny(doc, config.refs.docs)) continue;
118
+ const text = snapshot.texts.get(doc);
119
+ if (text === undefined) continue;
120
+ const normative = !matchesAny(doc, config.refs.narrativeDocs);
121
+ stripFences(text)
122
+ .split("\n")
123
+ .forEach((line, i) => {
124
+ const n = i + 1;
125
+ checkCommon(doc, n, line);
126
+ // Lines are read one at a time, so a span split across two is never checked. A line
127
+ // indented four spaces may be an indented code block, where a backtick is literal.
128
+ if (!/^( {4}|\t)/.test(line) && opensCodeSpan(line))
129
+ violations.push(
130
+ violation(
131
+ "split-code-span",
132
+ doc,
133
+ n,
134
+ "a code span crosses a line break, so the refs check can't see it: keep each `...` span on one line.",
135
+ ),
136
+ );
137
+ if (
138
+ normative &&
139
+ NON_NORMATIVE.test(line.replace(/`[^`]*`/g, (span) => span.replaceAll("`", " ")))
140
+ )
141
+ violations.push(
142
+ violation(
143
+ "normative-link",
144
+ doc,
145
+ n,
146
+ "a normative doc points into notes/, plan/ or a handoff, which age by design. Promote what matters into a check, test or decision.",
147
+ ),
148
+ );
149
+ for (const match of line.matchAll(/`([^`\n]+)`/g)) {
150
+ const span = match[1] ?? "";
151
+ const script = /^bun run (?:--?[\w-]+ )*([\w:./-]+)/.exec(span)?.[1];
152
+ // Flags such as `--silent` come before the script.
153
+ // `bun run path/to/file.ts` runs a file, which the path check below covers.
154
+ if (script !== undefined && !script.includes("/") && !KNOWN_EXTENSION.test(script)) {
155
+ if (!snapshot.packageScripts.has(script))
156
+ violations.push(
157
+ violation(
158
+ "unknown-script",
159
+ doc,
160
+ n,
161
+ `\`bun run ${script}\` is not a package.json script`,
162
+ ),
163
+ );
164
+ continue;
165
+ }
166
+ const path = pathCandidate(span.replace(/^bun (run )?/, ""));
167
+ if (path !== undefined && checkable(path) && !pathExists(doc, path))
168
+ violations.push(violation("missing-path", doc, n, `\`${span}\` does not exist`));
169
+ }
170
+ for (const match of line.matchAll(/\]\(([^)\s]+)\)/g)) {
171
+ const target = (match[1] ?? "").split("#")[0] ?? "";
172
+ if (target === "" || /^[a-z]+:/.test(target)) continue;
173
+ if (!pathExists(doc, target))
174
+ violations.push(
175
+ violation("missing-path", doc, n, `link target '${target}' does not exist`),
176
+ );
177
+ }
178
+ });
179
+ }
180
+
181
+ for (const file of snapshot.files) {
182
+ if (!isTsSource(file)) continue;
183
+ const text = snapshot.texts.get(file);
184
+ if (text === undefined) continue;
185
+ for (const comment of parse(file, text).comments) {
186
+ const line = lineAt(text, comment.start);
187
+ checkCommon(file, line, comment.value);
188
+ if (NON_NORMATIVE.test(comment.value))
189
+ violations.push(
190
+ violation(
191
+ "normative-link",
192
+ file,
193
+ line,
194
+ "code points into notes/, plan/ or a handoff, which age by design. State the reason here, or cite a test or D-slug.",
195
+ ),
196
+ );
197
+ if (beads !== undefined)
198
+ for (const match of comment.value.matchAll(BEAD_CANDIDATE)) {
199
+ if (!beads.has(match[0])) continue;
200
+ const before = comment.value.slice(0, match.index).trimEnd();
201
+ if (!before.endsWith("TODO("))
202
+ violations.push(
203
+ violation(
204
+ "bead-in-code",
205
+ file,
206
+ line,
207
+ `cites bead '${match[0]}'. Beads change and close; only \`TODO(${match[0]})\` may name one.`,
208
+ ),
209
+ );
210
+ }
211
+ }
212
+ }
213
+ return violations;
214
+ };
@@ -0,0 +1,67 @@
1
+ /** Text output for the CLI. Violations sort by file and line so diffs between runs are stable. */
2
+ import type { Metrics } from "./budgets.ts";
3
+ import type { Violation } from "./model.ts";
4
+ import type { RatchetResult } from "./ratchet.ts";
5
+
6
+ /** Location and rule on one line (grep-able), the message indented below it (readable). */
7
+ export const formatViolation = (v: Violation): string =>
8
+ `${v.file}${v.line === undefined ? "" : `:${v.line}`} ${v.rule}\n ${v.message}`;
9
+
10
+ const plural = (n: number, word: string): string => `${n} ${word}${n === 1 ? "" : "s"}`;
11
+
12
+ const byLocation = (a: Violation, b: Violation): number =>
13
+ a.file.localeCompare(b.file) || (a.line ?? 0) - (b.line ?? 0) || a.rule.localeCompare(b.rule);
14
+
15
+ export const formatCheck = (result: RatchetResult): string => {
16
+ const entries = [...result.failing].sort(byLocation).map(formatViolation);
17
+ for (const l of result.loose)
18
+ entries.push(
19
+ `${l.file} ${l.rule}\n ratchet is loose: baseline allows ${l.allowed}, found ${l.found}. Run \`mshape baseline --tighten\`.`,
20
+ );
21
+ const problems = result.failing.length + result.loose.length;
22
+ const suffix =
23
+ result.grandfathered > 0 ? `, ${result.grandfathered} grandfathered by the baseline` : "";
24
+ const summary =
25
+ problems === 0
26
+ ? `mshape check passed${suffix}`
27
+ : `mshape check failed: ${plural(problems, "problem")}${suffix}`;
28
+ return [...entries, summary].join("\n\n");
29
+ };
30
+
31
+ export interface GardenReport {
32
+ readonly metrics: Metrics;
33
+ readonly budgets: {
34
+ readonly agentsLines: number;
35
+ readonly readmeLines: number;
36
+ readonly decisions: number;
37
+ readonly memories: number;
38
+ readonly memoryBytes: number;
39
+ };
40
+ readonly escapeHatches: {
41
+ readonly shapeIgnores: number;
42
+ readonly biomeIgnores: number;
43
+ readonly allowances: number;
44
+ };
45
+ readonly ratcheted: number;
46
+ }
47
+
48
+ const row = (label: string, value: number | undefined, cap?: number): string =>
49
+ ` ${label.padEnd(28)}${value === undefined ? "n/a" : String(value)}${cap === undefined ? "" : ` / ${cap}`}`;
50
+
51
+ export const formatGarden = (g: GardenReport): string =>
52
+ [
53
+ "Budgets",
54
+ row("AGENTS.md lines", g.metrics.agentsLines, g.budgets.agentsLines),
55
+ row("README.md lines", g.metrics.readmeLines, g.budgets.readmeLines),
56
+ row("decisions", g.metrics.decisions, g.budgets.decisions),
57
+ row(" policy-only", g.metrics.policyOnlyDecisions),
58
+ row("bd memories", g.metrics.memories, g.budgets.memories),
59
+ row("bd memory bytes", g.metrics.memoryBytes, g.budgets.memoryBytes),
60
+ "Escape hatches (review any growth)",
61
+ row("shape-ignore comments", g.escapeHatches.shapeIgnores),
62
+ row("biome-ignore comments", g.escapeHatches.biomeIgnores),
63
+ row("config allowances", g.escapeHatches.allowances),
64
+ row("ratcheted violations", g.ratcheted),
65
+ `Large files (${g.metrics.largeFiles.length})`,
66
+ ...g.metrics.largeFiles.slice(0, 15).map((f) => ` ${String(f.lines).padStart(6)} ${f.file}`),
67
+ ].join("\n");
@@ -0,0 +1,50 @@
1
+ /** Small AST helpers shared by the rules. */
2
+ import type { Expression, ModuleExportName, Program } from "oxc-parser";
3
+
4
+ /** `A.b` for a non-computed member access on an identifier, else undefined. */
5
+ export const memberPath = (
6
+ expression: Expression,
7
+ ): { object: string; property: string } | undefined =>
8
+ expression.type === "MemberExpression" &&
9
+ !expression.computed &&
10
+ expression.object.type === "Identifier" &&
11
+ expression.property.type === "Identifier"
12
+ ? { object: expression.object.name, property: expression.property.name }
13
+ : undefined;
14
+
15
+ const exportName = (name: ModuleExportName): string =>
16
+ name.type === "Literal" ? String(name.value) : name.name;
17
+
18
+ /** What a local name was imported as: `{ source, imported }`, `imported` is `*` for namespaces. */
19
+ export type Bindings = ReadonlyMap<string, { readonly source: string; readonly imported: string }>;
20
+
21
+ export const importBindings = (program: Program): Bindings => {
22
+ const bindings = new Map<string, { source: string; imported: string }>();
23
+ for (const statement of program.body) {
24
+ if (statement.type !== "ImportDeclaration") continue;
25
+ for (const specifier of statement.specifiers) {
26
+ const imported =
27
+ specifier.type === "ImportSpecifier"
28
+ ? exportName(specifier.imported)
29
+ : specifier.type === "ImportNamespaceSpecifier"
30
+ ? "*"
31
+ : "default";
32
+ bindings.set(specifier.local.name, { source: statement.source.value, imported });
33
+ }
34
+ }
35
+ return bindings;
36
+ };
37
+
38
+ /**
39
+ * Whether a local identifier names an Effect module (`Effect`, `Schema`): imported from
40
+ * `effect` by that name, or as the namespace of `effect/<Module>`. Unbound uses of the
41
+ * canonical name also count, since tests and snippets often omit imports.
42
+ */
43
+ export const isEffectModule = (bindings: Bindings, local: string, module: string): boolean => {
44
+ const binding = bindings.get(local);
45
+ if (binding === undefined) return local === module;
46
+ return (
47
+ (binding.source === "effect" && binding.imported === module) ||
48
+ (binding.source === `effect/${module}` && binding.imported === "*")
49
+ );
50
+ };
@@ -0,0 +1,60 @@
1
+ import type { CallExpression, Expression } from "oxc-parser";
2
+ import { importBindings, isEffectModule, memberPath } from "./ast.ts";
3
+ import type { Rule } from "./engine.ts";
4
+
5
+ const DECODERS = new Set([
6
+ "decodeUnknownEffect",
7
+ "decodeEffect",
8
+ "decodeUnknownExit",
9
+ "decodeExit",
10
+ "decodeUnknownOption",
11
+ "decodeOption",
12
+ "decodeUnknownResult",
13
+ "decodeResult",
14
+ "decodeUnknownPromise",
15
+ "decodePromise",
16
+ "decodeUnknownSync",
17
+ "decodeSync",
18
+ ]);
19
+
20
+ /** `{ ..., onExcessProperty: "error" }` passed where the decoder takes its options. */
21
+ const strictOptions = (call: CallExpression): boolean => {
22
+ const options = call.arguments[1];
23
+ return (
24
+ options?.type === "ObjectExpression" &&
25
+ options.properties.some(
26
+ (property) =>
27
+ property.type === "Property" &&
28
+ property.key.type === "Identifier" &&
29
+ property.key.name === "onExcessProperty" &&
30
+ property.value.type === "Literal" &&
31
+ property.value.value === "error",
32
+ )
33
+ );
34
+ };
35
+
36
+ export const decodeStrict: Rule = {
37
+ id: "decode-strict",
38
+ layer: "core",
39
+ bugClass:
40
+ "Unknown keys silently dropped while decoding, so a misspelt or stale field is ignored.",
41
+ message:
42
+ 'decodes without onExcessProperty: "error". Use decodeStrict from monkeyshape, or pass { errors: "all", onExcessProperty: "error" }.',
43
+ entryExempt: false,
44
+ visit: (parsed, report) => {
45
+ const bindings = importBindings(parsed.program);
46
+ const isDecoder = (callee: Expression): boolean => {
47
+ const member = memberPath(callee);
48
+ if (member !== undefined)
49
+ return DECODERS.has(member.property) && isEffectModule(bindings, member.object, "Schema");
50
+ if (callee.type !== "Identifier") return false;
51
+ const binding = bindings.get(callee.name);
52
+ return binding?.source === "effect/Schema" && DECODERS.has(binding.imported);
53
+ };
54
+ return {
55
+ CallExpression: (node) => {
56
+ if (isDecoder(node.callee) && !strictOptions(node)) report({ offset: node.start });
57
+ },
58
+ };
59
+ },
60
+ };
@@ -0,0 +1,33 @@
1
+ import { importBindings, isEffectModule, memberPath } from "./ast.ts";
2
+ import type { Rule } from "./engine.ts";
3
+
4
+ const RUNNERS = new Set([
5
+ "runPromise",
6
+ "runPromiseExit",
7
+ "runSync",
8
+ "runSyncExit",
9
+ "runFork",
10
+ "runCallback",
11
+ ]);
12
+
13
+ export const effectRunAtEdge: Rule = {
14
+ id: "effect-run-at-edge",
15
+ layer: "core",
16
+ bugClass: "Nested runtimes that lose interruption, context and the typed error channel.",
17
+ message:
18
+ "runs an effect outside a composition root. Return the Effect and let the entry point (an `entry` file) run it.",
19
+ entryExempt: true,
20
+ visit: (parsed, report) => {
21
+ const bindings = importBindings(parsed.program);
22
+ return {
23
+ CallExpression: (node) => {
24
+ const member = memberPath(node.callee);
25
+ if (member === undefined) return;
26
+ const runner =
27
+ RUNNERS.has(member.property) && isEffectModule(bindings, member.object, "Effect");
28
+ const main = member.property === "runMain" && member.object.endsWith("Runtime");
29
+ if (runner || main) report({ offset: node.start });
30
+ },
31
+ };
32
+ },
33
+ };