cvx-kit 0.1.12 → 0.1.14

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 (79) hide show
  1. package/AGENTS.md +47 -0
  2. package/CHANGELOG.md +36 -0
  3. package/README.md +144 -0
  4. package/dist/auth.d.mts +3 -1
  5. package/dist/auth.mjs +1 -1
  6. package/dist/auth.mjs.map +1 -1
  7. package/dist/index.d.mts +5 -2
  8. package/dist/index.mjs +1 -1
  9. package/dist/modules/contracts/binding.d.mts +13 -1
  10. package/dist/modules/contracts/binding.mjs +1 -1
  11. package/dist/modules/contracts/binding.mjs.map +1 -1
  12. package/dist/modules/effect/api-zod.d.mts +1 -1
  13. package/dist/modules/effect/command.d.mts +13 -9
  14. package/dist/modules/effect/command.mjs.map +1 -1
  15. package/dist/modules/effect/domain.d.mts +31 -3
  16. package/dist/modules/effect/domain.mjs.map +1 -1
  17. package/dist/modules/effect/query.d.mts +6 -5
  18. package/dist/modules/effect/query.mjs.map +1 -1
  19. package/dist/modules/foundation/foundation.d.mts +14 -13
  20. package/dist/modules/foundation/foundation.mjs.map +1 -1
  21. package/dist/modules/foundation/operation.d.mts +20 -1
  22. package/dist/modules/foundation/operation.mjs.map +1 -1
  23. package/dist/oxlint/architecture.d.mts +2 -0
  24. package/dist/oxlint/architecture.mjs +1 -1
  25. package/dist/oxlint/architecture.mjs.map +1 -1
  26. package/dist/oxlint/ast.d.mts +10 -1
  27. package/dist/oxlint/ast.mjs +1 -1
  28. package/dist/oxlint/ast.mjs.map +1 -1
  29. package/dist/oxlint.d.mts +1 -1
  30. package/dist/oxlint.mjs +1 -1
  31. package/dist/oxlint.mjs.map +1 -1
  32. package/dist/querying/cursors.d.mts +45 -0
  33. package/dist/querying/cursors.mjs +2 -0
  34. package/dist/querying/cursors.mjs.map +1 -0
  35. package/dist/querying/execution.d.mts +30 -0
  36. package/dist/querying/execution.mjs +2 -0
  37. package/dist/querying/execution.mjs.map +1 -0
  38. package/dist/querying/filters.d.mts +136 -0
  39. package/dist/querying/filters.mjs +2 -0
  40. package/dist/querying/filters.mjs.map +1 -0
  41. package/dist/querying/planner.d.mts +50 -0
  42. package/dist/querying/planner.mjs +2 -0
  43. package/dist/querying/planner.mjs.map +1 -0
  44. package/dist/querying/relationships.d.mts +41 -0
  45. package/dist/querying/relationships.mjs +2 -0
  46. package/dist/querying/relationships.mjs.map +1 -0
  47. package/dist/querying/security.d.mts +107 -0
  48. package/dist/querying/security.mjs +2 -0
  49. package/dist/querying/security.mjs.map +1 -0
  50. package/dist/querying.d.mts +39 -0
  51. package/dist/querying.mjs +2 -0
  52. package/dist/querying.mjs.map +1 -0
  53. package/dist/relations-public.d.mts +2 -0
  54. package/dist/relations-public.mjs +1 -0
  55. package/dist/relations.d.mts +155 -0
  56. package/dist/relations.mjs +2 -0
  57. package/dist/relations.mjs.map +1 -0
  58. package/dist/zod-convex.d.mts +10 -0
  59. package/dist/zod-convex.mjs +2 -0
  60. package/dist/zod-convex.mjs.map +1 -0
  61. package/dist/zod-registration.d.mts +10 -0
  62. package/dist/zod-registration.mjs +2 -0
  63. package/dist/zod-registration.mjs.map +1 -0
  64. package/dist/zod-table.d.mts +63 -8
  65. package/dist/zod-table.mjs +1 -1
  66. package/dist/zod-table.mjs.map +1 -1
  67. package/docs/conventions.md +12 -0
  68. package/docs/domain-contracts.md +42 -9
  69. package/docs/llms.md +15 -5
  70. package/docs/oxlint.md +129 -25
  71. package/docs/querying.md +293 -0
  72. package/docs/zod-table.md +93 -13
  73. package/package.json +11 -1
  74. package/scripts/owned-process.mjs +140 -0
  75. package/scripts/owned-process.test.mjs +107 -0
  76. package/scripts/smoke-packed-querying.mjs +296 -0
  77. package/scripts/test-packed-effect.mjs +10 -1
  78. package/scripts/test-packed-oxlint.mjs +5 -1
  79. package/scripts/test-packed-querying.mjs +185 -0
