@pikku/kysely 0.13.15 → 0.13.18

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 (65) hide show
  1. package/CHANGELOG.md +229 -0
  2. package/bin/pikku-kysely-pure.ts +0 -0
  3. package/dist/src/coercion-plugin.d.ts +41 -0
  4. package/dist/src/coercion-plugin.js +150 -0
  5. package/dist/src/create-audited-kysely.d.ts +1 -1
  6. package/dist/src/index.d.ts +6 -5
  7. package/dist/src/index.js +5 -4
  8. package/dist/src/{kysely-ai-run-scores.d.ts → kysely-agent-run-scores.d.ts} +3 -3
  9. package/dist/src/{kysely-ai-run-scores.js → kysely-agent-run-scores.js} +3 -3
  10. package/dist/src/{kysely-ai-agent-run-service.d.ts → kysely-agent-run-service.d.ts} +4 -4
  11. package/dist/src/{kysely-ai-agent-run-service.js → kysely-agent-run-service.js} +8 -8
  12. package/dist/src/{kysely-ai-run-state-service.d.ts → kysely-agent-run-state-service.d.ts} +6 -5
  13. package/dist/src/{kysely-ai-run-state-service.js → kysely-agent-run-state-service.js} +11 -11
  14. package/dist/src/{kysely-ai-storage-service.d.ts → kysely-agent-storage-service.d.ts} +10 -10
  15. package/dist/src/{kysely-ai-storage-service.js → kysely-agent-storage-service.js} +31 -28
  16. package/dist/src/kysely-audit-service.d.ts +3 -1
  17. package/dist/src/kysely-channel-store.d.ts +1 -1
  18. package/dist/src/kysely-credential-service.js +1 -1
  19. package/dist/src/kysely-deployment-service.d.ts +2 -1
  20. package/dist/src/kysely-scope-service.d.ts +2 -1
  21. package/dist/src/kysely-secret-service.d.ts +1 -1
  22. package/dist/src/kysely-secret-service.js +2 -2
  23. package/dist/src/kysely-session-store.d.ts +1 -1
  24. package/dist/src/kysely-tables.d.ts +12 -12
  25. package/dist/src/kysely-webhook-service.d.ts +2 -1
  26. package/dist/src/kysely-webhook-service.js +2 -1
  27. package/dist/src/kysely-workflow-mirror.d.ts +1 -1
  28. package/dist/src/kysely-workflow-service.d.ts +3 -2
  29. package/dist/src/kysely-workflow-service.js +1 -1
  30. package/dist/src/schema/{ai.schema.d.ts → agent.schema.d.ts} +4 -4
  31. package/dist/src/schema/{ai.schema.js → agent.schema.js} +29 -29
  32. package/dist/src/schema/index.js +4 -4
  33. package/dist/src/serialize-plugin.d.ts +0 -4
  34. package/dist/src/serialize-plugin.js +0 -4
  35. package/dist/tsconfig.tsbuildinfo +1 -1
  36. package/package.json +7 -7
  37. package/src/coercion-plugin.test.ts +160 -0
  38. package/src/coercion-plugin.ts +187 -0
  39. package/src/create-audited-kysely.test.ts +1 -1
  40. package/src/create-audited-kysely.ts +1 -1
  41. package/src/index.ts +10 -5
  42. package/src/{kysely-ai-run-scores.ts → kysely-agent-run-scores.ts} +5 -5
  43. package/src/{kysely-ai-agent-run-service.ts → kysely-agent-run-service.ts} +18 -18
  44. package/src/{kysely-ai-run-state-service.ts → kysely-agent-run-state-service.ts} +16 -15
  45. package/src/{kysely-ai-storage-service.ts → kysely-agent-storage-service.ts} +53 -43
  46. package/src/kysely-audit-service.test.ts +1 -1
  47. package/src/kysely-audit-service.ts +4 -6
  48. package/src/kysely-channel-store.ts +1 -1
  49. package/src/kysely-credential-service.ts +5 -5
  50. package/src/kysely-deployment-service.ts +2 -1
  51. package/src/kysely-scope-service.ts +5 -2
  52. package/src/kysely-secret-service.ts +7 -6
  53. package/src/kysely-services.test.ts +10 -10
  54. package/src/kysely-session-store.ts +1 -1
  55. package/src/kysely-tables.ts +12 -12
  56. package/src/kysely-virtual-user-run-store.ts +1 -1
  57. package/src/kysely-webhook-service.test.ts +1 -1
  58. package/src/kysely-webhook-service.ts +2 -2
  59. package/src/kysely-workflow-mirror.ts +1 -1
  60. package/src/kysely-workflow-service.test.ts +0 -1
  61. package/src/kysely-workflow-service.ts +11 -11
  62. package/src/schema/{ai.schema.ts → agent.schema.ts} +29 -29
  63. package/src/schema/index.ts +4 -4
  64. package/src/schema/schema.test.ts +6 -6
  65. package/src/serialize-plugin.ts +0 -5
