@ultimat3/cli 31.20.0 → 31.22.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 (39) hide show
  1. package/CLAUDE.md +1 -1
  2. package/README.md +11 -6
  3. package/package.json +29 -29
  4. package/src/cmd-db.ts +5 -18
  5. package/src/cmd-doctor.ts +8 -3
  6. package/src/cmd-mcp.ts +6 -1
  7. package/src/cmd-verify.ts +19 -15
  8. package/src/db-schema-dump.ts +20 -0
  9. package/src/dev-lock.ts +26 -5
  10. package/src/doctor-guards.ts +27 -12
  11. package/src/drift-store.ts +28 -2
  12. package/src/error-codes-doctor.ts +9 -5
  13. package/src/guards.ts +66 -28
  14. package/src/lint-findings.ts +34 -10
  15. package/src/mcp-agent-host.ts +107 -0
  16. package/src/mcp-errors.ts +4 -0
  17. package/src/mcp-host.ts +23 -1
  18. package/src/mcp-request-statements.ts +129 -0
  19. package/src/mcp-ui.ts +1 -2
  20. package/src/messages.ts +0 -2
  21. package/src/runtime-cache.ts +12 -3
  22. package/src/schema-dump-drift.ts +78 -4
  23. package/src/templates/guard-repo-await-in-loop-test.ts +89 -0
  24. package/src/templates/guard-repo-await-in-loop.ts +214 -0
  25. package/src/templates/guard-repo-unbounded-test.ts +56 -0
  26. package/src/templates/guard-repo-unbounded.ts +197 -0
  27. package/src/templates/scaffold-claude-agents.ts +4 -4
  28. package/src/templates/scaffold-claude-hook.ts +40 -0
  29. package/src/templates/scaffold-claude.ts +22 -6
  30. package/src/templates/scaffold-docs.ts +2 -7
  31. package/src/templates/scaffold-guards.ts +6 -0
  32. package/src/verify-changed.ts +32 -5
  33. package/src/verify-checks.ts +26 -7
  34. package/src/verify-progress.ts +32 -1
  35. package/wiki/CLI-Reference.md +19 -8
  36. package/wiki/MCP-And-AI.md +7 -3
  37. package/wiki/Tutorial-02-First-Feature.md +1 -1
  38. package/wiki/Upgrading.md +7 -0
  39. package/src/retry-memo.ts +0 -37
@@ -1,7 +1,7 @@
1
- // The `drift` step's fourth rail: is the committed schema dump what the migrations produce, does
2
- // it hold what their snapshots record, and does a database loaded from it come back the same? The other three rails read files and open
3
- // nothing; this one replays the migrations on a scratch embedded database, because "what the
4
- // migrations produce" is a fact only a database can state — and so is what a view outputs.
1
+ // The `drift` step's fourth rail: is the committed dump what the migrations produce, does it hold
2
+ // what their snapshots record, and does it load back the same? Only a scratch database can state
3
+ // what migrations produce and what a view outputs. Beside it, with none: an index the dump holds
4
+ // and nothing declares (`X_DB_INDEX_UNDECLARED`), a warning on `main`.
5
5
 
6
6
  // why: Bun has no directory probe — `Bun.file().exists()` answers about a file.
7
7
  import { existsSync } from 'node:fs';
@@ -146,3 +146,77 @@ export async function checkSchemaDump(
146
146
  ...(entities === undefined ? [] : viewColumnFindings(entities, replayed.catalog)),
147
147
  ];
148
148
  }