@@ -0,0 +1,140 @@
1
+ import { spawn } from 'node:child_process'
2
+ import { setTimeout as delay } from 'node:timers/promises'
3
+
4
+ export function processGroupAlive(pid) {
5
+ try {
6
+ process.kill(-pid, 0)
7
+ return true
8
+ } catch (error) {
9
+ if (error.code === 'ESRCH') return false
10
+ throw error
11
+ }
12
+ }
13
+ const owned = new Set()
14
+ export async function cleanupOwnedProcess(pid, graceMs = 1000) {
15
+ if (!owned.has(pid)) throw new Error('Process group is not owned by this runner')
16
+ const signals = [],
17
+ errors = []
18
+ for (const signal of ['SIGINT', 'SIGTERM', 'SIGKILL']) {
19
+ if (!processGroupAlive(pid)) break
20
+ try {
21
+ process.kill(-pid, signal)
22
+ signals.push(signal)
23
+ } catch (error) {
24
+ if (error.code !== 'ESRCH') errors.push({ signal, code: error.code })
25
+ }
26
+ const deadline = performance.now() + graceMs
27
+ while (processGroupAlive(pid) && performance.now() < deadline) await delay(20)
28
+ }
29
+ return { pid, groupId: pid, signals, errors, alive: processGroupAlive(pid) }
30
+ }
31
+
32
+ export async function runOwnedProcess({
33
+ command,
34
+ args,
35
+ cwd,
36
+ env,
37
+ timeoutMs = 180000,
38
+ graceMs = 1000,
39
+ onSpawn = () => {},
40
+ }) {
41
+ const started = performance.now()
42
+ const child = spawn(command, args, { cwd, env, detached: true, stdio: ['pipe', 'pipe', 'pipe'] })
43
+ let stdout = '',
44
+ stderr = '',
45
+ timedOut = false,
46
+ spawnError,
47
+ timeoutCleanup
48
+ child.stdout.on('data', (bytes) => {
49
+ stdout += bytes
50
+ })
51
+ child.stderr.on('data', (bytes) => {
52
+ stderr += bytes
53
+ })
54
+ const closed = new Promise((resolve) => {
55
+ child.once('error', (error) => {
56
+ spawnError = { code: error.code, message: error.message }
57
+ resolve({ code: null, signal: null })
58
+ })
59
+ child.once('close', (code, signal) => resolve({ code, signal }))
60
+ })
61
+ if (child.pid) {
62
+ owned.add(child.pid)
63
+ onSpawn(child.pid)
64
+ }
65
+ child.stdin.end()
66
+ let finishTimeout
67
+ const timeoutFinished = new Promise((resolve) => {
68
+ finishTimeout = resolve
69
+ })
70
+ const timer = setTimeout(() => {
71
+ timedOut = true
72
+ timeoutCleanup = child.pid
73
+ ? cleanupOwnedProcess(child.pid, graceMs).catch((error) => ({
74
+ pid: child.pid,
75
+ alive: true,
76
+ error: { code: error.code, message: error.message },
77
+ }))
78
+ : Promise.resolve(null)
79
+ timeoutCleanup.then(() => finishTimeout({ code: child.exitCode, signal: child.signalCode }))
80
+ }, timeoutMs)
81
+ let exit, cleanup
82
+ try {
83
+ exit = await Promise.race([closed, timeoutFinished])
84
+ if (timeoutCleanup) await timeoutCleanup
85
+ } finally {
86
+ clearTimeout(timer)
87
+ if (child.pid) {
88
+ try {
89
+ cleanup = await cleanupOwnedProcess(child.pid, graceMs)
90
+ } catch (error) {
91
+ cleanup = {
92
+ pid: child.pid,
93
+ alive: true,
94
+ error: { code: error.code, message: error.message },
95
+ }
96
+ }
97
+ }
98
+ }
99
+ if (timedOut) {
100
+ child.stdout.destroy()
101
+ child.stderr.destroy()
102
+ child.unref()
103
+ }
104
+ return {
105
+ ...exit,
106
+ spawnError,
107
+ stdout,
108
+ stderr,
109
+ timedOut,
110
+ pid: child.pid,
111
+ milliseconds: performance.now() - started,
112
+ timeoutCleanup: await timeoutCleanup,
113
+ cleanup,
114
+ }
115
+ }
116
+
117
+ export async function collectOwnedCleanup({ pids, ports, checkPort, failure, graceMs = 1000 }) {
118
+ const groups = []
119
+ for (const pid of pids) {
120
+ try {
121
+ groups.push(await cleanupOwnedProcess(pid, graceMs))
122
+ } catch (error) {
123
+ groups.push({ pid, alive: true, error: { code: error.code, message: error.message } })
124
+ }
125
+ }
126
+ const portResults = []
127
+ for (const port of ports) {
128
+ try {
129
+ portResults.push({ port, closed: (await checkPort(port)) === port })
130
+ } catch (error) {
131
+ portResults.push({ port, closed: false, error: { code: error.code, message: error.message } })
132
+ }
133
+ }
134
+ return {
135
+ pids: groups.map(({ pid, alive }) => ({ pid, alive })),
136
+ failure: failure ? { name: failure.name, message: failure.message } : null,
137
+ groups,
138
+ ports: portResults,
139
+ }
140
+ }
@@ -0,0 +1,107 @@
1
+ // @vitest-environment node
2
+ import assert from 'node:assert/strict'
3
+ import { test } from 'vite-plus/test'
4
+ import { createServer } from 'node:net'
5
+ import { mkdtempSync, writeFileSync } from 'node:fs'
6
+ import { join } from 'node:path'
7
+ import {
8
+ runOwnedProcess,
9
+ cleanupOwnedProcess,
10
+ processGroupAlive,
11
+ collectOwnedCleanup,
12
+ } from './owned-process.mjs'
13
+
14
+ const proof = mkdtempSync('/tmp/cvx-owned-process-')
15
+ console.log('Owned cleanup evidence: ' + proof)
16
+
17
+ const descendant = `process.on('SIGINT',()=>{}); process.on('SIGTERM',()=>{}); console.log('ready'); setInterval(()=>{},1000)`
18
+ const parent = `
19
+ const {spawn}=require('node:child_process');
20
+ const child=spawn(process.execPath,['-e',${JSON.stringify(descendant)}],{stdio:['ignore','pipe','ignore']});
21
+ process.on('SIGINT',()=>{}); process.on('SIGTERM',()=>{});
22
+ child.stdout.once('data',()=>{console.log('descendant:'+child.pid); MODE});
23
+ setInterval(()=>{},1000);
24
+ `
25
+
26
+ test('timeout terminates the entire owned group after ignored graceful signals', async () => {
27
+ let pid
28
+ try {
29
+ const result = await runOwnedProcess({
30
+ command: process.execPath,
31
+ args: ['-e', parent.replace('MODE', '')],
32
+ timeoutMs: 1500,
33
+ graceMs: 150,
34
+ onSpawn: (value) => {
35
+ pid = value
36
+ },
37
+ })
38
+ writeFileSync(join(proof, 'timeout.json'), JSON.stringify(result, null, 2))
39
+ assert.match(result.stdout, /descendant:\d+/)
40
+ assert.equal(result.timedOut, true)
41
+ assert.ok(result.timeoutCleanup.signals.includes('SIGKILL'))
42
+ assert.equal(result.cleanup.alive, false)
43
+ assert.equal(processGroupAlive(pid), false)
44
+ } finally {
45
+ if (pid) await cleanupOwnedProcess(pid, 150)
46
+ }
47
+ })
48
+
49
+ test('failed leader preserves failure output and finally cleans its surviving descendant', async () => {
50
+ let pid
51
+ try {
52
+ const result = await runOwnedProcess({
53
+ command: process.execPath,
54
+ args: ['-e', parent.replace('MODE', "console.error('original failure'); process.exit(7)")],
55
+ timeoutMs: 1500,
56
+ graceMs: 150,
57
+ onSpawn: (value) => {
58
+ pid = value
59
+ },
60
+ })
61
+ writeFileSync(join(proof, 'failed-leader.json'), JSON.stringify(result, null, 2))
62
+ assert.equal(result.code, 7)
63
+ assert.equal(result.timedOut, false)
64
+ assert.match(result.stderr, /original failure/)
65
+ assert.equal(result.cleanup.alive, false)
66
+ assert.equal(processGroupAlive(pid), false)
67
+ } finally {
68
+ if (pid) await cleanupOwnedProcess(pid, 150)
69
+ }
70
+ })
71
+
72
+ test('cleanup rejects a group that was not created by the runner', async () => {
73
+ await assert.rejects(cleanupOwnedProcess(process.pid, 20), /not owned/)
74
+ })
75
+
76
+ test('port-check failure is recorded without replacing original proof failure', async () => {
77
+ const server = createServer()
78
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
79
+ const port = server.address().port
80
+ try {
81
+ const result = await runOwnedProcess({
82
+ command: process.execPath,
83
+ args: ['-e', 'process.exit(7)'],
84
+ timeoutMs: 1000,
85
+ })
86
+ const failure = new Error('original proof failure: exit ' + result.code)
87
+ const evidence = await collectOwnedCleanup({
88
+ pids: [result.pid],
89
+ ports: [port],
90
+ failure,
91
+ checkPort: (requested) =>
92
+ new Promise((resolve, reject) => {
93
+ const probe = createServer()
94
+ probe.once('error', reject)
95
+ probe.listen(requested, '127.0.0.1', () => probe.close(() => resolve(requested)))
96
+ }),
97
+ })
98
+ writeFileSync(join(proof, 'port-failure.json'), JSON.stringify(evidence, null, 2))
99
+ assert.equal(evidence.failure.message, 'original proof failure: exit 7')
100
+ assert.equal(evidence.ports[0].closed, false)
101
+ assert.equal(evidence.ports[0].error.code, 'EADDRINUSE')
102
+ assert.equal(evidence.groups[0].alive, false)
103
+ assert.equal(server.listening, true, 'unrelated listener must never be killed')
104
+ } finally {
105
+ await new Promise((resolve) => server.close(resolve))
106
+ }
107
+ })
@@ -0,0 +1,296 @@
1
+ import assert from 'node:assert/strict'
2
+ import { execFileSync } from 'node:child_process'
3
+ import { runOwnedProcess, collectOwnedCleanup } from './owned-process.mjs'
4
+ import { createHash } from 'node:crypto'
5
+ import {
6
+ cpSync,
7
+ existsSync,
8
+ mkdtempSync,
9
+ readFileSync,
10
+ readdirSync,
11
+ symlinkSync,
12
+ writeFileSync,
13
+ } from 'node:fs'
14
+ import { createServer } from 'node:net'
15
+ import { join, resolve, relative } from 'node:path'
16
+ import {
17
+ localConvexEnvironment,
18
+ assertIsolatedConvexFixture,
19
+ assertLocalConvexState,
20
+ } from './convex-smoke-env.mjs'
21
+
22
+ // Run against the retained installed peer of the exact packed stress candidate.
23
+ const packed = resolve(process.argv[2] ?? '')
24
+ const identity = JSON.parse(readFileSync(join(packed, 'package-identity.json'), 'utf8'))
25
+ const hash = (bytes) => createHash('sha256').update(bytes).digest('hex')
26
+ assert.equal(hash(readFileSync(identity.tarball)), identity.sha256)
27
+ const source = join(packed, 'installed')
28
+ assert.equal(
29
+ JSON.parse(readFileSync(join(source, 'node_modules/convex/package.json'), 'utf8')).version,
30
+ '1.46.0',
31
+ )
32
+ const fixture = mkdtempSync('/tmp/cvx-relational-engine-native-')
33
+ console.log(`U8 native retained proof: ${fixture}`)
34
+ cpSync(join(source, 'convex'), join(fixture, 'convex'), { recursive: true })
35
+ symlinkSync(join(source, 'node_modules'), join(fixture, 'node_modules'), 'dir')
36
+ writeFileSync(
37
+ join(fixture, 'package.json'),
38
+ JSON.stringify({
39
+ private: true,
40
+ type: 'module',
41
+ dependencies: { convex: '1.46.0', 'cvx-kit': identity.version },
42
+ }),
43
+ )
44
+ cpSync(join(source, 'register.mjs'), join(fixture, 'register.mjs'))
45
+ cpSync(
46
+ resolve(import.meta.dirname, '../test/fixture-packed-querying/audit-native.mjs.template'),
47
+ join(fixture, 'audit.mjs'),
48
+ )
49
+ cpSync(join(source, 'tsconfig.json'), join(fixture, 'tsconfig.json'))
50
+ writeFileSync(join(fixture, 'package-identity.json'), JSON.stringify(identity, null, 2))
51
+ // Native representative runs under central defaults, rather than the stress ceilings.
52
+ writeFileSync(
53
+ join(fixture, 'convex/querying.ts'),
54
+ `import { createQueryEngine } from 'cvx-kit/querying'
55
+ import schema from './schema'
56
+ import { relations } from './relations'
57
+ import { cursor } from './functions'
58
+ export const querying = createQueryEngine({ schema, relations, cursor })
59
+ `,
60
+ )
61
+ const originalRelations = readFileSync(join(fixture, 'convex/relations.ts'), 'utf8')
62
+ writeFileSync(join(fixture, 'convex/relations.ts'), originalRelations)
63
+ writeFileSync(join(fixture, 'convex/relationsEquivalent.ts'), originalRelations)
64
+ writeFileSync(
65
+ join(fixture, 'convex/relationsChanged.ts'),
66
+ originalRelations.replace(
67
+ 'aliasLabels: r.many.labels({ from: r.tasks._id.through(r.edges.task), to: r.labels._id.through(r.edges.label) })',
68
+ 'aliasLabels: r.many.labels({ from: r.tasks._id, to: r.labels.task })',
69
+ ),
70
+ )
71
+ writeFileSync(
72
+ join(fixture, 'convex/api/probes.ts'),
73
+ `import { createQueryEngine } from 'cvx-kit/querying'
74
+ import { authQuery } from '../functions'
75
+ import { relations as equivalent } from '../relationsEquivalent'
76
+ import { relations as changed } from '../relationsChanged'
77
+ import schema from '../schema'
78
+ import { cursor } from '../functions'
79
+ import { contract } from '../domain/tasks/contracts'
80
+ const eq = createQueryEngine({ schema, relations: equivalent, cursor })
81
+ const different = createQueryEngine({ schema, relations: changed, cursor })
82
+ export const resume = authQuery({ args: contract.queries.list.input, returns: contract.queries.list.result, handler: (ctx,args) => eq(ctx).tasks.paginate(args) })
83
+ export const reject = authQuery({ args: contract.queries.list.input, returns: contract.queries.list.result, handler: (ctx,args) => different(ctx).tasks.paginate(args) })
84
+ `,
85
+ )
86
+ writeFileSync(
87
+ join(fixture, 'convex/seed.ts'),
88
+ `import { internalMutation } from './_generated/server'
89
+ export const seed = internalMutation({ args: {}, handler: async (ctx) => {
90
+ const tasks = []
91
+ for(let ordinal=0;ordinal<24;ordinal++) tasks.push(await ctx.db.insert('tasks',{ordinal,tenant:'a',department:'support',status:'open',active:false,priority:0,code:'',authorized:ordinal>=5,secret:'NATIVE_PRIVATE'}))
92
+ const labels=[]
93
+ for(let ordinal=0;ordinal<6;ordinal++) labels.push(await ctx.db.insert('labels',{ordinal,tenant:'a',authorized:ordinal!==5,name:'native-label-'+ordinal,task:tasks[5]}))
94
+ await ctx.db.patch(tasks[5],{reference:tasks[0],required:labels[0]})
95
+ for(let ordinal=0;ordinal<6;ordinal++) await ctx.db.insert('edges',{ordinal,task:tasks[5],label:labels[ordinal],authorized:ordinal!==4})
96
+ await ctx.db.insert('edges',{ordinal:6,task:tasks[5],label:labels[1],authorized:true})
97
+ return {tasks,labels}
98
+ } })
99
+ `,
100
+ )
101
+ // Generated by the native CLI before deployment; initial binding supports the HTTP seed route.
102
+ const serverPath = join(fixture, 'convex/_generated/server.ts')
103
+ writeFileSync(
104
+ serverPath,
105
+ readFileSync(serverPath, 'utf8') +
106
+ "\nexport { httpActionGeneric as httpAction } from 'convex/server'\n",
107
+ )
108
+ writeFileSync(
109
+ join(fixture, 'convex/http.ts'),
110
+ `import { httpRouter } from 'convex/server'
111
+ import { httpAction } from './_generated/server'
112
+ import { makeFunctionReference } from 'convex/server'
113
+ const router=httpRouter()
114
+ router.route({path:'/seed',method:'POST',handler:httpAction(async ctx=>new Response(JSON.stringify(await ctx.runMutation(makeFunctionReference<'mutation'>('seed:seed'),{})),{headers:{'content-type':'application/json'}}))})
115
+ export default router
116
+ `,
117
+ )
118
+ // Metadata comes from actual native registered functions, not a reduced hand-written validator.
119
+ writeFileSync(
120
+ join(fixture, 'metadata.mjs'),
121
+ `import { writeFileSync } from 'node:fs'; import * as api from './convex/api/tasks.ts';
122
+ for(const [name, fn] of Object.entries(api)) writeFileSync('validator-'+name+'.json',JSON.stringify({args:JSON.parse(fn.exportArgs()),returns:JSON.parse(fn.exportReturns())}));
123
+ `,
124
+ )
125
+ writeFileSync(
126
+ join(fixture, 'verify.mjs'),
127
+ `import assert from 'node:assert/strict';import {readFileSync,writeFileSync} from 'node:fs';import {spawnSync} from 'node:child_process';
128
+ const key=JSON.parse(readFileSync('.convex/local/default/config.json')).adminKey;
129
+ const who={subject:'native-reader',issuer:'https://fixture.test',tokenIdentifier:'https://fixture.test|native-reader',org_id:'a',role:'reader'};
130
+ const url='http://127.0.0.1:'+process.argv[2];const records=[];
131
+ async function call(path,label,args,valid=true,identity=who){
132
+ const started=performance.now();const res=await fetch(url+'/api/query',{method:'POST',headers:{'content-type':'application/json',...(identity?{Authorization:'Convex '+key+':'+Buffer.from(JSON.stringify(identity)).toString('base64')}:{})},body:JSON.stringify({path,args,format:'json'})});const raw=await res.text();writeFileSync('http-'+records.length+'-'+label+'.json',raw);const body=JSON.parse(raw);assert.equal(res.status,200);assert.equal(body.status,valid?'success':'error',label+': '+raw);assert.ok(!raw.includes('NATIVE_PRIVATE'));records.push({path,label,args,status:body.status,milliseconds:performance.now()-started,bytes:Buffer.byteLength(raw)});writeFileSync('native-results.json',JSON.stringify(records,null,2));return body;
133
+ }
134
+ // Local deployment registration also consumes the backend write-rate window.
135
+ await new Promise(resolve=>setTimeout(resolve,2000));
136
+ const seedResponse=await fetch('http://127.0.0.1:'+process.argv[3]+'/seed',{method:'POST'});const seedRaw=await seedResponse.text();writeFileSync('seed-envelope.json',seedRaw);assert.equal(seedResponse.status,200);const ids=JSON.parse(seedRaw);
137
+ for(const order of ['asc','desc']){let cursor=null;const actual=[];for(let page=0;page<30;page++){const body=await call('api/tasks:conditional','conditional-'+order+'-'+page,{numItems:7,cursor,order,filters:{active:false}});actual.push(...body.value.page.map(r=>r._id));if(body.value.isDone)break;assert.notEqual(body.value.continueCursor,cursor);cursor=body.value.continueCursor;}const expected=ids.tasks.slice(5);if(order==='desc')expected.reverse();assert.deepEqual(actual,expected);}
138
+ const first=(await call('api/tasks:list','first',{numItems:1,cursor:null})).value;
139
+ assert.match(first.continueCursor,/^pc\\./);assert.ok(!first.continueCursor.includes(ids.tasks[5]));
140
+ await call('api/probes:resume','equivalent-registry',{numItems:7,cursor:first.continueCursor});
141
+ await call('api/probes:reject','changed-registry',{numItems:7,cursor:first.continueCursor},false);
142
+ for(const [label,args,identity] of [['tamper',{numItems:1,cursor:first.continueCursor+'!'},who],['filter',{numItems:1,cursor:first.continueCursor,filters:{ordinal:6}},who],['order',{numItems:1,cursor:first.continueCursor,order:'desc'},who],['tenant',{numItems:1,cursor:first.continueCursor},{...who,org_id:'b'}],['principal',{numItems:1,cursor:first.continueCursor},{...who,subject:'other',tokenIdentifier:'other'}]]){const body=await call('api/tasks:list',label,args,false,identity);assert.match(body.errorMessage,/Invalid cursor/);}
143
+ await call('api/tasks:list','no-identity',{numItems:1,cursor:null},false,null);
144
+ await call('api/tasks:list','unsupported-role',{numItems:1,cursor:null},false,{...who,role:'unknown'});
145
+ const expanded=(await call('api/tasks:expanded','expanded',{numItems:7,cursor:null,filters:{ordinal:5}})).value.page[0];assert.equal(expanded.referenceTask,null);assert.equal(expanded.requiredLabel._id,ids.labels[0]);assert.equal(expanded.labels.page.length,5);assert.ok(expanded.labels.page.every(r=>r.owner._id===ids.tasks[5]));assert.deepEqual(expanded.labels.page.map(r=>r._id),expanded.aliasLabels.page.map(r=>r._id));
146
+ const predicate=(await call('api/tasks:list','nested-predicate',{numItems:7,cursor:null,filters:{labels:{some:{ordinal:1,owner:{ordinal:5}}}}})).value;assert.deepEqual(predicate.page.map(r=>r._id),[ids.tasks[5]]);
147
+ let cursor=null;const child=[];for(let page=0;page<10;page++){const value=(await call('api/tasks:next','child-'+page,{parent:ids.tasks[5],numItems:1,cursor})).value;child.push(...value.page.map(r=>r._id));if(value.isDone)break;cursor=value.continueCursor;}assert.deepEqual(child,[...ids.labels.slice(0,4),ids.labels[1]]);
148
+ await call('api/tasks:next','cross-parent',{parent:ids.tasks[6],numItems:1,cursor},false);
149
+ for(const [label,args] of [['wrong-scalar',{numItems:1,cursor:null,filters:{referenceTask:{ordinal:'wrong'}}}],['unknown-operator',{numItems:1,cursor:null,filters:{ordinal:{bad:1}}}],['bad-options',{numItems:0,cursor:null}],['unknown-field',{numItems:1,cursor:null,filters:{unknown:1}}]])await call('api/tasks:list',label,args,false);
150
+ const wrongTable=await call('api/tasks:next','wrong-table-parent',{parent:ids.labels[0],numItems:1,cursor:null},false);assert.match(wrongTable.errorMessage,/ArgumentValidationError/);assert.ok(!wrongTable.errorMessage.includes('Invalid cursor'));
151
+ const split=(await call('api/tasks:list','native-limit',{numItems:100,cursor:null,maximumRowsRead:8})).value;assert.match(split.splitCursor,/^pc\\./);assert.ok(['SplitRequired','SplitRecommended'].includes(split.pageStatus));
152
+ const left=(await call('api/tasks:list','end-left',{numItems:100,cursor:null,endCursor:split.splitCursor})).value;const right=(await call('api/tasks:list','end-right',{numItems:100,cursor:split.splitCursor,endCursor:split.continueCursor})).value;assert.deepEqual([...left.page,...right.page],split.page);
153
+ const cli=spawnSync(process.execPath,['node_modules/convex/bin/main.js','run','api/tasks:list',JSON.stringify({numItems:1,cursor:null}),'--identity',JSON.stringify(who)],{encoding:'utf8',timeout:30000});writeFileSync('cli-identity.stdout.log',cli.stdout);writeFileSync('cli-identity.stderr.log',cli.stderr);assert.equal(cli.status,0);assert.equal(JSON.parse(cli.stdout).page[0]._id,ids.tasks[5]);
154
+ writeFileSync('NATIVE_SUCCESS',JSON.stringify({cases:records.length,cliIdentity:true}));console.log(records.length+' native HTTP envelopes passed');
155
+ `,
156
+ )
157
+ const files = (dir) =>
158
+ readdirSync(dir, { withFileTypes: true }).flatMap((e) =>
159
+ e.isDirectory() ? files(join(dir, e.name)) : [join(dir, e.name)],
160
+ )
161
+ const paths = files(join(fixture, 'convex')).filter((p) => !p.includes('/_generated/'))
162
+ const hashes = () =>
163
+ Object.fromEntries(paths.map((p) => [relative(fixture, p), hash(readFileSync(p))]))
164
+ const before = hashes()
165
+ writeFileSync(join(fixture, 'source-before.json'), JSON.stringify(before, null, 2))
166
+ execFileSync(process.execPath, ['--import', './register.mjs', 'metadata.mjs'], {
167
+ cwd: fixture,
168
+ stdio: 'pipe',
169
+ })
170
+ const metadata = files(fixture).filter((p) => /validator-.*\.json$/.test(p))
171
+ writeFileSync(
172
+ join(fixture, 'native-validator-hashes.json'),
173
+ JSON.stringify(
174
+ metadata.map((p) => ({
175
+ path: relative(fixture, p),
176
+ bytes: readFileSync(p).length,
177
+ sha256: hash(readFileSync(p)),
178
+ })),
179
+ null,
180
+ 2,
181
+ ),
182
+ )
183
+ const env = localConvexEnvironment()
184
+ assertIsolatedConvexFixture(fixture)
185
+ async function freePort(requested = 0) {
186
+ const server = createServer()
187
+ await new Promise((done, fail) => {
188
+ server.once('error', fail)
189
+ server.listen(requested, '127.0.0.1', done)
190
+ })
191
+ const port = server.address().port
192
+ await new Promise((done) => server.close(done))
193
+ return port
194
+ }
195
+ const cloud = await freePort()
196
+ let site = await freePort()
197
+ while (site === cloud) site = await freePort()
198
+ const commands = []
199
+ const processes = []
200
+ async function run(label, args) {
201
+ commands.push([process.execPath, 'node_modules/convex/bin/main.js', ...args])
202
+ writeFileSync(join(fixture, 'commands.json'), JSON.stringify(commands, null, 2))
203
+ const result = await runOwnedProcess({
204
+ command: process.execPath,
205
+ args: commands.at(-1).slice(1),
206
+ cwd: fixture,
207
+ env,
208
+ onSpawn: (pid) => processes.push(pid),
209
+ })
210
+ const { stdout, stderr, ...evidence } = result
211
+ writeFileSync(join(fixture, label + '.stdout.log'), stdout)
212
+ writeFileSync(join(fixture, label + '.stderr.log'), stderr)
213
+ writeFileSync(join(fixture, label + '-result.json'), JSON.stringify(evidence, null, 2))
214
+ assert.equal(result.code, 0, label + ' failed; retained logs')
215
+ assert.equal(result.timedOut, false, label + ' timed out; retained logs')
216
+ assert.equal(result.cleanup?.alive, false, label + ' owned group survived cleanup')
217
+ console.log(label + ': exit 0')
218
+ }
219
+ let originalFailure
220
+ try {
221
+ await run('deploy', [
222
+ 'dev',
223
+ '--once',
224
+ '--typecheck=disable',
225
+ '--local-cloud-port',
226
+ String(cloud),
227
+ '--local-site-port',
228
+ String(site),
229
+ ])
230
+ assertLocalConvexState(fixture)
231
+ const cfg = JSON.parse(readFileSync(join(fixture, '.convex/local/default/config.json')))
232
+ assert.equal(cfg.ports.cloud, cloud)
233
+ assert.equal(cfg.ports.site, site)
234
+ writeFileSync(
235
+ join(fixture, 'local-binding.json'),
236
+ JSON.stringify({ ports: cfg.ports, backendVersion: cfg.backendVersion }),
237
+ )
238
+ execFileSync(join(source, 'node_modules/.bin/tsc'), ['--project', 'tsconfig.json'], {
239
+ cwd: fixture,
240
+ stdio: 'pipe',
241
+ })
242
+ writeFileSync(
243
+ join(fixture, 'strict-types-result.json'),
244
+ JSON.stringify({ exitCode: 0, strict: true, skipLibCheck: false }),
245
+ )
246
+ await run('runtime', [
247
+ 'dev',
248
+ '--once',
249
+ '--typecheck=disable',
250
+ '--start',
251
+ `node verify.mjs ${cloud} ${site}`,
252
+ ])
253
+ assert.ok(existsSync(join(fixture, 'NATIVE_SUCCESS')))
254
+ const rows = JSON.parse(readFileSync(join(fixture, 'native-results.json')))
255
+ assert.ok(rows.length >= 25)
256
+ assert.equal(files(fixture).filter((p) => /http-\d+-.*\.json$/.test(p)).length, rows.length)
257
+ const key = JSON.parse(readFileSync(join(fixture, '.convex/local/default/config.json'))).adminKey
258
+ for (const path of files(fixture).filter(
259
+ (p) => /\.(log|json)$/.test(p) && !p.includes('/.convex/'),
260
+ )) {
261
+ const bytes = readFileSync(path, 'utf8')
262
+ assert.ok(!bytes.includes(key))
263
+ assert.ok(!bytes.includes('Authorization: Convex'))
264
+ }
265
+ assert.deepEqual(hashes(), before)
266
+ assert.equal(hash(readFileSync(identity.tarball)), identity.sha256)
267
+ writeFileSync(join(fixture, 'source-after.json'), JSON.stringify(hashes(), null, 2))
268
+ } catch (error) {
269
+ originalFailure = error
270
+ throw error
271
+ } finally {
272
+ const cleanup = await collectOwnedCleanup({
273
+ pids: processes,
274
+ ports: [cloud, site],
275
+ checkPort: freePort,
276
+ failure: originalFailure,
277
+ })
278
+ writeFileSync(join(fixture, 'cleanup.json'), JSON.stringify(cleanup, null, 2))
279
+ // Preserve the original proof error; cleanup diagnostics remain independently recorded.
280
+ if (!originalFailure) {
281
+ assert.ok(
282
+ cleanup.groups.every((group) => !group.alive && !group.error && group.errors.length === 0),
283
+ 'Owned process cleanup failed',
284
+ )
285
+ assert.ok(
286
+ cleanup.ports.every((port) => port.closed),
287
+ 'Owned ports remain occupied',
288
+ )
289
+ }
290
+ }
291
+ writeFileSync(
292
+ join(fixture, 'SUCCESS'),
293
+ 'Bounded exact packed default runtime integrated proof passed.\n',
294
+ )
295
+ execFileSync(process.execPath, ['audit.mjs'], { cwd: fixture, stdio: 'pipe' })
296
+ console.log(`Native proof complete: ${fixture}`)
@@ -29,6 +29,7 @@ const extraTypeFixtures = [
29
29
  join(root, 'README.md'),
30
30
  join(root, 'src/docs/effect.md'),
31
31
  join(root, 'src/docs/commands.md'),
32
+ join(root, 'src/docs/domain-contracts.md'),
32
33
  join(root, 'src/docs/command-context.md'),
33
34
  join(root, 'src/docs/commands-legacy.md'),
34
35
  join(root, 'src/docs/auth.md'),
@@ -143,6 +144,8 @@ import { workflowTransition } from 'cvx-kit/workflow'
143
144
  import { selectOperation, bindOperationExecutor, createOperationTools, operationToolDialect } from 'cvx-kit/agent-tools'
144
145
  import { actionGeneric, queryGeneric, mutationGeneric, internalActionGeneric, internalQueryGeneric, internalMutationGeneric } from 'convex/server'
145
146
  import { z } from 'zod'
147
+ import { convexTest } from 'convex-test'
148
+ import { defineSchema, anyApi } from 'convex/server'
146
149
  const require = createRequire(import.meta.url)
147
150
  if (process.argv.includes('--without-effect')) {
148
151
  assert.throws(() => require.resolve('effect'), { code: 'MODULE_NOT_FOUND' }, 'optional peer was unexpectedly auto-installed')
@@ -186,7 +189,11 @@ const auth = createAuthFunctions({
186
189
  getAuthUser: async () => ({ id: 'actor' }), mapRole: defaultRoleMap, adminRoles: ['admin'],
187
190
  })
188
191
  const authenticated = auth.authQuery({ args: {}, returns: z.string(), handler: ctx => ctx.actor.userId + ':' + ctx.tenant })
189
- assert.equal(await authenticated._handler({ auth: { getUserIdentity: async () => ({ subject: 'actor', org_id: 'org', role: 'member' }) }, db: {} }, {}), 'actor:org')
192
+ const authTest = convexTest(defineSchema({}), {
193
+ './_generated/server.js': async () => ({ query: queryGeneric }),
194
+ './auth.js': async () => ({ authenticated }),
195
+ })
196
+ assert.equal(await authTest.withIdentity({ subject: 'actor', org_id: 'org', role: 'member' }).query(anyApi.auth.authenticated, {}), 'actor:org')
190
197
  const table = zodTable('notes', () => ({ text: z.string() }), { commandFields: ['text'] })
191
198
  const crud = createCrudCommands({ Command, table, aggregateType: 'note', actor: () => 'actor' })
192
199
  const changes = []
@@ -374,6 +381,7 @@ try {
374
381
  'cvx-kit': `file:${join(temporary, `cvx-kit-${manifest.version}.tgz`)}`,
375
382
  convex: manifest.devDependencies.convex,
376
383
  'convex-helpers': helpersVersion,
384
+ 'convex-test': '0.0.61',
377
385
  '@convex-dev/workflow': manifest.dependencies['@convex-dev/workflow'],
378
386
  zod: manifest.devDependencies.zod,
379
387
  }
@@ -405,6 +413,7 @@ try {
405
413
  for (const filename of [
406
414
  'effect-foundation-types.ts',
407
415
  'domain-effect-types.ts',
416
+ 'domain-handler-types.ts',
408
417
  'domain-exactness-types.ts',
409
418
  'effect-api-types.ts',
410
419
  'effect-api-zod-types.ts',
@@ -9,7 +9,7 @@ const root = join(import.meta.dirname, '..')
9
9
  const temporary = mkdtempSync(join(tmpdir(), 'cvx-kit-oxlint-'))
10
10
  const manifest = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'))
11
11
  const ruleNames = Object.keys(rules)
12
- assert.equal(ruleNames.length, 21)
12
+ assert.equal(ruleNames.length, 23)
13
13
 
14
14
  try {
15
15
  run('bun', ['pm', 'pack', '--destination', temporary, '--ignore-scripts'], root)
@@ -79,6 +79,7 @@ export const value = privateHelper()
79
79
  import { makeFunctionReference as ref } from 'convex/server'
80
80
  import { z } from 'zod'
81
81
  import { createAuthFunctions } from 'cvx-kit/auth'
82
+ import { zodTable } from 'cvx-kit/zod-table'
82
83
  import { other } from '../domain/users/commands'
83
84
  export const save = mutation({ handler: async (ctx) => {
84
85
  await ctx.db.insert('orders', { updatedAt: Date.now() })
@@ -88,6 +89,9 @@ export const constructors = createAuthFunctions({})
88
89
  export const state = z.enum(['draft'])
89
90
  export const target = ref('orders:save')
90
91
  export const value = other
92
+ const orders = zodTable('orders', () => ({ name: z.string() }))
93
+ export const dto = { ...orders.toPublicDto(row), _id: row._id }
94
+ export const pagination = z.object({ numItems: z.number(), cursor: z.string().nullable() })
91
95
  `,
92
96
  )
93
97
  mkdirSync(join(fixture, 'convex/application'), { recursive: true })