@@ -2,18 +2,18 @@ import { sql } from 'kysely';
2
2
  /**
3
3
  * Threads, messages, tool calls, working memory and agent runs.
4
4
  *
5
- * `aiRun` carries `pendingApprovals` even though the two services that used to
6
- * create this table disagreed about it: `KyselyAIStorageService` omitted the
7
- * column while `KyselyAIRunStateService` declared it and read it back through
5
+ * `agentRun` carries `pendingApprovals` even though the two services that used to
6
+ * create this table disagreed about it: `KyselyAgentStorageService` omitted the
7
+ * column while `KyselyAgentRunStateService` declared it and read it back through
8
8
  * casts. Whichever service happened to run first decided the shape, and on a
9
9
  * database where the storage service won, resolving an approval failed. One
10
10
  * declaration ends that — the column is here because live code reads it.
11
11
  */
12
- export const aiSchema = {
13
- name: 'ai',
12
+ export const agentSchema = {
13
+ name: 'agent',
14
14
  statements: [
15
15
  (db) => db.schema
16
- .createTable('aiThreads')
16
+ .createTable('agentThreads')
17
17
  .addColumn('id', 'varchar(36)', (col) => col.primaryKey())
18
18
  .addColumn('resourceId', 'varchar(255)', (col) => col.notNull())
19
19
  .addColumn('title', 'text')
@@ -21,25 +21,25 @@ export const aiSchema = {
21
21
  .addColumn('createdAt', 'timestamp', (col) => col.defaultTo(sql `CURRENT_TIMESTAMP`).notNull())
22
22
  .addColumn('updatedAt', 'timestamp', (col) => col.defaultTo(sql `CURRENT_TIMESTAMP`).notNull()),
23
23
  (db) => db.schema
24
- .createIndex('idx_ai_threads_resource')
25
- .on('aiThreads')
24
+ .createIndex('idx_agent_threads_resource')
25
+ .on('agentThreads')
26
26
  .column('resourceId'),
27
27
  (db) => db.schema
28
- .createTable('aiMessage')
28
+ .createTable('agentMessage')
29
29
  .addColumn('id', 'varchar(36)', (col) => col.primaryKey())
30
- .addColumn('threadId', 'varchar(36)', (col) => col.notNull().references('aiThreads.id').onDelete('cascade'))
30
+ .addColumn('threadId', 'varchar(36)', (col) => col.notNull().references('agentThreads.id').onDelete('cascade'))
31
31
  .addColumn('role', 'varchar(50)', (col) => col.notNull())
32
32
  .addColumn('content', 'text')
33
33
  .addColumn('createdAt', 'timestamp', (col) => col.defaultTo(sql `CURRENT_TIMESTAMP`).notNull()),
34
34
  (db) => db.schema
35
- .createIndex('idx_ai_message_thread')
36
- .on('aiMessage')
35
+ .createIndex('idx_agent_message_thread')
36
+ .on('agentMessage')
37
37
  .columns(['threadId', 'createdAt']),
38
38
  (db) => db.schema
39
- .createTable('aiToolCall')
39
+ .createTable('agentToolCall')
40
40
  .addColumn('id', 'varchar(36)', (col) => col.primaryKey())
41
- .addColumn('threadId', 'varchar(36)', (col) => col.notNull().references('aiThreads.id').onDelete('cascade'))
42
- .addColumn('messageId', 'varchar(36)', (col) => col.notNull().references('aiMessage.id').onDelete('cascade'))
41
+ .addColumn('threadId', 'varchar(36)', (col) => col.notNull().references('agentThreads.id').onDelete('cascade'))
42
+ .addColumn('messageId', 'varchar(36)', (col) => col.notNull().references('agentMessage.id').onDelete('cascade'))
43
43
  .addColumn('runId', 'varchar(36)')
44
44
  .addColumn('toolName', 'varchar(255)', (col) => col.notNull())
45
45
  .addColumn('args', 'text', (col) => col.notNull())
@@ -51,25 +51,25 @@ export const aiSchema = {
51
51
  .addColumn('displayArgs', 'text')
52
52
  .addColumn('createdAt', 'timestamp', (col) => col.defaultTo(sql `CURRENT_TIMESTAMP`).notNull()),
53
53
  (db) => db.schema
54
- .createIndex('idx_ai_tool_call_thread')
55
- .on('aiToolCall')
54
+ .createIndex('idx_agent_tool_call_thread')
55
+ .on('agentToolCall')
56
56
  .column('threadId'),
57
57
  (db) => db.schema
58
- .createIndex('idx_ai_tool_call_message')
59
- .on('aiToolCall')
58
+ .createIndex('idx_agent_tool_call_message')
59
+ .on('agentToolCall')
60
60
  .column('messageId'),
61
61
  (db) => db.schema
62
- .createTable('aiWorkingMemory')
62
+ .createTable('agentWorkingMemory')
63
63
  .addColumn('id', 'varchar(255)', (col) => col.notNull())
64
64
  .addColumn('scope', 'varchar(50)', (col) => col.notNull())
65
65
  .addColumn('data', 'text', (col) => col.notNull())
66
66
  .addColumn('updatedAt', 'timestamp', (col) => col.defaultTo(sql `CURRENT_TIMESTAMP`).notNull())
67
- .addPrimaryKeyConstraint('ai_working_memory_pk', ['id', 'scope']),
67
+ .addPrimaryKeyConstraint('agent_working_memory_pk', ['id', 'scope']),
68
68
  (db) => db.schema
69
- .createTable('aiRun')
69
+ .createTable('agentRun')
70
70
  .addColumn('runId', 'varchar(36)', (col) => col.primaryKey())
71
71
  .addColumn('agentName', 'varchar(255)', (col) => col.notNull())
72
- .addColumn('threadId', 'varchar(36)', (col) => col.notNull().references('aiThreads.id').onDelete('cascade'))
72
+ .addColumn('threadId', 'varchar(36)', (col) => col.notNull().references('agentThreads.id').onDelete('cascade'))
73
73
  .addColumn('resourceId', 'varchar(255)', (col) => col.notNull())
74
74
  .addColumn('status', 'varchar(50)', (col) => col.notNull().defaultTo('running'))
75
75
  .addColumn('errorMessage', 'text')
@@ -82,21 +82,21 @@ export const aiSchema = {
82
82
  .addColumn('createdAt', 'timestamp', (col) => col.defaultTo(sql `CURRENT_TIMESTAMP`).notNull())
83
83
  .addColumn('updatedAt', 'timestamp', (col) => col.defaultTo(sql `CURRENT_TIMESTAMP`).notNull()),
84
84
  (db) => db.schema
85
- .createIndex('idx_ai_run_thread')
86
- .on('aiRun')
85
+ .createIndex('idx_agent_run_thread')
86
+ .on('agentRun')
87
87
  .columns(['threadId', 'createdAt']),
88
88
  (db) => db.schema
89
- .createTable('aiRunScore')
89
+ .createTable('agentRunScore')
90
90
  .addColumn('id', 'varchar(36)', (col) => col.primaryKey())
91
- .addColumn('runId', 'varchar(36)', (col) => col.notNull().references('aiRun.runId').onDelete('cascade'))
91
+ .addColumn('runId', 'varchar(36)', (col) => col.notNull().references('agentRun.runId').onDelete('cascade'))
92
92
  .addColumn('scorerName', 'varchar(255)', (col) => col.notNull())
93
93
  .addColumn('score', 'real', (col) => col.notNull())
94
94
  .addColumn('reason', 'text')
95
95
  .addColumn('metadata', 'text')
96
96
  .addColumn('createdAt', 'timestamp', (col) => col.defaultTo(sql `CURRENT_TIMESTAMP`).notNull()),
97
97
  (db) => db.schema
98
- .createIndex('idx_ai_run_score_run')
99
- .on('aiRunScore')
98
+ .createIndex('idx_agent_run_score_run')
99
+ .on('agentRunScore')
100
100
  .columns(['runId', 'createdAt']),
101
101
  ],
102
102
  };
@@ -1,6 +1,6 @@
1
1
  import { CamelCasePlugin } from 'kysely';
2
2
  import { schemaContext, } from './pikku-schema.types.js';
3
- import { aiSchema } from './ai.schema.js';
3
+ import { agentSchema } from './agent.schema.js';
4
4
  import { channelSchema } from './channel.schema.js';
5
5
  import { credentialSchema } from './credential.schema.js';
6
6
  import { deploymentSchema } from './deployment.schema.js';
@@ -31,7 +31,7 @@ export const pikkuSchemas = [
31
31
  deploymentSchema,
32
32
  webhookSchema,
33
33
  workflowSchema,
34
- aiSchema,
34
+ agentSchema,
35
35
  scopeSchema,
36
36
  ];
37
37
  /**
@@ -39,8 +39,8 @@ export const pikkuSchemas = [
39
39
  *
40
40
  * The plugin is applied here rather than trusted to the caller. Declarations
41
41
  * name tables and columns the way the rest of the codebase queries them
42
- * (`aiThreads.resourceId`), and it is `CamelCasePlugin` that turns those into
43
- * the physical `ai_threads.resource_id`. Without it the same declaration
42
+ * (`agentThreads.resourceId`), and it is `CamelCasePlugin` that turns those into
43
+ * the physical `agent_threads.resource_id`. Without it the same declaration
44
44
  * silently creates quoted camelCase tables that nothing can read.
45
45
  */
46
46
  const bind = (db) => db.withPlugin(new CamelCasePlugin());
@@ -69,7 +69,3 @@ export declare class SerializePlugin extends BaseSerializePlugin {
69
69
  */
70
70
  constructor(options?: SerializePluginOptions);
71
71
  }
72
- /**
73
- * @deprecated use {@link SerializePlugin} instead
74
- */
75
- export declare const SqliteSerializePlugin: typeof SerializePlugin;
@@ -171,7 +171,3 @@ export class SerializePlugin extends BaseSerializePlugin {
171
171
  super(serializer, deserializer, skipNodeKind);
172
172
  }
173
173
  }
174
- /**
175
- * @deprecated use {@link SerializePlugin} instead
176
- */
177
- export const SqliteSerializePlugin = SerializePlugin;
@@ -1 +1 @@
1
- {"root":["../src/create-audited-kysely.ts","../src/index.ts","../src/kysely-ai-agent-run-service.ts","../src/kysely-ai-run-scores.ts","../src/kysely-ai-run-state-service.ts","../src/kysely-ai-storage-service.ts","../src/kysely-audit-service.ts","../src/kysely-channel-store.ts","../src/kysely-credential-service.ts","../src/kysely-deployment-service.ts","../src/kysely-eventhub-store.ts","../src/kysely-json.ts","../src/kysely-scope-service.ts","../src/kysely-secret-service.ts","../src/kysely-session-store.ts","../src/kysely-tables.ts","../src/kysely-virtual-user-run-store.ts","../src/kysely-webhook-service.ts","../src/kysely-workflow-mirror.ts","../src/kysely-workflow-run-service.ts","../src/kysely-workflow-service.ts","../src/serialize-plugin.ts","../src/schema/ai.schema.ts","../src/schema/audit.schema.ts","../src/schema/channel.schema.ts","../src/schema/credential.schema.ts","../src/schema/deployment.schema.ts","../src/schema/index.ts","../src/schema/pikku-schema.types.ts","../src/schema/scope.schema.ts","../src/schema/secret.schema.ts","../src/schema/session.schema.ts","../src/schema/virtual-user.schema.ts","../src/schema/webhook.schema.ts","../src/schema/workflow.schema.ts","../bin/pikku-kysely-pure.ts"],"version":"6.0.3"}
1
+ {"root":["../src/coercion-plugin.ts","../src/create-audited-kysely.ts","../src/index.ts","../src/kysely-agent-run-scores.ts","../src/kysely-agent-run-service.ts","../src/kysely-agent-run-state-service.ts","../src/kysely-agent-storage-service.ts","../src/kysely-audit-service.ts","../src/kysely-channel-store.ts","../src/kysely-credential-service.ts","../src/kysely-deployment-service.ts","../src/kysely-eventhub-store.ts","../src/kysely-json.ts","../src/kysely-scope-service.ts","../src/kysely-secret-service.ts","../src/kysely-session-store.ts","../src/kysely-tables.ts","../src/kysely-virtual-user-run-store.ts","../src/kysely-webhook-service.ts","../src/kysely-workflow-mirror.ts","../src/kysely-workflow-run-service.ts","../src/kysely-workflow-service.ts","../src/serialize-plugin.ts","../src/schema/agent.schema.ts","../src/schema/audit.schema.ts","../src/schema/channel.schema.ts","../src/schema/credential.schema.ts","../src/schema/deployment.schema.ts","../src/schema/index.ts","../src/schema/pikku-schema.types.ts","../src/schema/scope.schema.ts","../src/schema/secret.schema.ts","../src/schema/session.schema.ts","../src/schema/virtual-user.schema.ts","../src/schema/webhook.schema.ts","../src/schema/workflow.schema.ts","../bin/pikku-kysely-pure.ts"],"version":"6.0.3"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pikku/kysely",
3
- "version": "0.13.15",
3
+ "version": "0.13.18",
4
4
  "description": "Kysely-backed Pikku services — workflow state, secrets, sessions, scopes and audit",
5
5
  "author": "yasser.fadl@gmail.com",
6
6
  "license": "MIT",
@@ -21,20 +21,20 @@
21
21
  "prepublishOnly": "yarn build"
22
22
  },
23
23
  "peerDependencies": {
24
- "@pikku/core": "^0.12.82"
24
+ "@pikku/core": "^0.12.86"
25
25
  },
26
26
  "dependencies": {
27
- "kysely": "^0.29.0"
27
+ "kysely": "^0.29.5"
28
28
  },
29
29
  "devDependencies": {
30
- "@types/better-sqlite3": "^7.6.13",
31
- "better-sqlite3": "^12.10.0",
30
+ "@types/better-sqlite3": "^9.6.0",
31
+ "better-sqlite3": "^13.0.3",
32
32
  "kysely-codegen": "^0.20.0",
33
33
  "kysely-postgres-js": "^3.0.0",
34
- "postgres": "^3.4.8",
34
+ "postgres": "^3.4.9",
35
35
  "typescript": "^6.0.3"
36
36
  },
37
37
  "exports": {
38
38
  ".": "./dist/src/index.js"
39
39
  }
40
- }
40
+ }
@@ -0,0 +1,160 @@
1
+ import { describe, test } from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import type { QueryResult, UnknownRow } from 'kysely'
4
+ import { createCoercionPlugin, type CoercionMap } from './coercion-plugin.js'
5
+
6
+ function selectFrom(...tables: string[]) {
7
+ return {
8
+ kind: 'SelectQueryNode',
9
+ from: {
10
+ kind: 'FromNode',
11
+ froms: tables.map((table) => ({
12
+ kind: 'TableNode',
13
+ table: {
14
+ kind: 'SchemableIdentifierNode',
15
+ identifier: { kind: 'IdentifierNode', name: table },
16
+ },
17
+ })),
18
+ },
19
+ }
20
+ }
21
+
22
+ const runTransform = async (
23
+ map: CoercionMap,
24
+ rows: UnknownRow[],
25
+ node?: unknown
26
+ ): Promise<UnknownRow[]> => {
27
+ const plugin = createCoercionPlugin({ map })
28
+ const queryId = {} as { queryId: string }
29
+ if (node !== undefined) {
30
+ plugin.transformQuery({ node, queryId } as any)
31
+ }
32
+ const result = { rows } as QueryResult<UnknownRow>
33
+ const out = await plugin.transformResult({ result, queryId } as any)
34
+ return out.rows as UnknownRow[]
35
+ }
36
+
37
+ describe('createCoercionPlugin', () => {
38
+ test('transformQuery passes the node through untouched', () => {
39
+ const plugin = createCoercionPlugin({ map: {} })
40
+ const node = selectFrom('users') as any
41
+ assert.equal(
42
+ plugin.transformQuery({ node, queryId: { queryId: 'x' } } as any),
43
+ node
44
+ )
45
+ })
46
+
47
+ test('coerces date columns from ISO strings to Date', async () => {
48
+ const [row] = await runTransform({ users: { created_at: 'date' } }, [
49
+ { created_at: '2026-06-26T00:00:00.000Z' },
50
+ ])
51
+ assert.ok(row!.created_at instanceof Date)
52
+ assert.equal(
53
+ (row!.created_at as Date).toISOString(),
54
+ '2026-06-26T00:00:00.000Z'
55
+ )
56
+ })
57
+
58
+ test('leaves unparseable date strings untouched', async () => {
59
+ const [row] = await runTransform({ users: { created_at: 'date' } }, [
60
+ { created_at: 'not-a-date' },
61
+ ])
62
+ assert.equal(row!.created_at, 'not-a-date')
63
+ })
64
+
65
+ test('coerces bool columns from 0/1 numbers and bigints', async () => {
66
+ const rows = await runTransform(
67
+ { users: { is_active: 'bool', has_pets: 'bool' } },
68
+ [{ is_active: 1, has_pets: 0n }]
69
+ )
70
+ assert.equal(rows[0]!.is_active, true)
71
+ assert.equal(rows[0]!.has_pets, false)
72
+ })
73
+
74
+ test('parses json columns and tolerates invalid json', async () => {
75
+ const rows = await runTransform(
76
+ { users: { meta: 'json', broken: 'json' } },
77
+ [{ meta: '{"a":1}', broken: '{bad' }]
78
+ )
79
+ assert.deepEqual(rows[0]!.meta, { a: 1 })
80
+ assert.equal(rows[0]!.broken, '{bad')
81
+ })
82
+
83
+ test('passes through null values and unmapped columns', async () => {
84
+ const rows = await runTransform({ users: { created_at: 'date' } }, [
85
+ { created_at: null, name: 'leave me' },
86
+ ])
87
+ assert.equal(rows[0]!.created_at, null)
88
+ assert.equal(rows[0]!.name, 'leave me')
89
+ })
90
+
91
+ test('matches both snake_case and camelCase column names', async () => {
92
+ const rows = await runTransform({ users: { created_at: 'date' } }, [
93
+ { createdAt: '2026-06-26T00:00:00.000Z' },
94
+ ])
95
+ assert.ok(rows[0]!.createdAt instanceof Date)
96
+ })
97
+
98
+ test('leaves columns ambiguous across tables uncoerced', async () => {
99
+ const rows = await runTransform(
100
+ { users: { value: 'json' }, events: { value: 'bool' } },
101
+ [{ value: '{"a":1}' }]
102
+ )
103
+ assert.equal(rows[0]!.value, '{"a":1}')
104
+ })
105
+
106
+ test('still coerces columns that agree across tables', async () => {
107
+ const rows = await runTransform(
108
+ { users: { active: 'bool' }, events: { active: 'bool' } },
109
+ [{ active: 1 }]
110
+ )
111
+ assert.equal(rows[0]!.active, true)
112
+ })
113
+
114
+ test('uses table-qualified coercions when names collide', async () => {
115
+ const map: CoercionMap = {
116
+ users: { settings: 'json' },
117
+ posts: { settings: 'bool' },
118
+ }
119
+ const fromUsers = await runTransform(
120
+ map,
121
+ [{ settings: '{"theme":"dark"}' }],
122
+ selectFrom('users')
123
+ )
124
+ assert.deepEqual(fromUsers[0]!.settings, { theme: 'dark' })
125
+
126
+ const fromPosts = await runTransform(
127
+ map,
128
+ [{ settings: 1 }],
129
+ selectFrom('posts')
130
+ )
131
+ assert.equal(fromPosts[0]!.settings, true)
132
+ })
133
+
134
+ test('table-qualified lookup matches camelCase result columns too', async () => {
135
+ const rows = await runTransform(
136
+ { users: { created_at: 'date' }, jobs: { created_at: 'json' } },
137
+ [{ createdAt: '2026-06-26T00:00:00.000Z' }],
138
+ selectFrom('users')
139
+ )
140
+ assert.ok(rows[0]!.createdAt instanceof Date)
141
+ })
142
+
143
+ test('a join whose tables disagree leaves the column uncoerced', async () => {
144
+ const rows = await runTransform(
145
+ { users: { value: 'json' }, events: { value: 'bool' } },
146
+ [{ value: '{"a":1}' }],
147
+ selectFrom('users', 'events')
148
+ )
149
+ assert.equal(rows[0]!.value, '{"a":1}')
150
+ })
151
+
152
+ test('falls back to flat keys when the query names no known table', async () => {
153
+ const rows = await runTransform(
154
+ { users: { created_at: 'date' } },
155
+ [{ createdAt: '2026-01-02T03:04:05.000Z' }],
156
+ selectFrom('unrelated')
157
+ )
158
+ assert.ok(rows[0]!.createdAt instanceof Date)
159
+ })
160
+ })
@@ -0,0 +1,187 @@
1
+ import type { KyselyPlugin, RootOperationNode, UnknownRow } from 'kysely'
2
+
3
+ /**
4
+ * The kinds a column can be coerced *to* at runtime. This is the value type of
5
+ * the generated `CoercionMap`, so it is a public artifact contract — a kind may
6
+ * only appear here if `fromDb` below actually does something with it.
7
+ *
8
+ * `uuid` is deliberately absent: it is an annotation kind (it selects the `Uuid`
9
+ * TypeScript type in the generated schema) but not a coercion kind, and the
10
+ * codegen filters it out of `coercion.gen.ts` for exactly that reason — a UUID
11
+ * is a string in both Postgres and SQLite.
12
+ */
13
+ export type ColumnKind = 'date' | 'bool' | 'json'
14
+
15
+ /**
16
+ * Per-table column kind map. Keys are the table names queries are written
17
+ * against; inner keys are snake_case column names.
18
+ * Generated into `outDir/db/coercion.gen.ts` by `pikku db migrate` from the
19
+ * explicit `kind` entries in `db/annotations.ts`.
20
+ */
21
+ export type CoercionMap = Record<string, Record<string, ColumnKind>>
22
+
23
+ export interface CreateCoercionPluginOptions {
24
+ map: CoercionMap
25
+ }
26
+
27
+ function fromDb(value: unknown, kind: ColumnKind): unknown {
28
+ if (value == null) return value
29
+ switch (kind) {
30
+ case 'date':
31
+ if (typeof value === 'string') {
32
+ const d = new Date(value)
33
+ return Number.isNaN(d.getTime()) ? value : d
34
+ }
35
+ return value
36
+ case 'bool':
37
+ if (typeof value === 'number') return value !== 0
38
+ if (typeof value === 'bigint') return value !== 0n
39
+ return value
40
+ case 'json':
41
+ if (typeof value !== 'string') return value
42
+ try {
43
+ return JSON.parse(value)
44
+ } catch {
45
+ return value
46
+ }
47
+ }
48
+ }
49
+
50
+ function snakeToCamel(name: string): string {
51
+ return name.replace(/_([a-z])/g, (_, c) => c.toUpperCase())
52
+ }
53
+
54
+ interface ResolvedMaps {
55
+ /** `table.column` → kind, for the exact per-query resolution. */
56
+ qualified: Record<string, ColumnKind>
57
+ /** `column` → kind, the fallback for when the query's tables say nothing. */
58
+ flat: Record<string, ColumnKind>
59
+ }
60
+
61
+ /**
62
+ * Flatten the per-table map into a table-qualified lookup plus a bare
63
+ * column-name fallback. Both are indexed by BOTH snake_case and camelCase so
64
+ * they work regardless of CamelCasePlugin ordering in the plugin array.
65
+ *
66
+ * When two tables disagree on the kind for the same column name, the bare name
67
+ * is ambiguous (a joined/aliased query could carry either) and is dropped from
68
+ * the flat map rather than letting whichever table was processed last win. The
69
+ * qualified map still resolves it whenever the query names its tables.
70
+ */
71
+ function buildMaps(map: CoercionMap): ResolvedMaps {
72
+ const qualified: Record<string, ColumnKind> = {}
73
+ const flat: Record<string, ColumnKind> = {}
74
+ const ambiguous = new Set<string>()
75
+ const assignFlat = (key: string, kind: ColumnKind) => {
76
+ const existing = flat[key]
77
+ if (existing !== undefined && existing !== kind) {
78
+ ambiguous.add(key)
79
+ return
80
+ }
81
+ flat[key] = kind
82
+ }
83
+ for (const [table, cols] of Object.entries(map)) {
84
+ for (const [col, kind] of Object.entries(cols)) {
85
+ const camel = snakeToCamel(col)
86
+ qualified[`${table}.${col}`] = kind
87
+ qualified[`${table}.${camel}`] = kind
88
+ assignFlat(col, kind)
89
+ assignFlat(camel, kind)
90
+ }
91
+ }
92
+ for (const key of ambiguous) delete flat[key]
93
+ return { qualified, flat }
94
+ }
95
+
96
+ /**
97
+ * Collect every table named anywhere in the query's operation node, so a result
98
+ * column can be resolved against the tables the query actually touched instead
99
+ * of against every table in the schema.
100
+ */
101
+ function collectQueryTables(node: unknown, out: Set<string>): void {
102
+ if (!node || typeof node !== 'object') return
103
+
104
+ const op = node as {
105
+ kind?: string
106
+ table?: { identifier?: { name?: string } }
107
+ }
108
+ if (op.kind === 'TableNode') {
109
+ const tableName = op.table?.identifier?.name
110
+ if (typeof tableName === 'string' && tableName.length > 0)
111
+ out.add(tableName)
112
+ }
113
+
114
+ for (const value of Object.values(node)) {
115
+ if (Array.isArray(value)) {
116
+ for (const item of value) collectQueryTables(item, out)
117
+ } else {
118
+ collectQueryTables(value, out)
119
+ }
120
+ }
121
+ }
122
+
123
+ /**
124
+ * Resolve a result column's kind against the query's tables, falling back to
125
+ * the bare column name. Tables that disagree with each other are as ambiguous
126
+ * as two schema tables are, so they fall back too.
127
+ */
128
+ function lookupKind(
129
+ maps: ResolvedMaps,
130
+ tables: readonly string[],
131
+ col: string
132
+ ): ColumnKind | undefined {
133
+ let matchedKind: ColumnKind | undefined
134
+ for (const table of tables) {
135
+ const kind = maps.qualified[`${table}.${col}`]
136
+ if (!kind) continue
137
+ if (matchedKind && matchedKind !== kind) return maps.flat[col]
138
+ matchedKind = kind
139
+ }
140
+ return matchedKind ?? maps.flat[col]
141
+ }
142
+
143
+ /**
144
+ * Convert values stored in a dialect's on-disk representation back into the
145
+ * logical types app code expects (Date / boolean / parsed JSON).
146
+ *
147
+ * SQLite is what makes this necessary — it stores dates as TEXT, booleans as
148
+ * INTEGER and JSON as TEXT — but the plugin is dialect-neutral: on Postgres the
149
+ * driver already returns Date/boolean/object, and every branch of `fromDb`
150
+ * passes a non-string, non-number value straight through. That is why it lives
151
+ * in `@pikku/kysely` next to `SerializePlugin` rather than in a SQLite package:
152
+ * the CLI installs it on its local Postgres database too.
153
+ *
154
+ * Write-side coercion (Date → ISO string, boolean → 0/1, object → JSON) is
155
+ * handled in the SQLite database adapters (always-on), so this plugin is
156
+ * read-only.
157
+ *
158
+ * Place AFTER CamelCasePlugin in the plugin array (or it handles both
159
+ * orderings via the dual-keyed maps).
160
+ */
161
+ export function createCoercionPlugin(
162
+ options: CreateCoercionPluginOptions
163
+ ): KyselyPlugin {
164
+ const maps = buildMaps(options.map)
165
+ const queryTables = new WeakMap<object, readonly string[]>()
166
+ return {
167
+ transformQuery(args) {
168
+ const tables = new Set<string>()
169
+ collectQueryTables(args.node as RootOperationNode, tables)
170
+ queryTables.set(args.queryId, [...tables])
171
+ return args.node
172
+ },
173
+ async transformResult(args) {
174
+ const tables = queryTables.get(args.queryId) ?? []
175
+ const out: UnknownRow[] = []
176
+ for (const row of args.result.rows as UnknownRow[]) {
177
+ const next: UnknownRow = { ...row }
178
+ for (const [col, val] of Object.entries(row)) {
179
+ const kind = lookupKind(maps, tables, col)
180
+ if (kind) next[col] = fromDb(val, kind)
181
+ }
182
+ out.push(next)
183
+ }
184
+ return { ...args.result, rows: out }
185
+ },
186
+ }
187
+ }
@@ -7,7 +7,7 @@ import {
7
7
  NoopAuditService,
8
8
  type AuditEvent,
9
9
  type AuditService,
10
- } from '../../../core/src/index.js'
10
+ } from '@pikku/core/services'
11
11
 
