@ultimat3/cli 31.21.0 → 31.22.1

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.
@@ -0,0 +1,214 @@
1
+ // The `repo-await-in-loop` guard `x new` ships, REPORT ONLY: an `await` inside a loop body or an
2
+ // element callback in a `repo.ts` is one round trip per element. The statement ledger sees it only
3
+ // on a path something calls; this reads every repo. A loop under `expectedQueryLoop` is declared.
4
+
5
+ import { guardCode } from './guard';
6
+ import { repoAwaitInLoopTest } from './guard-repo-await-in-loop-test';
7
+ import type { GeneratedFile } from './naming';
8
+
9
+ /** Derived from the guard's name, never a literal: an `X_*` literal here is a FRAMEWORK code. */
10
+ const NAME = 'repo-await-in-loop';
11
+ const CODE = guardCode(NAME);
12
+
13
+ const source =
14
+ (): string => `// repo-await-in-loop: a repo.ts sends one statement for a set, never one per turn of a loop.
15
+ // \`x verify\` discovers every file in \`guards/\` and runs its \`guard\` inside the \`boundaries\`
16
+ // step — nothing registers this file, so nothing can forget to. Delete it to drop the rule.
17
+ //
18
+ // Why: an \`await\` inside a \`for\`/\`while\`/\`do\` body or a \`.forEach\`/\`.map\` callback is one round
19
+ // trip per element. The statement ledger catches it only on a path a test or \`x exercise\` happens
20
+ // to call; this reads every repo.ts. Read: \`{apps,packages}/**/repo{,-*}.ts\`, never a test.
21
+ // Admitted: a loop written inside \`expectedQueryLoop('<why>', fn)\` from \`@ultimat3/db\`, the same
22
+ // declaration the ledger honours. REPORT ONLY (\`severity: 'warning'\`): listed, never red.
23
+
24
+ import type { Finding, Guard } from '@ultimat3/cli';
25
+
26
+ /** The app owns the codes its own conventions raise — this one is named for the guard. */
27
+ const CODE = '${CODE}';
28
+
29
+ export interface RepoFile {
30
+ /** App-root-relative POSIX path, so the finding names the file an author opens. */
31
+ readonly path: string;
32
+ readonly source: string;
33
+ }
34
+
35
+ const isWordChar = (char: string | undefined): boolean => char !== undefined && /[\\w$]/.test(char);
36
+ const isSpace = (char: string | undefined): boolean => char !== undefined && /\\s/.test(char);
37
+
38
+ /**
39
+ * Comments, strings and template text blanked IN PLACE, newlines kept, so a line number still
40
+ * points at the source. A scan by index, never a backtracking pattern.
41
+ */
42
+ export function blank(source: string): string {
43
+ const out = source.split('');
44
+ const clear = (from: number, to: number): void => {
45
+ for (let index = from; index < to && index < out.length; index += 1) {
46
+ if (out[index] !== '\\n') out[index] = ' ';
47
+ }
48
+ };
49
+ let index = 0;
50
+ while (index < source.length) {
51
+ const char = source[index];
52
+ const pair = source.slice(index, index + 2);
53
+ let end = index + 1;
54
+ if (pair === '//') {
55
+ const eol = source.indexOf('\\n', index);
56
+ end = eol === -1 ? source.length : eol;
57
+ clear(index, end);
58
+ } else if (pair === '/*') {
59
+ const close = source.indexOf('*/', index + 2);
60
+ end = close === -1 ? source.length : close + 2;
61
+ clear(index, end);
62
+ } else if (char === "'" || char === '"' || char === '\`') {
63
+ end = index + 1;
64
+ while (end < source.length && source[end] !== char) end += source[end] === '\\\\' ? 2 : 1;
65
+ end += 1;
66
+ clear(index, end);
67
+ }
68
+ index = end;
69
+ }
70
+ return out.join('');
71
+ }
72
+
73
+ const OPENERS = '([{';
74
+ const CLOSERS = ')]}';
75
+
76
+ /** The index of the bracket closing the one at \`open\`; the text's end when it never closes. */
77
+ const closing = (text: string, open: number): number => {
78
+ let depth = 0;
79
+ for (let index = open; index < text.length; index += 1) {
80
+ if (OPENERS.includes(text[index] ?? '')) depth += 1;
81
+ else if (CLOSERS.includes(text[index] ?? '')) {
82
+ depth -= 1;
83
+ if (depth === 0) return index;
84
+ }
85
+ }
86
+ return text.length;
87
+ };
88
+
89
+ const skip = (text: string, from: number): number => {
90
+ let index = from;
91
+ while (isSpace(text[index])) index += 1;
92
+ return index;
93
+ };
94
+
95
+ const before = (text: string, from: number): string | undefined => {
96
+ let index = from - 1;
97
+ while (isSpace(text[index])) index -= 1;
98
+ return text[index];
99
+ };
100
+
101
+ /** Where a brace-less loop body ends: its \`;\`, or the line break, at depth 0. */
102
+ const statementEnd = (text: string, from: number): number => {
103
+ let depth = 0;
104
+ for (let index = from; index < text.length; index += 1) {
105
+ const char = text[index] ?? '';
106
+ if (OPENERS.includes(char)) depth += 1;
107
+ else if (CLOSERS.includes(char)) depth -= 1;
108
+ if (depth < 0 || (depth === 0 && (char === ';' || char === '\\n'))) return index;
109
+ }
110
+ return text.length;
111
+ };
112
+
113
+ interface Span {
114
+ readonly start: number;
115
+ readonly end: number;
116
+ /** Where the loop's keyword or method name stands: what the finding names. */
117
+ readonly at: number;
118
+ readonly kind: string;
119
+ }
120
+
121
+ /** A loop body (and a \`while\` condition, run every turn) or an element callback. */
122
+ function loopAt(text: string, word: string, start: number, end: number): Span | undefined {
123
+ const next = skip(text, end);
124
+ if (word === 'forEach' || word === 'map') {
125
+ if (before(text, start) !== '.' || text[next] !== '(') return undefined;
126
+ return { start: next, end: closing(text, next), at: start, kind: \`.\${word}\` };
127
+ }
128
+ if (before(text, start) === '.') return undefined;
129
+ if (word === 'do') {
130
+ return text[next] === '{'
131
+ ? { start: next, end: closing(text, next), at: start, kind: 'do' }
132
+ : undefined;
133
+ }
134
+ if (word !== 'for' && word !== 'while') return undefined;
135
+ let open = next;
136
+ if (word === 'for' && text.startsWith('await', open)) open = skip(text, open + 5);
137
+ if (text[open] !== '(') return undefined;
138
+ const header = closing(text, open);
139
+ const body = skip(text, header + 1);
140
+ const close = text[body] === '{' ? closing(text, body) : statementEnd(text, body);
141
+ // A \`for\` header runs its iterable once; a \`while\` condition runs every turn.
142
+ return { start: word === 'for' ? header : open, end: close, at: start, kind: word };
143
+ }
144
+
145
+ const lineOf = (text: string, index: number): number => text.slice(0, index).split('\\n').length;
146
+
147
+ /** Pure — the caller does the I/O — so the rule is testable without a filesystem. */
148
+ export function awaitsInLoops(files: readonly RepoFile[]): readonly Finding[] {
149
+ const findings: Finding[] = [];
150
+ for (const file of files) {
151
+ const text = blank(file.source);
152
+ const loops: Span[] = [];
153
+ const declared: Span[] = [];
154
+ const awaits: number[] = [];
155
+ let index = 0;
156
+ while (index < text.length) {
157
+ if (!isWordChar(text[index]) || isWordChar(text[index - 1])) {
158
+ index += 1;
159
+ continue;
160
+ }
161
+ let end = index;
162
+ while (isWordChar(text[end])) end += 1;
163
+ const word = text.slice(index, end);
164
+ if (word === 'await' && before(text, index) !== '.') awaits.push(index);
165
+ else if (word === 'expectedQueryLoop' && text[skip(text, end)] === '(') {
166
+ const open = skip(text, end);
167
+ declared.push({ start: open, end: closing(text, open), at: index, kind: word });
168
+ } else {
169
+ const loop = loopAt(text, word, index, end);
170
+ if (loop !== undefined) loops.push(loop);
171
+ }
172
+ index = end;
173
+ }
174
+ const counted = loops.filter(
175
+ (loop) => !declared.some((span) => span.start < loop.at && loop.at < span.end),
176
+ );
177
+ const reported = new Set<Span>();
178
+ for (const at of awaits) {
179
+ const inner = counted
180
+ .filter((loop) => loop.start < at && at < loop.end)
181
+ .sort((a, b) => b.start - a.start)[0];
182
+ if (inner === undefined || reported.has(inner)) continue;
183
+ reported.add(inner);
184
+ const where = \`\${file.path}:\${lineOf(text, at)}\`;
185
+ const loopLine = \`\${file.path}:\${lineOf(text, inner.at)}\`;
186
+ findings.push({
187
+ code: CODE,
188
+ cause: \`\${where} awaits inside the \${inner.kind} at \${loopLine} — one round trip per element, so the statements a call sends grow with the rows it is handed\`,
189
+ fix: \`db.<table>.andWhere('id', 'in', ids).limit(ids.length).all() (or insertAll / updateWhere / deleteWhere) — one statement for the set in place of the \${inner.kind} at \${loopLine}, or expectedQueryLoop('<why one per element is optimal>', fn) from @ultimat3/db around it — then: x verify\`,
190
+ at: where,
191
+ });
192
+ }
193
+ }
194
+ return findings;
195
+ }
196
+
197
+ export const guard: Guard = {
198
+ summary: 'a repo.ts sends one statement for a set, never an await per turn of a loop',
199
+ // REPORT ONLY: findings are warnings on the \`boundaries\` step. Delete this line to enforce it.
200
+ severity: 'warning',
201
+ async check(_root, sources) {
202
+ // The run's ONE read of these files: \`repo-raw-sql\` asks for the same glob, so they share it.
203
+ const repos = await sources.files('{apps,packages}/**/repo{,-*}.ts');
204
+ const read = repos.filter((file) => !file.path.endsWith('.test.ts'));
205
+ return awaitsInLoops(read.map((file) => ({ path: file.path, source: file.text })));
206
+ },
207
+ };
208
+ `;
209
+
210
+ /** `guards/repo-await-in-loop.ts` and its test. No index, no registry — the directory registers it. */
211
+ export const repoAwaitInLoopGuardFiles = (): readonly GeneratedFile[] => [
212
+ { path: `guards/${NAME}.ts`, contents: source() },
213
+ { path: `guards/${NAME}.test.ts`, contents: repoAwaitInLoopTest(CODE) },
214
+ ];
@@ -0,0 +1,56 @@
1
+ // The test `x new` writes beside the `repo-unbounded` guard: the rule's own cases, run in the app.
2
+ // Split from `guard-repo-unbounded.ts` at the file target; the code is handed in, never restated.
3
+
4
+ export const repoUnboundedTest = (
5
+ code: string,
6
+ ): string => `// The rule, driven directly. Failure case first: a guard whose rule silently stopped matching is
7
+ // a green gate over the convention it was written to enforce.
8
+
9
+ import { expect, unitTest } from '@ultimat3/testing';
10
+ import { unboundedReads } from './repo-unbounded';
11
+
12
+ const REPO = 'apps/web/app/posts/repo.ts';
13
+ const repo = (...lines: readonly string[]) => [{ path: REPO, source: lines.join('\\n') }];
14
+
15
+ unitTest('a handle read ending in .all() with no limit is refused at its first line', () => {
16
+ const findings = unboundedReads(
17
+ repo(
18
+ '// the typed handle, imported from this app db package',
19
+ 'export const mine = (orgId: string) =>',
20
+ ' db.posts',
21
+ ' .where({ orgId })',
22
+ " .orderBy('id')",
23
+ ' .all();',
24
+ ),
25
+ );
26
+ expect(findings).toHaveLength(1);
27
+ expect(findings[0]?.code).toBe('${code}');
28
+ expect(findings[0]?.at).toBe(\`\${REPO}:3\`);
29
+ expect(findings[0]?.cause).toContain('reads db.posts with .all()');
30
+ expect(findings[0]?.fix).toStartWith('db.posts….limit(<the most rows this caller needs>).all()');
31
+ });
32
+
33
+ unitTest('a bare table, a tx, ctx.db and an optional chain are the same rule', () => {
34
+ expect(unboundedReads(repo('const all = await db.posts.all();'))).toHaveLength(1);
35
+ expect(unboundedReads(repo('await tx.comments.where({ postId }).all();'))).toHaveLength(1);
36
+ expect(unboundedReads(repo('ctx.db.tags.orderBy("name").all();'))[0]?.cause).toContain('db.tags');
37
+ expect(unboundedReads(repo('db.tags.where({ a })?.all();'))).toHaveLength(1);
38
+ });
39
+
40
+ unitTest('a limit, a one, a why:, Promise.all and a chain off no handle are silent', () => {
41
+ expect(unboundedReads(repo('db.posts.where({ orgId }).limit(limit).all();'))).toEqual([]);
42
+ expect(unboundedReads(repo('db.posts.where({ id }).one();'))).toEqual([]);
43
+ expect(
44
+ unboundedReads(repo('// why: at most the four plans the catalog seeds', 'db.plans.all();')),
45
+ ).toEqual([]);
46
+ expect(unboundedReads(repo('await Promise.all(ids.map((id) => db.posts.byId(id)));'))).toEqual(
47
+ [],
48
+ );
49
+ expect(unboundedReads(repo('query.all();', 'rows.all();'))).toEqual([]);
50
+ });
51
+
52
+ unitTest('a comment and a string naming the shape are not code', () => {
53
+ expect(unboundedReads(repo('// db.posts.all()'))).toEqual([]);
54
+ expect(unboundedReads(repo("const s = 'db.posts.all()';"))).toEqual([]);
55
+ });
56
+ `;
@@ -0,0 +1,197 @@
1
+ // The `repo-unbounded` guard `x new` ships, REPORT ONLY: a handle chain in a `repo.ts` ending in
2
+ // `.all()` with no `.limit(n)` answers the handle's default page and drops the cursor to the rest —
3
+ // neither every row nor a page the caller chose. Pairs with entity's `entity.all.truncated` event.
4
+
5
+ import { guardCode } from './guard';
6
+ import { repoUnboundedTest } from './guard-repo-unbounded-test';
7
+ import type { GeneratedFile } from './naming';
8
+
9
+ /** Derived from the guard's name, never a literal: an `X_*` literal here is a FRAMEWORK code. */
10
+ const NAME = 'repo-unbounded';
11
+ const CODE = guardCode(NAME);
12
+
13
+ const source =
14
+ (): string => `// repo-unbounded: a repo.ts read says how many rows it wants, never a bare \`.all()\`.
15
+ // \`x verify\` discovers every file in \`guards/\` and runs its \`guard\` inside the \`boundaries\`
16
+ // step — nothing registers this file, so nothing can forget to. Delete it to drop the rule.
17
+ //
18
+ // Why: \`.all()\` with no \`.limit(n)\` answers ONE page — the handle's default, 50 rows — and drops
19
+ // the cursor to the rest. The caller holds neither every row nor a page it chose, and learns so
20
+ // only from a missing row. Read: a \`db.<table>…all()\` or \`tx.<table>…all()\` chain with no
21
+ // \`.limit(\`, \`.page(\`, \`.keyset(\` or \`.one(\` in it, in \`{apps,packages}/**/repo{,-*}.ts\`, never a
22
+ // test. Admitted: a \`// why:\` on the chain's first line or the line above it, naming the bound.
23
+ // REPORT ONLY (\`severity: 'warning'\`): its findings list on \`boundaries\`, never fail it.
24
+
25
+ import type { Finding, Guard } from '@ultimat3/cli';
26
+
27
+ /** The app owns the codes its own conventions raise — this one is named for the guard. */
28
+ const CODE = '${CODE}';
29
+
30
+ export interface RepoFile {
31
+ /** App-root-relative POSIX path, so the finding names the file an author opens. */
32
+ readonly path: string;
33
+ readonly source: string;
34
+ }
35
+
36
+ /** The handle's names: the app's \`db\` and the \`tx\` a transaction hands its callback. */
37
+ const HANDLES = new Set(['db', 'tx']);
38
+ /** A call anywhere in the chain that bounds what \`.all()\` answers. */
39
+ const BOUNDS = new Set(['limit', 'page', 'keyset', 'one']);
40
+ const WHY = /\\/\\/\\s*why:/;
41
+
42
+ const isWordChar = (char: string | undefined): boolean => char !== undefined && /[\\w$]/.test(char);
43
+ const isSpace = (char: string | undefined): boolean => char !== undefined && /\\s/.test(char);
44
+
45
+ /**
46
+ * Comments, strings and template text blanked IN PLACE, newlines kept, so a line number still
47
+ * points at the source. A scan by index, never a backtracking pattern.
48
+ */
49
+ export function blank(source: string): string {
50
+ const out = source.split('');
51
+ const clear = (from: number, to: number): void => {
52
+ for (let index = from; index < to && index < out.length; index += 1) {
53
+ if (out[index] !== '\\n') out[index] = ' ';
54
+ }
55
+ };
56
+ let index = 0;
57
+ while (index < source.length) {
58
+ const char = source[index];
59
+ const pair = source.slice(index, index + 2);
60
+ let end = index + 1;
61
+ if (pair === '//') {
62
+ const eol = source.indexOf('\\n', index);
63
+ end = eol === -1 ? source.length : eol;
64
+ clear(index, end);
65
+ } else if (pair === '/*') {
66
+ const close = source.indexOf('*/', index + 2);
67
+ end = close === -1 ? source.length : close + 2;
68
+ clear(index, end);
69
+ } else if (char === "'" || char === '"' || char === '\`') {
70
+ end = index + 1;
71
+ while (end < source.length && source[end] !== char) end += source[end] === '\\\\' ? 2 : 1;
72
+ end += 1;
73
+ clear(index, end);
74
+ }
75
+ index = end;
76
+ }
77
+ return out.join('');
78
+ }
79
+
80
+ const skip = (text: string, from: number): number => {
81
+ let index = from;
82
+ while (isSpace(text[index])) index += 1;
83
+ return index;
84
+ };
85
+
86
+ const back = (text: string, from: number): number => {
87
+ let index = from;
88
+ while (isSpace(text[index])) index -= 1;
89
+ return index;
90
+ };
91
+
92
+ /** The \`(\` opening the \`)\` at \`close\`, read backwards; -1 when it never opens. */
93
+ const opening = (text: string, close: number): number => {
94
+ let depth = 0;
95
+ for (let index = close; index >= 0; index -= 1) {
96
+ const char = text[index] ?? '';
97
+ if (')]}'.includes(char)) depth += 1;
98
+ else if ('([{'.includes(char)) {
99
+ depth -= 1;
100
+ if (depth === 0) return index;
101
+ }
102
+ }
103
+ return -1;
104
+ };
105
+
106
+ interface Link {
107
+ readonly name: string;
108
+ readonly call: boolean;
109
+ readonly start: number;
110
+ }
111
+
112
+ /**
113
+ * The chain \`.all\` hangs off, read backwards from the \`.\` before it to its first name:
114
+ * \`db.posts.where({ … }).orderBy('id')\` is \`orderBy()\`, \`where()\`, \`posts\`, \`db\`. Stops at
115
+ * anything that is not a name or a call — \`(await x).all()\` has no chain to read.
116
+ */
117
+ function chainBefore(text: string, dot: number): readonly Link[] {
118
+ const links: Link[] = [];
119
+ // \`?.\` is the same link as \`.\`: step over the \`?\` too.
120
+ const past = (at: number): number => back(text, text[at - 1] === '?' ? at - 2 : at - 1);
121
+ let index = past(dot);
122
+ while (index >= 0) {
123
+ let call = false;
124
+ if (text[index] === ')') {
125
+ const open = opening(text, index);
126
+ if (open < 0) break;
127
+ call = true;
128
+ index = back(text, open - 1);
129
+ }
130
+ if (!isWordChar(text[index])) break;
131
+ let start = index;
132
+ while (isWordChar(text[start - 1])) start -= 1;
133
+ links.push({ name: text.slice(start, index + 1), call, start });
134
+ const prior = back(text, start - 1);
135
+ if (text[prior] !== '.') break;
136
+ index = past(prior);
137
+ }
138
+ return links;
139
+ }
140
+
141
+ const lineOf = (text: string, index: number): number => text.slice(0, index).split('\\n').length;
142
+
143
+ /** Pure — the caller does the I/O — so the rule is testable without a filesystem. */
144
+ export function unboundedReads(files: readonly RepoFile[]): readonly Finding[] {
145
+ const findings: Finding[] = [];
146
+ for (const file of files) {
147
+ const text = blank(file.source);
148
+ const lines = file.source.split('\\n');
149
+ let from = text.indexOf('all', 0);
150
+ while (from !== -1) {
151
+ const at = from;
152
+ from = text.indexOf('all', at + 3);
153
+ if (isWordChar(text[at - 1]) || isWordChar(text[at + 3])) continue;
154
+ const dot = back(text, at - 1);
155
+ if (text[dot] !== '.') continue;
156
+ // Only the terminal, argument-less \`.all()\`: \`Promise.all(…)\` and \`.all(x)\` are other calls.
157
+ const open = skip(text, at + 3);
158
+ if (text[open] !== '(' || text[skip(text, open + 1)] !== ')') continue;
159
+ const links = chainBefore(text, dot);
160
+ const handle = links.findIndex((link) => !link.call && HANDLES.has(link.name));
161
+ const root = links[handle];
162
+ const table = links[handle - 1];
163
+ if (root === undefined || table === undefined || table.call) continue;
164
+ if (links.some((link) => link.call && BOUNDS.has(link.name))) continue;
165
+ const line = lineOf(text, root.start);
166
+ if (WHY.test(lines[line - 1] ?? '') || WHY.test(lines[line - 2] ?? '')) continue;
167
+ const where = \`\${file.path}:\${line}\`;
168
+ const read = \`\${root.name}.\${table.name}\`;
169
+ findings.push({
170
+ code: CODE,
171
+ cause: \`\${where} reads \${read} with .all() and no .limit(n) — .all() answers its first page, 50 rows, and drops the cursor to the rest, so the caller holds neither every row nor a page it chose\`,
172
+ fix: \`\${read}….limit(<the most rows this caller needs>).all() at \${where} — or .inBatches(size) to walk every row, .page() to hand a cursor on, or a // why: comment on that line naming the bound — then: x verify\`,
173
+ at: where,
174
+ });
175
+ }
176
+ }
177
+ return findings;
178
+ }
179
+
180
+ export const guard: Guard = {
181
+ summary: 'a repo.ts read says how many rows it wants: no .all() without a .limit(n)',
182
+ // REPORT ONLY: findings are warnings on the \`boundaries\` step. Delete this line to enforce it.
183
+ severity: 'warning',
184
+ async check(_root, sources) {
185
+ // The run's ONE read of these files: \`repo-raw-sql\` asks for the same glob, so they share it.
186
+ const repos = await sources.files('{apps,packages}/**/repo{,-*}.ts');
187
+ const read = repos.filter((file) => !file.path.endsWith('.test.ts'));
188
+ return unboundedReads(read.map((file) => ({ path: file.path, source: file.text })));
189
+ },
190
+ };
191
+ `;
192
+
193
+ /** `guards/repo-unbounded.ts` and its test. No index, no registry — the directory registers it. */
194
+ export const repoUnboundedGuardFiles = (): readonly GeneratedFile[] => [
195
+ { path: `guards/${NAME}.ts`, contents: source() },
196
+ { path: `guards/${NAME}.test.ts`, contents: repoUnboundedTest(CODE) },
197
+ ];
@@ -8,7 +8,7 @@ import type { GeneratedFile, NameSet } from './naming';
8
8
  const shape = (app: NameSet): string => `---
9
9
  name: shape
10
10
  description: Use BEFORE writing any code, at the idea stage — turns a product request into the one decision that governs everything after it: which of the eight primitives each piece is, which slice and surface it lives in, and the exact \`bunx x g\` invocations. Read-only; it decides, it never builds. Also use when a request seems to need something the framework does not have.
11
- tools: Read, Glob, Grep, Bash
11
+ tools: Read, Glob, Grep, Bash, mcp__${app.kebab}__*
12
12
  ---
13
13
 
14
14
  You decide **whether and what to build** in ${app.kebab}. You write no code, and you do not edit
@@ -63,7 +63,7 @@ Refused: <anything that fits no primitive, and why>
63
63
  const data = (app: NameSet): string => `---
