@ultimat3/cli 30.6.0 → 30.8.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.
- package/CLAUDE.md +2 -1
- package/package.json +28 -28
- package/src/cmd-exercise.ts +13 -2
- package/src/cmd-generate.ts +15 -2
- package/src/cmd-new.ts +4 -2
- package/src/error-codes.ts +2 -0
- package/src/exercise-entry-edit.ts +169 -0
- package/src/exercise-findings.ts +74 -4
- package/src/exercise-registration.ts +10 -14
- package/src/exercise-subject.ts +9 -2
- package/src/generate-exercise.ts +77 -0
- package/src/generate-follow-ups.ts +16 -3
- package/src/mcp-errors.ts +2 -0
- package/src/messages.ts +2 -0
- package/src/templates/action-exercise.ts +71 -0
- package/src/templates/action-tests.ts +10 -34
- package/src/templates/action.ts +8 -3
- package/src/templates/naming.ts +7 -0
- package/src/templates/resource-create.ts +10 -4
- package/src/templates/scaffold-auth.ts +17 -1
- package/src/templates/scaffold-exercise.ts +2 -1
- package/wiki/Actions.md +1 -1
- package/wiki/CLI-Reference.md +1 -1
- package/wiki/Policies-And-Authz.md +3 -2
- package/wiki/Testing.md +50 -26
- package/wiki/Tutorial-02-First-Feature.md +3 -3
- package/wiki/Tutorial-03-Auth-And-Admin.md +1 -1
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// `x g`'s half of the one exercise declaration: each written contract test's entry inserted into
|
|
2
|
+
// `apps/web/exercise.ts` (created from `x new`'s shape when the app has none), since the test reads
|
|
3
|
+
// it from there. A file the editor cannot read is `X_EXERCISE_FILE_UNEDITABLE`, the entry in its fix.
|
|
4
|
+
|
|
5
|
+
import { UltimateError } from '@ultimat3/core';
|
|
6
|
+
import type { ExerciseEntry } from './exercise-entry-edit';
|
|
7
|
+
import { editExerciseFile } from './exercise-entry-edit';
|
|
8
|
+
import { EXERCISE_FILE } from './exercise-registration';
|
|
9
|
+
import type { GenerateDisk } from './generate-disk';
|
|
10
|
+
import type { Finding } from './output';
|
|
11
|
+
import type { GeneratedFile } from './templates';
|
|
12
|
+
|
|
13
|
+
/** The entries the files this run WROTE carry — a skipped or conflicting file is owed none. */
|
|
14
|
+
export const writtenExercises = (
|
|
15
|
+
files: readonly GeneratedFile[],
|
|
16
|
+
written: readonly string[],
|
|
17
|
+
): readonly ExerciseEntry[] =>
|
|
18
|
+
files.flatMap((file) =>
|
|
19
|
+
'exercise' in file && file.exercise !== undefined && written.includes(file.path)
|
|
20
|
+
? [file.exercise]
|
|
21
|
+
: [],
|
|
22
|
+
);
|
|
23
|
+
|
|
24
|
+
/** One line of an entry: what the fix asks to paste, whitespace folded. */
|
|
25
|
+
const oneLine = (entry: ExerciseEntry): string =>
|
|
26
|
+
`${entry.name}: ${entry.value.replace(/\s*\n\s*/g, ' ').replace(/, }/g, ' }')}`;
|
|
27
|
+
|
|
28
|
+
/** Inserts `entries` into the app's exercise file; answers the path when it changed, or a refusal. */
|
|
29
|
+
export async function declareGeneratedExercises(
|
|
30
|
+
entries: readonly ExerciseEntry[],
|
|
31
|
+
disk: GenerateDisk,
|
|
32
|
+
): Promise<{ readonly edited: readonly string[]; readonly findings: readonly Finding[] }> {
|
|
33
|
+
if (entries.length === 0) return { edited: [], findings: [] };
|
|
34
|
+
const before = await disk.read(EXERCISE_FILE);
|
|
35
|
+
const edit = editExerciseFile(before, entries);
|
|
36
|
+
if (edit.kind === 'refused') {
|
|
37
|
+
return {
|
|
38
|
+
edited: [],
|
|
39
|
+
findings: [
|
|
40
|
+
{
|
|
41
|
+
code: 'X_EXERCISE_FILE_UNEDITABLE',
|
|
42
|
+
cause: `${EXERCISE_FILE} ${edit.reason}, so x g could not declare ${entries.map((e) => e.name).join(', ')} there and its contract test reads no entry`,
|
|
43
|
+
// The code to paste first: a fix is pasted from its first character.
|
|
44
|
+
fix: `${entries.map(oneLine).join(', ')}, # paste inside export const exercise = defineExercise({ … }) in ${EXERCISE_FILE}`,
|
|
45
|
+
at: EXERCISE_FILE,
|
|
46
|
+
},
|
|
47
|
+
],
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
if (edit.kind === 'unchanged' && before !== undefined) return { edited: [], findings: [] };
|
|
51
|
+
await disk.write(EXERCISE_FILE, edit.source);
|
|
52
|
+
return { edited: [EXERCISE_FILE], findings: [] };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* `x new`'s file set with every contract test's entry already in its `apps/web/exercise.ts` — the
|
|
57
|
+
* scaffold writes both at once, so there is no disk to edit. The file is the template's own, so a
|
|
58
|
+
* refusal is this package's defect and is thrown, never written.
|
|
59
|
+
*/
|
|
60
|
+
export function withDeclaredExercises(files: readonly GeneratedFile[]): readonly GeneratedFile[] {
|
|
61
|
+
const entries = writtenExercises(
|
|
62
|
+
files,
|
|
63
|
+
files.map((file) => file.path),
|
|
64
|
+
);
|
|
65
|
+
const at = files.findIndex((file) => file.path === EXERCISE_FILE);
|
|
66
|
+
const file = files[at];
|
|
67
|
+
if (entries.length === 0 || file === undefined || typeof file.contents !== 'string') return files;
|
|
68
|
+
const edit = editExerciseFile(file.contents, entries);
|
|
69
|
+
if (edit.kind === 'refused') {
|
|
70
|
+
throw new UltimateError({
|
|
71
|
+
code: 'X_EXERCISE_FILE_UNEDITABLE',
|
|
72
|
+
cause: `x new's own ${EXERCISE_FILE} ${edit.reason}, so its contract tests would read no entry`,
|
|
73
|
+
fix: 'bun test packages/cli/src/generate-exercise.test.ts # the scaffold template and the editor disagree',
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
return files.map((one, index) => (index === at ? { ...one, contents: edit.source } : one));
|
|
77
|
+
}
|
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
// Everything `x g` edits OUTSIDE the files it creates, in the one order they have to happen: a
|
|
2
2
|
// declared permission granted to a role, a primitive listed in `defineApi`, an entity added to the
|
|
3
|
-
// typed handle, an `--admin` override wired,
|
|
4
|
-
// made selectable. One function over one disk seam, so a real run and a dry run are the same code
|
|
3
|
+
// typed handle, an `--admin` override wired, a contract test's exercise entry declared, each new
|
|
4
|
+
// workspace edge declared, and every catalog made selectable. One function over one disk seam, so a real run and a dry run are the same code
|
|
5
5
|
// — and the dry run's list of touched files is what the run touches, not a second guess at it.
|
|
6
6
|
|
|
7
7
|
import { registerAdminResources } from './admin-registration';
|
|
8
8
|
import { registerGeneratedPrimitives } from './api-registration';
|
|
9
|
+
import type { ExerciseEntry } from './exercise-entry-edit';
|
|
9
10
|
import type { GenerateDisk } from './generate-disk';
|
|
11
|
+
import { declareGeneratedExercises } from './generate-exercise';
|
|
10
12
|
import { ungrantedByGenerator } from './generate-grant-findings';
|
|
11
13
|
import { grantGeneratedPermissions } from './generate-grants';
|
|
12
14
|
import { declareGeneratedImports } from './generated-imports';
|
|
@@ -33,11 +35,15 @@ export async function followUpEdits(
|
|
|
33
35
|
written: readonly string[],
|
|
34
36
|
dbModule: string | undefined,
|
|
35
37
|
disk: GenerateDisk,
|
|
38
|
+
/** The written contract tests' entries, declared in `apps/web/exercise.ts` (`generate-exercise.ts`). */
|
|
39
|
+
exercises: readonly ExerciseEntry[] = [],
|
|
36
40
|
): Promise<FollowUps> {
|
|
37
41
|
const handle = await registerGeneratedEntities(root, written, dbModule, disk);
|
|
38
42
|
const adminWiring = await registerAdminResources(root, written, disk);
|
|
39
43
|
const granted = await grantGeneratedPermissions(root, written, disk);
|
|
40
44
|
const listed = await registerGeneratedPrimitives(root, written, disk);
|
|
45
|
+
// Before the manifests: the entry may bring an import (`userActor`) into the exercise file.
|
|
46
|
+
const exercise = await declareGeneratedExercises(exercises, disk);
|
|
41
47
|
// Last of the manifest writers, because the others add imports too: every sibling workspace a
|
|
42
48
|
// written file imports, declared in the manifest it landed under.
|
|
43
49
|
const imports = await declareGeneratedImports(root, written, disk);
|
|
@@ -53,12 +59,19 @@ export async function followUpEdits(
|
|
|
53
59
|
...new Set([
|
|
54
60
|
...granted,
|
|
55
61
|
...listed,
|
|
62
|
+
...exercise.edited,
|
|
56
63
|
...handle.edited,
|
|
57
64
|
...adminWiring.edited,
|
|
58
65
|
...imports,
|
|
59
66
|
...(indexSync.edited ?? []),
|
|
60
67
|
]),
|
|
61
68
|
].filter((path) => !written.includes(path)),
|
|
62
|
-
findings: [
|
|
69
|
+
findings: [
|
|
70
|
+
...handle.findings,
|
|
71
|
+
...ungranted,
|
|
72
|
+
...adminWiring.findings,
|
|
73
|
+
...exercise.findings,
|
|
74
|
+
...indexSync.findings,
|
|
75
|
+
],
|
|
63
76
|
};
|
|
64
77
|
}
|
package/src/mcp-errors.ts
CHANGED
|
@@ -392,6 +392,8 @@ const CLI_FIXES: Readonly<Record<CliErrorCode, string>> = {
|
|
|
392
392
|
'x verify --only boundaries --json # names the file; end its mount() with return render(() => <Island {...props} />, el)',
|
|
393
393
|
X_SOCKET_HAND_ROLLED:
|
|
394
394
|
'x verify --only boundaries --json — names the file and line; delete the upgrade and declare the socket with deviceSocket({ path, resolveToken, onFrame }) from @ultimat3/realtime/server',
|
|
395
|
+
X_EXERCISE_FILE_UNEDITABLE:
|
|
396
|
+
'edit apps/web/exercise.ts — paste the entry the finding names into export const exercise = defineExercise({ … })',
|
|
395
397
|
};
|
|
396
398
|
|
|
397
399
|
const isCliCode = (code: string): code is CliErrorCode =>
|
package/src/messages.ts
CHANGED
|
@@ -103,6 +103,8 @@ const CATALOG = {
|
|
|
103
103
|
'cli.exercise.none': 'this app registers no action, query or job: nothing to exercise',
|
|
104
104
|
'cli.exercise.summary':
|
|
105
105
|
'{total} primitive(s): {reached} reached, {refused} refused, {off} off, {unreached} unreached — {file}',
|
|
106
|
+
'cli.exercise.phases': 'took {total} ms — {phases} — slowest: {slowest}',
|
|
107
|
+
'cli.exercise.slowest': 'slowest: {primitive} · {proof} {ms} ms',
|
|
106
108
|
// One rendering of "this file was written", for every command that writes files — `x g`, its
|
|
107
109
|
// own `--dry-run`, and `x new`. Three copies of the same two characters is how a fourth writer
|
|
108
110
|
// arrives with a fifth marker; `--json` carries the paths themselves in `data.files`.
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// A generated action's ONE exercise declaration: its entry in `apps/web/exercise.ts`, which `x g`
|
|
2
|
+
// inserts (`exercise-entry-edit.ts`) and both runners read — the contract test hands that file's
|
|
3
|
+
// export to `.contract({ exercise })`, and `x exercise` re-homes the actor into each tenant it seeds.
|
|
4
|
+
|
|
5
|
+
import type { ExerciseEntry } from '../exercise-entry-edit';
|
|
6
|
+
|
|
7
|
+
const ORG = '00000000-0000-4000-8000-000000000002';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* `../../../exercise` from a directory under the app root (`apps/web/app/post/actions`). Counted
|
|
11
|
+
* off the shared `apps/web/` prefix, which every generated surface sits under.
|
|
12
|
+
*/
|
|
13
|
+
export function exerciseImportFrom(dir: string): string {
|
|
14
|
+
const prefix = 'apps/web/';
|
|
15
|
+
const depth = dir.startsWith(prefix) ? dir.slice(prefix.length).split('/').length : 0;
|
|
16
|
+
return depth === 0 ? './exercise' : `${'../'.repeat(depth)}exercise`;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** The import line a contract test reads the declarations with. */
|
|
20
|
+
export const exerciseImportLine = (dir: string): string =>
|
|
21
|
+
`import { exercise } from '${exerciseImportFrom(dir)}';`;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Who the generated-input runs act as: a member holding the slice's grant, in the org every draw
|
|
25
|
+
* is bound to when the policy compares orgs. A grant that cannot be read is the author's to name,
|
|
26
|
+
* so the entry turns the exercise off and says what to write instead. Printed expanded at every
|
|
27
|
+
* level, the shape Biome keeps for an object written over several lines.
|
|
28
|
+
*/
|
|
29
|
+
export function actionExerciseEntry(
|
|
30
|
+
name: string,
|
|
31
|
+
grant: string | undefined,
|
|
32
|
+
orgRule: boolean,
|
|
33
|
+
feature: string,
|
|
34
|
+
): ExerciseEntry {
|
|
35
|
+
if (grant === undefined) {
|
|
36
|
+
return {
|
|
37
|
+
name,
|
|
38
|
+
value: `{\n off: '${feature}/policy.ts names no one grant: give { actor } holding what it checks',\n}`,
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
return memberEntry(name, grant, orgRule ? { org: ORG, bindsInput: true } : {});
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* A member holding `grant`; in `org` when given, and with every draw's `orgId` bound to it when
|
|
46
|
+
* `bindsInput` — an action whose input names no org (a create that writes under the actor's) gets
|
|
47
|
+
* the actor's org alone.
|
|
48
|
+
*/
|
|
49
|
+
export function memberEntry(
|
|
50
|
+
name: string,
|
|
51
|
+
grant: string,
|
|
52
|
+
where: { readonly org?: string; readonly bindsInput?: boolean },
|
|
53
|
+
): ExerciseEntry {
|
|
54
|
+
const { org } = where;
|
|
55
|
+
const actor = [
|
|
56
|
+
'actor: userActor({',
|
|
57
|
+
" id: 'member',",
|
|
58
|
+
...(org === undefined ? [] : [` orgId: '${org}',`]),
|
|
59
|
+
` permissions: ['${grant}'],`,
|
|
60
|
+
'}),',
|
|
61
|
+
];
|
|
62
|
+
const input =
|
|
63
|
+
org === undefined || where.bindsInput !== true
|
|
64
|
+
? []
|
|
65
|
+
: [`input: (drawn) => ({ ...drawn, orgId: '${org}' }),`];
|
|
66
|
+
return {
|
|
67
|
+
name,
|
|
68
|
+
value: `{\n${[...actor, ...input].map((line) => ` ${line}`).join('\n')}\n}`,
|
|
69
|
+
imports: [{ name: 'userActor', from: '@ultimat3/core' }],
|
|
70
|
+
};
|
|
71
|
+
}
|
|
@@ -44,10 +44,12 @@ const preamble = (
|
|
|
44
44
|
isMutator: boolean,
|
|
45
45
|
wrappers: string,
|
|
46
46
|
outsider: boolean,
|
|
47
|
-
/** `testActor` is imported for the outsider
|
|
47
|
+
/** `testActor` is imported for the outsider. */
|
|
48
48
|
importsActor = outsider,
|
|
49
|
+
/** A contract suite's import of `apps/web/exercise.ts`, the one home of its exercise. */
|
|
50
|
+
exerciseImport?: string,
|
|
49
51
|
): string => `${importsActor ? "import { testActor } from '@ultimat3/policy';\n" : ''}import { ${wrappers} } from '@ultimat3/testing';
|
|
50
|
-
import { ${name.camel} } from './${name.kebab}';
|
|
52
|
+
${exerciseImport === undefined ? '' : `${exerciseImport}\n`}import { ${name.camel} } from './${name.kebab}';
|
|
51
53
|
${
|
|
52
54
|
outsider
|
|
53
55
|
? `
|
|
@@ -233,33 +235,6 @@ unitTest('${name.camel} rejects input that is not a uuid', async () => {
|
|
|
233
235
|
${shape.isMutator ? localTwinTests() : ''}${handlerTests(feature, shape)}`;
|
|
234
236
|
};
|
|
235
237
|
|
|
236
|
-
/**
|
|
237
|
-
* Who the generated-input runs act as: an actor holding the slice's grant — `<feature>:write` for
|
|
238
|
-
* the policy this generator wrote, the one literal `can('<perm>')` of a handwritten one — in the
|
|
239
|
-
* input's org when the rule compares orgs. A grant that cannot be read is the author's to name,
|
|
240
|
-
* so those runs are skipped out loud instead.
|
|
241
|
-
*/
|
|
242
|
-
const exerciseActor = (grant: string | undefined, orgRule: boolean): string =>
|
|
243
|
-
grant === undefined
|
|
244
|
-
? ''
|
|
245
|
-
: `
|
|
246
|
-
// Holds the grant${orgRule ? ', in the org every generated input is bound to' : ''}: the actor the handler runs as when \`.contract()\`
|
|
247
|
-
// calls it with generated legal input.
|
|
248
|
-
const member = testActor('member', {${orgRule ? '\n orgId,' : ''}
|
|
249
|
-
permissions: ['${grant}'],
|
|
250
|
-
}).actor;
|
|
251
|
-
`;
|
|
252
|
-
|
|
253
|
-
/** The `.contract()` argument: the actor and, under an org rule, the org every draw is bound to. */
|
|
254
|
-
const exerciseOption = (grant: string | undefined, orgRule: boolean): string => {
|
|
255
|
-
if (grant === undefined) {
|
|
256
|
-
return "{\n exercise: { off: '../policy.ts names no one grant: pass { actor } holding what it checks' },\n }";
|
|
257
|
-
}
|
|
258
|
-
return orgRule
|
|
259
|
-
? '{\n exercise: { actor: member, input: (drawn) => ({ ...(drawn as object), orgId }) },\n }'
|
|
260
|
-
: '{ exercise: { actor: member } }';
|
|
261
|
-
};
|
|
262
|
-
|
|
263
238
|
export const actionContractTest = (
|
|
264
239
|
name: NameSet,
|
|
265
240
|
feature: NameSet,
|
|
@@ -268,16 +243,17 @@ export const actionContractTest = (
|
|
|
268
243
|
scaffoldPolicy = true,
|
|
269
244
|
/** That policy holds an org rule: false for a slice whose entity names no tenant. */
|
|
270
245
|
orgRule = scaffoldPolicy,
|
|
271
|
-
/** The
|
|
272
|
-
|
|
246
|
+
/** The line importing `apps/web/exercise.ts`'s export, relative to this test (`action-exercise.ts`). */
|
|
247
|
+
exerciseImport = "import { exercise } from '../../../exercise';",
|
|
273
248
|
): string => `// ${name.camel}: the contract every action owes, and the foreign-org actor it denies before the
|
|
274
249
|
// handler runs. One declaration, every surface.
|
|
275
|
-
${preamble(name, feature, isMutator, 'contractTest, expect', orgRule, orgRule
|
|
250
|
+
${preamble(name, feature, isMutator, 'contractTest, expect', orgRule, orgRule, exerciseImport)}
|
|
276
251
|
contractTest('${name.camel} passes the action contract', async () => {
|
|
277
252
|
// Four assertions the framework makes for any action, without knowing what this one does:
|
|
278
253
|
// garbage input is rejected, an anonymous actor is denied, the operation reaches the OpenAPI
|
|
279
|
-
// document, and the handler survives 16 generated legal inputs, each rolled back
|
|
280
|
-
|
|
254
|
+
// document, and the handler survives 16 generated legal inputs, each rolled back — run as its
|
|
255
|
+
// entry in apps/web/exercise.ts declares, the same entry \`x exercise\` runs.
|
|
256
|
+
for (const contract of target.contract({ exercise })) {
|
|
281
257
|
await contract.run();
|
|
282
258
|
}
|
|
283
259
|
});
|
package/src/templates/action.ts
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
// job handle, an MCP tool and these tests; the generator writes the declaration and the tests.
|
|
4
4
|
|
|
5
5
|
import { SlicePolicyIncompleteError } from '../generate-slice-policy';
|
|
6
|
+
import { actionExerciseEntry, exerciseImportLine } from './action-exercise';
|
|
6
7
|
import { actionContractTest, actionUnitTest } from './action-tests';
|
|
7
8
|
import type { FeatureTarget } from './entity';
|
|
8
9
|
import type { GeneratedFile, NameSet } from './naming';
|
|
@@ -194,6 +195,8 @@ export function actionFiles(rawName: string, target: ActionOptions): readonly Ge
|
|
|
194
195
|
: grantOf(target.slicePolicy, `can${feature.pascal}Write`);
|
|
195
196
|
const org =
|
|
196
197
|
!singleTenant || (target.slicePolicy !== undefined && policyReadsOrg(target.slicePolicy));
|
|
198
|
+
// The org rule the contract can rely on: the one this generator's own policy writes.
|
|
199
|
+
const orgRule = target.slicePolicy === undefined && !singleTenant;
|
|
197
200
|
// Before a file is planned: a generated action that does not compile is refused, never written.
|
|
198
201
|
assertPolicyExports(target, feature, isMutator);
|
|
199
202
|
const lookup =
|
|
@@ -247,10 +250,12 @@ export function actionFiles(rawName: string, target: ActionOptions): readonly Ge
|
|
|
247
250
|
feature,
|
|
248
251
|
isMutator,
|
|
249
252
|
target.slicePolicy === undefined,
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
grant,
|
|
253
|
+
orgRule,
|
|
254
|
+
exerciseImportLine(dir),
|
|
253
255
|
),
|
|
256
|
+
// Who its handler runs as, declared once in apps/web/exercise.ts — the file this test reads
|
|
257
|
+
// and `x exercise` reads. A hand-written policy's one literal grant: an actor holding it.
|
|
258
|
+
exercise: actionExerciseEntry(name.camel, grant, orgRule, target.feature),
|
|
254
259
|
},
|
|
255
260
|
];
|
|
256
261
|
}
|
package/src/templates/naming.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
// Name derivation for generators. One place, because `x g resource post` has to agree with itself
|
|
2
2
|
// across eight emitted files — a second casing helper is how `Post`/`post`/`posts` drift apart.
|
|
3
3
|
|
|
4
|
+
import type { ExerciseEntry } from '../exercise-entry-edit';
|
|
5
|
+
|
|
4
6
|
/**
|
|
5
7
|
* A catalog is one file per locale that many generators contribute keys to; a whole-file write
|
|
6
8
|
* would delete every key already in it, so a `'json'` file merges instead of overwriting. Always
|
|
@@ -30,6 +32,11 @@ export interface GeneratedSourceFile {
|
|
|
30
32
|
* then the target's own text: the copy `write-generated.ts` writes where the OS refuses a link.
|
|
31
33
|
*/
|
|
32
34
|
readonly link?: string;
|
|
35
|
+
/**
|
|
36
|
+
* The primitive's entry in `apps/web/exercise.ts`, for the contract test that reads it: the run
|
|
37
|
+
* that writes this file inserts it there (`generate-exercise.ts`), never the file itself.
|
|
38
|
+
*/
|
|
39
|
+
readonly exercise?: ExerciseEntry;
|
|
33
40
|
}
|
|
34
41
|
|
|
35
42
|
/**
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
// input was `{ id, orgId }` while the form posted `{ title }`. The input is the entity's own view of
|
|
4
4
|
// the columns a caller supplies; the org comes from the actor, never from the body.
|
|
5
5
|
|
|
6
|
+
import { exerciseImportLine, memberEntry } from './action-exercise';
|
|
6
7
|
import { sortedImports } from './imports';
|
|
7
8
|
import type { GeneratedFile, NameSet } from './naming';
|
|
8
9
|
import { names } from './naming';
|
|
@@ -119,10 +120,13 @@ unitTest('orgOf answers the org of the actor, and refuses an actor with none', (
|
|
|
119
120
|
|
|
120
121
|
const createContractTest = (
|
|
121
122
|
feature: NameSet,
|
|
123
|
+
/** The line importing `apps/web/exercise.ts`'s export, relative to this test. */
|
|
124
|
+
exerciseImport: string,
|
|
122
125
|
): string => `// create${feature.pascal}: the contract every action owes, and the orgless actor it denies before
|
|
123
126
|
// the handler runs — the org a row is written under is the actor's, so an actor with none is refused.
|
|
124
127
|
import { testActor } from '@ultimat3/policy';
|
|
125
128
|
import { contractTest, expect } from '@ultimat3/testing';
|
|
129
|
+
${exerciseImport}
|
|
126
130
|
import { create${feature.pascal} } from './create-${feature.kebab}';
|
|
127
131
|
|
|
128
132
|
const target = create${feature.pascal}.named('create${feature.pascal}');
|
|
@@ -137,9 +141,9 @@ const writer = testActor('writer', {
|
|
|
137
141
|
}).actor;
|
|
138
142
|
|
|
139
143
|
contractTest('create${feature.pascal} passes the action contract', async () => {
|
|
140
|
-
// The fourth assertion runs the handler
|
|
141
|
-
//
|
|
142
|
-
for (const contract of target.contract({ exercise
|
|
144
|
+
// The fourth assertion runs the handler on 16 generated legal inputs, each inside a transaction
|
|
145
|
+
// that rolls back, as its entry in apps/web/exercise.ts declares — the one \`x exercise\` runs.
|
|
146
|
+
for (const contract of target.contract({ exercise })) await contract.run();
|
|
143
147
|
});
|
|
144
148
|
|
|
145
149
|
contractTest('create${feature.pascal} needs an actor with an org', async () => {
|
|
@@ -167,7 +171,9 @@ export function resourceCreateFiles(
|
|
|
167
171
|
{ path: `${dir}/create-${feature.kebab}.test.ts`, contents: createUnitTest(feature, dbModule) },
|
|
168
172
|
{
|
|
169
173
|
path: `${dir}/create-${feature.kebab}.contract.test.ts`,
|
|
170
|
-
contents: createContractTest(feature),
|
|
174
|
+
contents: createContractTest(feature, exerciseImportLine(dir)),
|
|
175
|
+
// A writer in one org: the create writes under the actor's org, so no input names one.
|
|
176
|
+
exercise: memberEntry(`create${feature.pascal}`, `${feature.kebab}:write`, { org: ORG }),
|
|
171
177
|
},
|
|
172
178
|
];
|
|
173
179
|
}
|
|
@@ -27,6 +27,7 @@ const devActor = (
|
|
|
27
27
|
//
|
|
28
28
|
// Delete it the day sign-in exists, and the fallback line in \`authenticator.ts\` with it.
|
|
29
29
|
import { type Actor, logger, readCookie } from '@ultimat3/core';
|
|
30
|
+
import { seedId } from '@ultimat3/entity';
|
|
30
31
|
import { DEMO_ORG_ID } from '../../shared/demo-org';
|
|
31
32
|
import { roles } from '../../shared/roles';
|
|
32
33
|
|
|
@@ -56,13 +57,20 @@ export const devRoleFrom = (cookieHeader: string | null): string | undefined =>
|
|
|
56
57
|
return Object.hasOwn(roles, named) ? named : undefined;
|
|
57
58
|
};
|
|
58
59
|
|
|
60
|
+
/**
|
|
61
|
+
* The viewer's user id for \`role\`: a uuid, as \`ctx.actor.id\` is on every real request (an
|
|
62
|
+
* \`x_users\` key) — a name here was \`22P02 invalid input syntax for type uuid\` the first time a
|
|
63
|
+
* handler looked its caller up. \`seedId\`, so a seed's id('user:dev:<role>') is this very user.
|
|
64
|
+
*/
|
|
65
|
+
export const devActorId = (role: string): string => seedId(\`user:dev:\${role}\`);
|
|
66
|
+
|
|
59
67
|
/**
|
|
60
68
|
* \`roles\`, never a permission list: \`can()\` expands the role map at decision time, so a grant
|
|
61
69
|
* moved between roles reaches this actor without an edit here.
|
|
62
70
|
*/
|
|
63
71
|
export const devActorFor = (role: string): Actor => ({
|
|
64
72
|
kind: 'user',
|
|
65
|
-
id:
|
|
73
|
+
id: devActorId(role),
|
|
66
74
|
// The seed's org, never an invented string: a generated tenant policy compares it with a uuid.
|
|
67
75
|
orgId: DEMO_ORG_ID,
|
|
68
76
|
roles: [role],
|
|
@@ -230,6 +238,14 @@ unitTest('a cookie naming an undeclared role is never the default viewer', () =>
|
|
|
230
238
|
}
|
|
231
239
|
});
|
|
232
240
|
|
|
241
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
|
242
|
+
|
|
243
|
+
unitTest('the viewer is a user: a uuid id, one per role', () => {
|
|
244
|
+
// An app reads \`ctx.actor.id\` as an \`x_users\` key; a name in it fails the uuid cast.
|
|
245
|
+
for (const role of declaredDevRoles()) expect(devActorFor(role).id).toMatch(UUID);
|
|
246
|
+
expect(devActorFor('admin').id).not.toBe(devActorFor('member').id);
|
|
247
|
+
});
|
|
248
|
+
|
|
233
249
|
unitTest('the actor it mints holds what the role map grants it, and nothing else', () => {
|
|
234
250
|
// \`actorHas\` and not \`holds\`: this is the function \`can()\` itself calls, so the assertion is
|
|
235
251
|
// the pipeline's own decision rather than a second implementation of it. The map is passed
|
|
@@ -7,7 +7,8 @@ const exercise =
|
|
|
7
7
|
(): string => `// What \`x exercise\` cannot guess about this app: an input a primitive needs bound to a real
|
|
8
8
|
// row, an actor its policy permits, or a primitive that must not run in the pass and why. Empty
|
|
9
9
|
// runs every action, query and job as generated. \`x exercise --json\` prints the entry to paste
|
|
10
|
-
// for each one it could not reach
|
|
10
|
+
// for each one it could not reach. A contract test reads the same entry:
|
|
11
|
+
// \`target.contract({ exercise })\`, handed this file's export.
|
|
11
12
|
import { defineExercise } from '@ultimat3/testing';
|
|
12
13
|
|
|
13
14
|
export const exercise = defineExercise({});
|
package/wiki/Actions.md
CHANGED
|
@@ -144,7 +144,7 @@ Every projection needs the name `registerActions()` stamps on. It names the expo
|
|
|
144
144
|
| 3 | **Typed client function** | `input` + `output` | one map-wide client, `export const client = rpc<Api['actions']>({ baseUrl })`, then `await client.publishPost({ postId })` in `app/`; or `publishPost.client({ baseUrl })` for a single method. `rpc` is the only name for the map-wide client — no `createClient` alias, no fetch, no codegen step to remember. `x new` writes it as `apps/web/shared/browser-client.ts` (`browserClient`, beside `browserQueries`); it typechecks at any app size (pinned at 300 actions in 100 modules). **`rpc` and `queryClient` do not reach a mount**: under `baseUrl: '…/v1'` they derive `/v1/api/…` and a valid token answers 404. A machine caller uses the mount's OpenAPI document |
|
|
145
145
|
| 4 | **Job handle** | the whole declaration | `publishPost.job()` — a namespaced name, an `idempotencyKey` from the payload, and an `invoke` that runs the same handler durably. Register it with the queue; `.enqueue()` belongs to a declared `job` |
|
|
146
146
|
| 5 | **MCP tool** | `mcp` + `input` + `policy` | `toolFrom(publishPost)` from `@ultimat3/mcp` — one tool named `publishPost` per exposed action, exactly the `tools/list` entry, JSON Schema from `input`, every call through this action's `invoke` (authz unchanged) |
|
|
147
|
-
| 6 | **Test** | `input` + `policy` + `handle` | `publishPost.contract({ exercise
|
|
147
|
+
| 6 | **Test** | `input` + `policy` + `handle` | `publishPost.contract({ exercise })`, handed `apps/web/exercise.ts`'s export, where `x g` declares its entry — schema round-trip, a denial test per policy branch, and the handler on generated legal input, generated green, not as a `TODO` |
|
|
148
148
|
|
|
149
149
|
**A client for code that cannot import the app.** `rpc` needs the app's action types, so a customer's TypeScript never had one. `x client customer --out <dir>` compiles the committed `openapi.json` (or a bearer mount's own document, `--mount /v1`) into `index.ts` + `types.ts` with no import beyond the platform: `createClient({ baseUrl, headers })`, one method per `operationId`, a non-2xx as `ProblemError`, and `refusalOf(error, 'publishPost')` narrowing to the codes that operation declares under `errors:`. The calling direction is `x client vendor <name>` — `outbound()` and `t` schemas from a third party's document. One compiler for both, never a second way: [CLI reference](CLI-Reference#x-client). `As of 2026-11`.
|
|
150
150
|
|
package/wiki/CLI-Reference.md
CHANGED
|
@@ -356,7 +356,7 @@ is a word (`a-z`, `0-9`, `-`, `_`) or `[param]` / `[...rest]`; `..`, `.` and emp
|
|
|
356
356
|
| `--force` | boolean | `false` | overwrite existing files |
|
|
357
357
|
| `--dry-run` | boolean | `false` | the write plan, nothing written: **every file the run would touch** — the ones it creates (a slice module already on disk is skipped, not listed) and, `As of 27.6.2`, the ones it EDITS outside the slice (role map, typed handle, API index, manifests, catalogs, the i18n index), in the order the run lists them. `--json`: `data.files` is that list, `data.edits` the subset that already exists, `data.refreshes` the committed contracts (`x.manifest.json`, `openapi.json`) a real run re-projects. `ok: false` with every finding the real run would report — an existing file, an API-index binding already held, a grant or a handle entry it cannot place |
|
|
358
358
|
|
|
359
|
-
`resource` emits the whole slice — `entity`, `repo`, `policy`, `errors`, `service`, `actions`, `live`, `jobs`, `ui`, the form island, the plural route and a test beside each declaration — **
|
|
359
|
+
`resource` emits the whole slice — `entity`, `repo`, `policy`, `errors`, `service`, `actions`, `live`, `jobs`, `ui`, the form island, the plural route and a test beside each declaration — **38 files** on a dry run in an app scaffolded with its example slice, 40 on the real run after `bun run setup` (`x.manifest.json` and `openapi.json` re-projected; 41 dry with `--admin`) — and `x g resource` in a `--no-example` app, which also gains two `package.json` edits, writes 40 and 42 files (43 and 45 with `--admin`; `--live` is refused — a resource already ships a live query, and the flag belongs to `x g query`: `X_CLI_BAD_FLAG`, fix `x g query <name>-feed --feature <name> --live`), and **no migration**: `x db gen` is the only writer of `packages/db/migrations`, so a new slice is `x g resource <name>`, then `x db gen "create <table>"`, then `x db migrate`, then `x build --target static && x verify --only budgets` — the four commands the run prints, in that order (`data.next` under `--json`). **The plural route is reachable as written**, `As of 2026-10-01`: its `load` reads the list through the slice's query as the request's actor (no org in the URL), `AsyncRegion` renders ready, empty and refused, the form island is mounted, and the route declares `policy: { permission: '<name>:read' }`. Its `budget.js` is MEASURED on `x new`'s app (58,522 B, Bun 1.4.0) and carries the `measured:` / `why:` comment `bun run budget-raises` reads; an app that charges more to every document — `navigation: { client: [...] }` adds its router — is over it on the printed build, and the raise is that edit. The page sits in `apps/web/shared/shell.tsx` when the app has one. `backfill` emits a `backfill()` declaration with its `source()` and `handle()` to fill in — see [Migrations and backfills](Migrations-And-Backfills). **`x g query` and `x g backfill` read a table and never create one**, `As of 2026-11-02`: both name a slice holding an `entity.ts`, by `--feature <slice>` or by a name that is one, and neither finding it is `X_FEATURE_REQUIRED`, zero files written, its fix the closest slice's `--feature` line or `x g resource <name>`. `x g resource` and `x g entity` are what create a table. Every generator produces code that passes `x verify` unmodified, and writes it through the app's own Biome when the app has one: `node_modules/.bin/biome` over the TypeScript files that run created, best effort, never a failed `x g`. A slice whose `entity.ts` declares another table under its name gets no foundation from `x g action`/`x g mutator`, and `x g query` there is `X_QUERY_SLICE_ENTITY`. A written contract test reads its exercise from `apps/web/exercise.ts` (`target.contract({ exercise })`), and the same run inserts its entry there — once, the file created from `x new`'s when absent, `As of 2026-11-08`; a file that is not one `export const exercise = defineExercise({ … })` is `X_EXERCISE_FILE_UNEDITABLE`, the entry to paste in its `fix:`. Errors: `X_GENERATE_CONFLICT`, `X_DB_HANDLE_UNREGISTERED`, `X_FEATURE_UNKNOWN`, `X_FEATURE_REQUIRED`, `X_QUERY_SLICE_ENTITY`, `X_EXERCISE_FILE_UNEDITABLE`.
|
|
360
360
|
|
|
361
361
|
**A name the templates would mangle is `X_CLI_BAD_FLAG` before anything is planned**, each with a `fix:` that runs: a reserved word or a leading digit; a letter outside ASCII (`Über` → `x g entity uber` — it was dropped to `ber`); an already-plural `resource`/`entity` name (`posts` → `x g resource post` — it became `entity('postses')`); and a name whose type spelling an emitted file also uses as a global or local type (`promise`, `omit`, `partial`, `row` → `x g resource promise-resource`).
|
|
362
362
|
|
|
@@ -168,14 +168,15 @@ gate's `exercise` step, around each primitive's own call: B, then A, then B agai
|
|
|
168
168
|
|
|
169
169
|
```
|
|
170
170
|
X_TENANT_LEAK: another tenant's row reached a call's output or effect
|
|
171
|
-
cause: action readAttachment, called by tenant B with
|
|
172
|
-
fix: x exercise readAttachment --json — then read the row behind output.url through the repository scoped to ctx.actor, never by the input id alone
|
|
171
|
+
cause: action readAttachment, called by tenant B with A's own input before A ran, handed back A's seeded data at output.url: …
|
|
172
|
+
fix: x exercise readAttachment --json — then read the row behind output.url through the repository scoped to ctx.actor, never by the input id alone, nor by an unscoped statement
|
|
173
173
|
```
|
|
174
174
|
|
|
175
175
|
| Not a failure | Why |
|
|
176
176
|
|---|---|
|
|
177
177
|
| `public` | the policy admits an anonymous caller: what it returns, anyone may read. The read half is skipped; a crossed **write** is still red |
|
|
178
178
|
| `public`, as a declared sweep | a job that reads every org on purpose says so with `crossTenant(reason, fn)`, and its input names no org's rows. The proof sees the scope and quotes the reason; the read half is skipped, a crossed **write** is still red. The same scope in an action or a query, or in a job handed A's id, is still `X_TENANT_LEAK` |
|
|
179
|
+
| `public`, as a tenantless job | a job declaring `tenant: 'none'` whose input names none of A's rows — a nightly cleanup across every org, input `{ occurrenceMs }`. No org and no id of B's choosing reaches its run, so B's run is A's run: what it writes it writes for every enqueuer. The **write** half is skipped, the read half kept. Handed one of A's ids it is crossed as ever; an action or a query handed no id still crosses, since B's org runs it |
|
|
179
180
|
| `unproven` | A's own call was not reached (that record is already red as `X_CONTRACT_EXERCISE_UNREACHED`), or a query answered A none of A's rows — B's empty answer then proves nothing |
|
|
180
181
|
|
|
181
182
|
B holds the role A held, minus `tenancy:cross`. **Not checked**: a `route` `load` and a `task`
|