12
12
  import { createAuditedKysely } from './create-audited-kysely.js'
13
13
 
@@ -1,4 +1,4 @@
1
- import type { AuditLog } from '@pikku/core'
1
+ import type { AuditLog } from '@pikku/core/services'
2
2
  import type {
3
3
  Kysely,
4
4
  KyselyPlugin,
package/src/index.ts CHANGED
@@ -4,9 +4,9 @@ export { KyselyWorkflowService } from './kysely-workflow-service.js'
4
4
  export { KyselyWorkflowRunService } from './kysely-workflow-run-service.js'
5
5
  export { KyselyWorkflowMirror } from './kysely-workflow-mirror.js'
6
6
  export { KyselyDeploymentService } from './kysely-deployment-service.js'
7
- export { KyselyAIStorageService } from './kysely-ai-storage-service.js'
8
- export { KyselyAgentRunService } from './kysely-ai-agent-run-service.js'
9
- export { KyselyAIRunStateService } from './kysely-ai-run-state-service.js'
7
+ export { KyselyAgentStorageService } from './kysely-agent-storage-service.js'
8
+ export { KyselyAgentRunService } from './kysely-agent-run-service.js'
9
+ export { KyselyAgentRunStateService } from './kysely-agent-run-state-service.js'
10
10
  export { KyselySecretService } from './kysely-secret-service.js'
11
11
  export { KyselyCredentialService } from './kysely-credential-service.js'
12
12
  export { KyselySessionStore } from './kysely-session-store.js'
@@ -21,11 +21,16 @@ export { KyselyVirtualUserRunStore } from './kysely-virtual-user-run-store.js'
21
21
 
22
22
  export {
23
23
  SerializePlugin,
24
- SqliteSerializePlugin,
25
24
  BaseSerializePlugin,
26
25
  type Serializer,
27
26
  type Deserializer,
28
27
  } from './serialize-plugin.js'
28
+ export {
29
+ createCoercionPlugin,
30
+ type ColumnKind,
31
+ type CoercionMap,
32
+ type CreateCoercionPluginOptions,
33
+ } from './coercion-plugin.js'
29
34
  export {
30
35
  auditSchema,
31
36
  pikkuSchemas,
@@ -42,7 +47,7 @@ export {
42
47
 
43
48
  export type { KyselyPikkuDB } from './kysely-tables.js'
44
49
  export type { WorkflowRunService } from '@pikku/core/workflow'
45
- export type { AgentRunService, AgentRunRow } from '@pikku/core/ai-agent'
50
+ export type { AgentRunService, AgentRunRow } from '@pikku/core/agent'
46
51
  export type {
47
52
  VirtualUserRunStore,
48
53
  VirtualUserRunRecord,
@@ -1,11 +1,11 @@
1
1
  import type { Kysely } from 'kysely'
2
2
  import type { KyselyPikkuDB } from './kysely-tables.js'
3
+ import type { AgentRunScore } from '@pikku/core/agent-scorer'
3
4
  import type { SaveScoreInput } from '@pikku/core/services'
4
- import type { AIRunScore } from '@pikku/core/ai-scorer'
5
5
  import { parseJson } from './kysely-json.js'
6
6
 
7
7
  /**
8
- * Shared by the two Kysely services that implement `AIRunStateService` — they
8
+ * Shared by the two Kysely services that implement `AgentRunStateService` — they
9
9
  * differ in how they store approvals, not in how they store grades.
10
10
  */
11
11
  export const saveRunScore = async (
@@ -13,7 +13,7 @@ export const saveRunScore = async (
13
13
  score: SaveScoreInput
14
14
  ): Promise<void> => {
15
15
  await db
16
- .insertInto('aiRunScore')
16
+ .insertInto('agentRunScore')
17
17
  .values({
18
18
  id: crypto.randomUUID(),
19
19
  runId: score.runId,
@@ -28,9 +28,9 @@ export const saveRunScore = async (
28
28
  export const getRunScores = async (
29
29
  db: Kysely<KyselyPikkuDB>,
30
30
  runId: string
31
- ): Promise<AIRunScore[]> => {
31
+ ): Promise<AgentRunScore[]> => {
32
32
  const rows = await db
33
- .selectFrom('aiRunScore')
33
+ .selectFrom('agentRunScore')
34
34
  .selectAll()
35
35
  .where('runId', '=', runId)
36
36
  .orderBy('createdAt', 'asc')