149
+
150
+ /** One `CREATE [UNIQUE] INDEX name ON [ONLY] schema.table` of `pg_get_indexdef`, quoted only when it must be. */
151
+ const DUMP_INDEX =
152
+ /^CREATE (?:UNIQUE )?INDEX (?:"((?:[^"]|"")+)"|(\S+)) ON (?:ONLY )?(?:"(?:[^"]|"")+"|[^\s."]+)\.(?:"((?:[^"]|"")+)"|(\S+)) /gm;
153
+
154
+ const unquoted = (quoted: string | undefined, bare: string | undefined): string =>
155
+ quoted === undefined ? (bare ?? '') : quoted.replaceAll('""', '"');
156
+
157
+ interface DumpedIndex {
158
+ readonly name: string;
159
+ readonly table: string;
160
+ readonly path: string;
161
+ }
162
+
163
+ /** The app's own: `framework/` holds the tables the framework's migrations own, which it declares. */
164
+ const dumpedIndexes = (committed: readonly SchemaDumpFile[]): readonly DumpedIndex[] =>
165
+ committed
166
+ .filter((file) => file.path.startsWith('05_indexes/'))
167
+ .flatMap((file) =>
168
+ [...file.content.matchAll(DUMP_INDEX)].map((match) => ({
169
+ name: unquoted(match[1], match[2]),
170
+ table: unquoted(match[3], match[4]),
171
+ path: file.path,
172
+ })),
173
+ );
174
+
175
+ const undeclaredIndex = (index: DumpedIndex): Finding => ({
176
+ code: 'X_DB_INDEX_UNDECLARED',
177
+ cause: `the schema dump holds index "${index.name}" on table "${index.table}", which neither the newest migration snapshot nor any entity declares: every write maintains an index nothing asked for`,
178
+ fix: `DROP INDEX CONCURRENTLY IF EXISTS "${index.name}"; # a hand-written migration of its own under ${MIGRATIONS_DIR} with -- transaction: false. Meant to keep it: declare it in the "${index.table}" entity's indexes: [...], then x db gen "<change>"`,
179
+ docs: ERROR_DOCS_URL,
180
+ at: `${SCHEMA_DUMP_DIR}/${index.path}`,
181
+ });
182
+
183
+ /**
184
+ * The dump's own indexes against the newest snapshot and the entities. The replay cannot see this
185
+ * one either: a generated migration that records an index as renamed without dropping the old name
186
+ * replays into a dump holding both, and every snapshot since agrees with the entities. A registry
187
+ * that did not load answers nothing, since "declared by neither" is then not a fact; the entities
188
+ * are only asked for once the snapshot leaves an index unexplained.
189
+ */
190
+ export async function undeclaredIndexFindings(
191
+ root: string,
192
+ declared: DeclaredEntities = appEntities,
193
+ ): Promise<readonly Finding[]> {
194
+ if (!existsSync(join(root, DB_PACKAGE)) || !hasSchemaDump(root)) return [];
195
+ const migrations = await readMigrations(root);
196
+ const snapshot = migrations.findLast((migration) => migration.snapshot !== undefined)?.snapshot;
197
+ const recorded = new Set(
198
+ (snapshot?.tables ?? []).flatMap((table) => table.indexes.map((one) => one.name)),
199
+ );
200
+ const unexplained = dumpedIndexes(await readSchemaDump(root)).filter(
201
+ (index) => !recorded.has(index.name),
202
+ );
203
+ if (unexplained.length === 0) return [];
204
+ const entities = await declared(root);
205
+ if (entities === undefined) return [];
206
+ const named = new Set(entities.flatMap((entity) => entity.indexes.map((one) => one.name)));
207
+ return unexplained.filter((index) => !named.has(index.name)).map(undeclaredIndex);
208
+ }
209
+
210
+ /**
211
+ * What the `drift` step carries on `main`: advice in `StepOutcome.warnings`, never a failed step —
212
+ * a red gate on an app that passed yesterday is X_BREAKING_ON_MAIN. The refusal lands on `next`,
213
+ * where the step reports `undeclaredIndexFindings` as findings.
214
+ */
215
+ export async function undeclaredIndexWarnings(
216
+ root: string,
217
+ declared: DeclaredEntities = appEntities,
218
+ ): Promise<readonly string[]> {
219
+ return (await undeclaredIndexFindings(root, declared)).map(
220
+ (finding) => `${finding.code} ${finding.at}: ${finding.cause} — fix: ${finding.fix}`,
221
+ );
222
+ }
@@ -0,0 +1,89 @@
1
+ // The test `x new` writes beside the `repo-await-in-loop` guard: the rule's own cases, run in the
2
+ // app. Split from `guard-repo-await-in-loop.ts` at the file target; the code is handed in.
3
+
4
+ export const repoAwaitInLoopTest = (
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 { awaitsInLoops } from './repo-await-in-loop';
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('an await in a for body is refused at its line, naming the loop', () => {
16
+ const findings = awaitsInLoops(
17
+ repo(
18
+ 'export const touch = async (ids: string[]) => {',
19
+ ' for (const id of ids) {',
20
+ ' await db.posts.update(id, { seen: true });',
21
+ ' }',
22
+ '};',
23
+ ),
24
+ );
25
+ expect(findings).toHaveLength(1);
26
+ expect(findings[0]?.code).toBe('${code}');
27
+ expect(findings[0]?.at).toBe(\`\${REPO}:3\`);
28
+ expect(findings[0]?.cause).toContain(\`the for at \${REPO}:2\`);
29
+ expect(findings[0]?.fix).toStartWith(
30
+ "db.<table>.andWhere('id', 'in', ids).limit(ids.length).all()",
31
+ );
32
+ });
33
+
34
+ unitTest('a while condition, a do body, a brace-less for and a callback are the same rule', () => {
35
+ expect(awaitsInLoops(repo('while (await db.jobs.claim()) count += 1;'))).toHaveLength(1);
36
+ expect(
37
+ awaitsInLoops(repo('do {', ' row = await db.jobs.next();', '} while (row);')),
38
+ ).toHaveLength(1);
39
+ expect(awaitsInLoops(repo('for (const id of ids) await db.posts.delete(id);'))).toHaveLength(1);
40
+ const each = repo('ids.forEach(async (id) => {', ' await db.posts.delete(id);', '});');
41
+ expect(awaitsInLoops(each)[0]?.cause).toContain('the .forEach at');
42
+ expect(
43
+ awaitsInLoops(repo('rows.map(async (row) => await db.tags.byId(row.tagId));')),
44
+ ).toHaveLength(1);
45
+ });
46
+
47
+ unitTest('one finding per loop, at the innermost loop holding the await', () => {
48
+ const nested = repo(
49
+ 'for (const a of as) {',
50
+ ' for (const b of bs) {',
51
+ ' await db.x.insert({ a, b });',
52
+ ' await db.y.insert({ a, b });',
53
+ ' }',
54
+ '}',
55
+ );
56
+ const findings = awaitsInLoops(nested);
57
+ expect(findings).toHaveLength(1);
58
+ expect(findings[0]?.cause).toContain(\`the for at \${REPO}:2\`);
59
+ });
60
+
61
+ unitTest(
62
+ 'a loop under expectedQueryLoop, an await outside the loop and a for-await header are silent',
63
+ () => {
64
+ const declared = repo(
65
+ "expectedQueryLoop('one indexed lookup per field', async () => {",
66
+ ' for (const f of fields) await db.posts.where({ [f]: term }).limit(5).all();',
67
+ '});',
68
+ );
69
+ expect(awaitsInLoops(declared)).toEqual([]);
70
+ expect(
71
+ awaitsInLoops(
72
+ repo(
73
+ 'const rows = await db.posts.limit(10).all();',
74
+ 'for (const row of rows) total += row.n;',
75
+ ),
76
+ ),
77
+ ).toEqual([]);
78
+ expect(awaitsInLoops(repo('await Promise.all(ids.map((id) => id.trim()));'))).toEqual([]);
79
+ expect(awaitsInLoops(repo('for await (const row of stream) total += row.n;'))).toEqual([]);
80
+ },
81
+ );
82
+
83
+ unitTest('a comment and a string naming the shape are not code', () => {
84
+ expect(awaitsInLoops(repo('// for (const id of ids) await db.x.delete(id);'))).toEqual([]);
85
+ expect(awaitsInLoops(repo("const s = 'for (const id of ids) await db.x.delete(id)';"))).toEqual(
86
+ [],
87
+ );
88
+ });
89
+ `;
@@ -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
+ ];