64
64
  name: data
65
65
  description: Use for anything about what is stored — entity definitions, invariants, indexes, repositories, migrations and seed data in ${app.kebab}. Owns \`packages/db/\` and every \`entity.ts\` and \`repo.ts\`. Not for actions, queries or UI.
66
- tools: Read, Write, Edit, Glob, Grep, Bash
66
+ tools: Read, Write, Edit, Glob, Grep, Bash, mcp__${app.kebab}__*
67
67
  ---
68
68
 
69
69
  You own the data boundary of ${app.kebab}: \`packages/db/\` plus every \`entity.ts\` and \`repo.ts\` in a
@@ -88,7 +88,7 @@ once when you are otherwise done. Never \`bunx x verify\` — that belongs to wh
88
88
  const server = (app: NameSet): string => `---
89
89
  name: server
90
90
  description: Use for server-authoritative behaviour in ${app.kebab} — actions, mutators, queries, jobs, tasks and policies, plus the HTTP surface under \`apps/web/api/\`. Not for entities, migrations or anything that renders.
91
- tools: Read, Write, Edit, Glob, Grep, Bash
91
+ tools: Read, Write, Edit, Glob, Grep, Bash, mcp__${app.kebab}__*
92
92
  ---
93
93
 
94
94
  You own the server boundary of ${app.kebab}: \`policy.ts\`, actions, mutators, queries, jobs and tasks
@@ -115,7 +115,7 @@ once when you are otherwise done. Never \`bunx x verify\` — that belongs to wh
115
115
  const web = (app: NameSet): string => `---
116
116
  name: web
117
117
  description: Use for anything rendered in ${app.kebab} — pages under \`apps/web/site/\` and \`apps/web/app/\`, islands, components in \`packages/ui/\`, styles, tokens and i18n catalogs. Not for actions, queries, entities or migrations.
118
- tools: Read, Write, Edit, Glob, Grep, Bash
118
+ tools: Read, Write, Edit, Glob, Grep, Bash, mcp__${app.kebab}__*
119
119
  ---
120
120
 
121
121
  You own the rendering boundary of ${app.kebab}: \`apps/web/site/\`, the pages and UI of
@@ -0,0 +1,40 @@
1
+ // The one hook `x new` writes: `.claude/hooks/format-edited.ts`, run after every Edit/Write. A
2
+ // Bun script rather than a shell one-liner, because the edited path arrives as JSON on stdin
3
+ // (`tool_input.file_path`) — the harness sets no `$CLAUDE_FILE_PATHS` — and `jq` is not a
4
+ // dependency a fresh app (or a Windows machine) can be assumed to have.
5
+
6
+ import type { GeneratedFile } from './naming';
7
+
8
+ export const HOOK_PATH = '.claude/hooks/format-edited.ts';
9
+
10
+ /** The settings.json command line that runs it, from wherever the session's cwd is. */
11
+ export const HOOK_COMMAND = `bun "$CLAUDE_PROJECT_DIR"/${HOOK_PATH}`;
12
+
13
+ const script = `#!/usr/bin/env bun
14
+ // PostToolUse(Edit|Write): \`biome check --write\` on the one file just edited — it formats in place
15
+ // and reports what it cannot fix. The path arrives on stdin as \`tool_input.file_path\`. Exit 2
16
+ // shows the agent the finding (the edit already landed); a file biome does not handle is a no-op.
17
+
18
+ const input: unknown = JSON.parse((await Bun.stdin.text()) || '{}');
19
+ const record = (typeof input === 'object' && input !== null ? input : {}) as {
20
+ tool_input?: { file_path?: unknown };
21
+ };
22
+ const file = record.tool_input?.file_path;
23
+ if (typeof file === 'string' && file !== '') {
24
+ const proc = Bun.spawnSync(
25
+ ['bunx', 'biome', 'check', '--write', '--no-errors-on-unmatched', file],
26
+ { stdout: 'pipe', stderr: 'pipe', timeout: 15_000 },
27
+ );
28
+ if (proc.exitCode !== 0) {
29
+ const out = \`\${proc.stdout.toString()}\${proc.stderr.toString()}\`.trim();
30
+ process.stderr.write(
31
+ \`\${out.split('\\n').slice(-30).join('\\n')}\\nfix what it names, then: bunx biome check --write \${file}\\n\`,
32
+ );
33
+ process.exit(2);
34
+ }
35
+ }
36
+ `;
37
+
38
+ export function claudeHookFile(): GeneratedFile {
39
+ return { path: HOOK_PATH, contents: script };
40
+ }
@@ -6,6 +6,7 @@
6
6
  import type { GeneratedFile, NameSet } from './naming';
7
7
  import { claudeAgentFiles } from './scaffold-claude-agents';
8
8
  import { claudeCommandFiles } from './scaffold-claude-commands';
9
+ import { claudeHookFile, HOOK_COMMAND, HOOK_PATH } from './scaffold-claude-hook';
9
10
 
10
11
  /**
11
12
  * Read-only commands and the two write commands whose blast radius is a file the gate checks.
@@ -13,6 +14,9 @@ import { claudeCommandFiles } from './scaffold-claude-commands';
13
14
  * Deliberately absent: `x db reset`, `x db backfill --write`, `x secrets`, `x deploy` — each is
14
15
  * destructive or reaches production, and an allowlist that covers them is a prompt nobody reads.
15
16
  *
17
+ * The read-only commands the app's own docs tell an agent to run (`x impact` before every edit,
18
+ * `x graph`, `x affected`, `x exercise`, `x mcp tools`) are here too: a prompt on one is a stall.
19
+ *
16
20
  * The hook is the one part of the bundle that ACTS: `--write` rewrites the file just edited, in
17
21
  * place. JSON takes no comment (the lesson `scaffold-repo.ts`'s `biome.json` already paid for), so
18
22
  * the disclosure lives in `.claude/README.md` under "The hook" — and a test pins it there.
@@ -41,6 +45,13 @@ const settings = (): string => `{
41
45
  "Bash(bunx x i18n check:*)",
42
46
  "Bash(bunx x errors:*)",
43
47
  "Bash(bunx x docs:*)",
48
+ "Bash(bunx x impact:*)",
49
+ "Bash(bunx x graph:*)",
50
+ "Bash(bunx x affected:*)",
51
+ "Bash(bunx x exercise:*)",
52
+ "Bash(bunx x i18n sync:*)",
53
+ "Bash(bunx x fix boundary:*)",
54
+ "Bash(bunx x mcp tools:*)",
44
55
  "Bash(bunx x env check:*)",
45
56
  "Bash(bunx x manifest:*)",
46
57
  "Bash(bunx x db gen:*)",
@@ -54,11 +65,12 @@ const settings = (): string => `{
54
65
  "hooks": {
55
66
  "PostToolUse": [
56
67
  {
57
- "matcher": "Edit|Write",
68
+ "matcher": "Edit|Write|MultiEdit",
58
69
  "hooks": [
59
70
  {
60
71
  "type": "command",
61
- "command": "bunx biome check --no-errors-on-unmatched --write \\"$CLAUDE_FILE_PATHS\\" 2>/dev/null || true"
72
+ "command": "${HOOK_COMMAND.replaceAll('"', '\\"')}",
73
+ "timeout": 20
62
74
  }
63
75
  ]
64
76
  }
@@ -80,6 +92,7 @@ own — see [The hook](#the-hook), and delete the \`hooks\` block if you would r
80
92
  | Path | What it costs | When you pay it |
81
93
  |---|---|---|
82
94
  | \`settings.json\` | nothing in context | read once per session; the hook runs per edit |
95
+ | \`hooks/format-edited.ts\` | nothing in context | runs after each edit, on that one file |
83
96
  | \`commands/*.md\` | nothing until invoked | the file is read when you type \`/<name>\` |
84
97
  | \`agents/*.md\` | one \`description\` line each | the body is read only when that agent is dispatched |
85
98
 
@@ -111,10 +124,12 @@ framework's.
111
124
 
112
125
  ## The hook
113
126
 
114
- One \`PostToolUse\` hook: \`bunx biome check --write\` on the file that was just edited. **\`--write\`
115
- means it rewrites that file in place** — the same safe fixes \`biome check --write .\` would make
116
- repo-wide, but your working tree does change after every agent edit. Scoped to one file, so it costs
117
- milliseconds, and it settles formatting arguments before they reach a diff.
127
+ One \`PostToolUse\` hook, \`${HOOK_PATH}\`: \`bunx biome check --write\` on the file that was just
128
+ edited, named by the JSON the harness sends on stdin. **\`--write\` means it rewrites that file in
129
+ place** — the same safe fixes \`biome check --write .\` would make repo-wide, but your working tree
130
+ does change after every agent edit. Scoped to one file, so it costs milliseconds, and it settles
131
+ formatting arguments before they reach a diff. What biome cannot fix is shown to the agent at once,
132
+ with the command that re-checks the file, instead of surfacing later as a red \`lint\` step.
118
133
 
119
134
  It is not a typecheck, because a *scoped* one does not exist: \`tsc\` needs the project, and even
120
135
  \`bunx x verify --only typecheck\` checks the whole tree — and says \`NOT A GATE RUN\`, because green
@@ -131,6 +146,7 @@ export function claudeFiles(app: NameSet): readonly GeneratedFile[] {
131
146
  return [
132
147
  { path: '.claude/README.md', contents: readme(app) },
133
148
  { path: '.claude/settings.json', contents: settings() },
149
+ claudeHookFile(),
134
150
  ...claudeCommandFiles(app),
135
151
  ...claudeAgentFiles(app),
136
152
  ];
@@ -25,8 +25,7 @@ const conventions = (app: NameSet): string => `# ${app.pascal}
25
25
  Human-authored, short, stable — one file under two names, \`AGENTS.md\` being a symlink to it.
26
26
  Facts live in \`x.manifest.json\`; this file holds only what an agent cannot infer from the code.
27
27
 
28
- Every row below names what refuses it. A rule with nothing in the last column is a rule that does
29
- not exist — five of these had an empty column and were each measured green on \`bunx x verify\`.
28
+ Every row below names what refuses it. A rule with nothing in the last column does not exist.
30
29
 
31
30
  There is no global \`x\`: every command here is \`bunx x …\`, the CLI this app installs.
32
31
 
@@ -43,7 +42,7 @@ queries, jobs, MCP tools, published operations and tests it touches, each with p
43
42
  | One way | generators, not hand-rolled files: \`bunx x g resource\`, \`bunx x g action\`, \`bunx x g route\` | review |
44
43
  | Surfaces | \`site/\` is 0kb JS and may not import \`app/\`; \`shared/\` is a leaf | \`X_BOUNDARY_SITE_TO_APP\` |
45
44
  | Data | routes call actions and queries; only \`repo.ts\` touches the database | \`X_BOUNDARY_ROUTE_TO_DB\` |
46
- | Repos | a \`repo.ts\` reads through the typed handle, never a \`sql\` literal the handle can express | \`guards/repo-raw-sql.ts\` |
45
+ | Repos | a \`repo.ts\` reads through the typed handle, never a \`sql\` literal it can express; reported, not refused: an \`await\` per loop turn outside \`expectedQueryLoop('<why>', fn)\`, a bare \`.all()\` (it stops at 50 rows: say \`.limit(n)\`) | \`guards/repo-raw-sql.ts\`, \`guards/repo-await-in-loop.ts\`, \`guards/repo-unbounded.ts\` |
47
46
  | Fan-out | a database call per element of a list runs through \`mapBounded(rows, fn, { width })\` from \`@ultimat3/core\` — never \`Promise.all(rows.map(async …))\`, one statement per row at once; a \`// why:\` on the line admits a list bounded where it is built | \`guards/unbounded-fanout.ts\` |
48
47
  | Vendors | a server \`fetch(\` carries a \`signal\` in its own options — better, it is \`outbound()\` from \`@ultimat3/core/outbound\`: a deadline, the caller's signal, safe-only retry | \`guards/raw-fetch.ts\` |
49
48
  | Polling | an island re-reads a query on a timer with \`useQuery(ref, input, { poll: pollEvery(ms) })\` (\`@ultimat3/realtime\`), anything else with \`visibleInterval(run, ms)\` from \`@ultimat3/core/page\` — no call while the tab is hidden, none after a lost session — never a bare \`setInterval(\`; a \`// why:\` on the line admits a tick that is not a read | \`guards/raw-interval.ts\` |
@@ -111,10 +110,6 @@ see, and the type already fires — measured, \`price: 19.99\` in a seed is
111
110
  \`TS2322: Type 'number' is not assignable to type 'MoneyInput'\`. A guard that pretended to check
112
111
  it would be worse than the type that really does.
113
112
 
114
- \`bun run verify\` is \`bunx x verify\`, the whole gate: its \`budgets\` step runs
115
- \`bunx x build --target static\` itself when \`.x/build-stats.json\` is missing or older than the
116
- source, so nothing has to be built first.
117
-
118
113
  Commands: \`bun run setup\`, \`bun run dev\`, \`bun run verify\`, \`bunx x g <primitive>\`,
119
114
  \`bunx x g guard <name>\`, \`bunx x db branch create <name>\`, \`bunx x doctor\`. \`setup\` is
120
115
  \`bin/setup.ts\`, a file Bun runs, so all three are the same command in PowerShell, cmd and bash.