@ontrails/core 1.0.0-beta.3 → 1.0.0-beta.30

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 (245) hide show
  1. package/CHANGELOG.md +305 -8
  2. package/README.md +114 -33
  3. package/package.json +11 -1
  4. package/src/activation-provenance.ts +111 -0
  5. package/src/activation-source-compatibility.ts +430 -0
  6. package/src/activation-source-projection.ts +221 -0
  7. package/src/activation-source.ts +91 -0
  8. package/src/blob-ref.ts +51 -0
  9. package/src/branded.ts +1 -1
  10. package/src/compose-batch.ts +69 -0
  11. package/src/compose-schema.ts +36 -0
  12. package/src/context.ts +44 -10
  13. package/src/contour.ts +346 -0
  14. package/src/derive.ts +241 -16
  15. package/src/detours.ts +8 -0
  16. package/src/draft.ts +342 -0
  17. package/src/error-projection.ts +51 -0
  18. package/src/errors.ts +335 -48
  19. package/src/execute.ts +1577 -0
  20. package/src/fire.ts +1169 -0
  21. package/src/index.ts +495 -34
  22. package/src/internal/fork-ctx.ts +69 -0
  23. package/src/layer-projection.ts +193 -0
  24. package/src/layer.ts +43 -6
  25. package/src/observe.ts +361 -0
  26. package/src/path-security.ts +1 -1
  27. package/src/permits.ts +12 -0
  28. package/src/redaction/patterns.ts +6 -3
  29. package/src/resilience.ts +11 -11
  30. package/src/resource-config.ts +792 -0
  31. package/src/resource.ts +194 -0
  32. package/src/result.ts +18 -0
  33. package/src/run.ts +76 -0
  34. package/src/schedule-runtime.ts +689 -0
  35. package/src/schedule.ts +326 -0
  36. package/src/serialization.ts +92 -55
  37. package/src/signal-diagnostics.ts +633 -0
  38. package/src/signal-ref.ts +87 -0
  39. package/src/signal.ts +104 -0
  40. package/src/store/accessor-protocol.ts +56 -0
  41. package/src/store/index.ts +4 -0
  42. package/src/structured-examples.ts +248 -0
  43. package/src/surface-derivation.ts +91 -0
  44. package/src/surface-filter.ts +176 -0
  45. package/src/surface-versioning.ts +42 -0
  46. package/src/topo.ts +769 -67
  47. package/src/tracing.ts +345 -0
  48. package/src/trail.ts +1168 -30
  49. package/src/trails/derive-trail.ts +842 -0
  50. package/src/trails/index.ts +9 -0
  51. package/src/trails/ingest.ts +139 -0
  52. package/src/trails-db.ts +206 -0
  53. package/src/transport-error-map.ts +174 -0
  54. package/src/type-utils.ts +87 -0
  55. package/src/types.ts +254 -12
  56. package/src/validate-established-topo.ts +69 -0
  57. package/src/validate-topo.ts +393 -45
  58. package/src/validation.ts +152 -4
  59. package/src/version-marker.ts +716 -0
  60. package/src/version-resolution.ts +308 -0
  61. package/src/version-runtime.ts +120 -0
  62. package/src/webhook.ts +278 -0
  63. package/src/workspace.ts +1 -1
  64. package/src/zod-wrappers.ts +72 -0
  65. package/.turbo/turbo-build.log +0 -1
  66. package/.turbo/turbo-lint.log +0 -3
  67. package/.turbo/turbo-typecheck.log +0 -1
  68. package/dist/adapters.d.ts +0 -39
  69. package/dist/adapters.d.ts.map +0 -1
  70. package/dist/adapters.js +0 -2
  71. package/dist/adapters.js.map +0 -1
  72. package/dist/blob-ref.d.ts +0 -20
  73. package/dist/blob-ref.d.ts.map +0 -1
  74. package/dist/blob-ref.js +0 -22
  75. package/dist/blob-ref.js.map +0 -1
  76. package/dist/branded.d.ts +0 -36
  77. package/dist/branded.d.ts.map +0 -1
  78. package/dist/branded.js +0 -89
  79. package/dist/branded.js.map +0 -1
  80. package/dist/collections.d.ts +0 -31
  81. package/dist/collections.d.ts.map +0 -1
  82. package/dist/collections.js +0 -60
  83. package/dist/collections.js.map +0 -1
  84. package/dist/context.d.ts +0 -10
  85. package/dist/context.d.ts.map +0 -1
  86. package/dist/context.js +0 -15
  87. package/dist/context.js.map +0 -1
  88. package/dist/derive.d.ts +0 -33
  89. package/dist/derive.d.ts.map +0 -1
  90. package/dist/derive.js +0 -125
  91. package/dist/derive.js.map +0 -1
  92. package/dist/errors.d.ts +0 -83
  93. package/dist/errors.d.ts.map +0 -1
  94. package/dist/errors.js +0 -142
  95. package/dist/errors.js.map +0 -1
  96. package/dist/event.d.ts +0 -45
  97. package/dist/event.d.ts.map +0 -1
  98. package/dist/event.js +0 -17
  99. package/dist/event.js.map +0 -1
  100. package/dist/fetch.d.ts +0 -15
  101. package/dist/fetch.d.ts.map +0 -1
  102. package/dist/fetch.js +0 -102
  103. package/dist/fetch.js.map +0 -1
  104. package/dist/guards.d.ts +0 -17
  105. package/dist/guards.d.ts.map +0 -1
  106. package/dist/guards.js +0 -25
  107. package/dist/guards.js.map +0 -1
  108. package/dist/health.d.ts +0 -18
  109. package/dist/health.d.ts.map +0 -1
  110. package/dist/health.js +0 -5
  111. package/dist/health.js.map +0 -1
  112. package/dist/hike.d.ts +0 -36
  113. package/dist/hike.d.ts.map +0 -1
  114. package/dist/hike.js +0 -20
  115. package/dist/hike.js.map +0 -1
  116. package/dist/index.d.ts +0 -36
  117. package/dist/index.d.ts.map +0 -1
  118. package/dist/index.js +0 -40
  119. package/dist/index.js.map +0 -1
  120. package/dist/job.d.ts +0 -24
  121. package/dist/job.d.ts.map +0 -1
  122. package/dist/job.js +0 -17
  123. package/dist/job.js.map +0 -1
  124. package/dist/layer.d.ts +0 -17
  125. package/dist/layer.d.ts.map +0 -1
  126. package/dist/layer.js +0 -21
  127. package/dist/layer.js.map +0 -1
  128. package/dist/path-security.d.ts +0 -28
  129. package/dist/path-security.d.ts.map +0 -1
  130. package/dist/path-security.js +0 -63
  131. package/dist/path-security.js.map +0 -1
  132. package/dist/patterns/bulk.d.ts +0 -15
  133. package/dist/patterns/bulk.d.ts.map +0 -1
  134. package/dist/patterns/bulk.js +0 -14
  135. package/dist/patterns/bulk.js.map +0 -1
  136. package/dist/patterns/change.d.ts +0 -10
  137. package/dist/patterns/change.d.ts.map +0 -1
  138. package/dist/patterns/change.js +0 -10
  139. package/dist/patterns/change.js.map +0 -1
  140. package/dist/patterns/date-range.d.ts +0 -10
  141. package/dist/patterns/date-range.d.ts.map +0 -1
  142. package/dist/patterns/date-range.js +0 -10
  143. package/dist/patterns/date-range.js.map +0 -1
  144. package/dist/patterns/index.d.ts +0 -9
  145. package/dist/patterns/index.d.ts.map +0 -1
  146. package/dist/patterns/index.js +0 -9
  147. package/dist/patterns/index.js.map +0 -1
  148. package/dist/patterns/pagination.d.ts +0 -18
  149. package/dist/patterns/pagination.d.ts.map +0 -1
  150. package/dist/patterns/pagination.js +0 -18
  151. package/dist/patterns/pagination.js.map +0 -1
  152. package/dist/patterns/progress.d.ts +0 -11
  153. package/dist/patterns/progress.d.ts.map +0 -1
  154. package/dist/patterns/progress.js +0 -11
  155. package/dist/patterns/progress.js.map +0 -1
  156. package/dist/patterns/sorting.d.ts +0 -13
  157. package/dist/patterns/sorting.d.ts.map +0 -1
  158. package/dist/patterns/sorting.js +0 -10
  159. package/dist/patterns/sorting.js.map +0 -1
  160. package/dist/patterns/status.d.ts +0 -15
  161. package/dist/patterns/status.d.ts.map +0 -1
  162. package/dist/patterns/status.js +0 -9
  163. package/dist/patterns/status.js.map +0 -1
  164. package/dist/patterns/timestamps.d.ts +0 -10
  165. package/dist/patterns/timestamps.d.ts.map +0 -1
  166. package/dist/patterns/timestamps.js +0 -10
  167. package/dist/patterns/timestamps.js.map +0 -1
  168. package/dist/redaction/index.d.ts +0 -4
  169. package/dist/redaction/index.d.ts.map +0 -1
  170. package/dist/redaction/index.js +0 -3
  171. package/dist/redaction/index.js.map +0 -1
  172. package/dist/redaction/patterns.d.ts +0 -9
  173. package/dist/redaction/patterns.d.ts.map +0 -1
  174. package/dist/redaction/patterns.js +0 -39
  175. package/dist/redaction/patterns.js.map +0 -1
  176. package/dist/redaction/redactor.d.ts +0 -27
  177. package/dist/redaction/redactor.d.ts.map +0 -1
  178. package/dist/redaction/redactor.js +0 -89
  179. package/dist/redaction/redactor.js.map +0 -1
  180. package/dist/resilience.d.ts +0 -34
  181. package/dist/resilience.d.ts.map +0 -1
  182. package/dist/resilience.js +0 -164
  183. package/dist/resilience.js.map +0 -1
  184. package/dist/result.d.ts +0 -57
  185. package/dist/result.d.ts.map +0 -1
  186. package/dist/result.js +0 -156
  187. package/dist/result.js.map +0 -1
  188. package/dist/serialization.d.ts +0 -27
  189. package/dist/serialization.d.ts.map +0 -1
  190. package/dist/serialization.js +0 -153
  191. package/dist/serialization.js.map +0 -1
  192. package/dist/topo.d.ts +0 -18
  193. package/dist/topo.d.ts.map +0 -1
  194. package/dist/topo.js +0 -80
  195. package/dist/topo.js.map +0 -1
  196. package/dist/trail.d.ts +0 -83
  197. package/dist/trail.d.ts.map +0 -1
  198. package/dist/trail.js +0 -16
  199. package/dist/trail.js.map +0 -1
  200. package/dist/types.d.ts +0 -46
  201. package/dist/types.d.ts.map +0 -1
  202. package/dist/types.js +0 -2
  203. package/dist/types.js.map +0 -1
  204. package/dist/validate-topo.d.ts +0 -24
  205. package/dist/validate-topo.d.ts.map +0 -1
  206. package/dist/validate-topo.js +0 -156
  207. package/dist/validate-topo.js.map +0 -1
  208. package/dist/validation.d.ts +0 -27
  209. package/dist/validation.d.ts.map +0 -1
  210. package/dist/validation.js +0 -134
  211. package/dist/validation.js.map +0 -1
  212. package/dist/workspace.d.ts +0 -25
  213. package/dist/workspace.d.ts.map +0 -1
  214. package/dist/workspace.js +0 -57
  215. package/dist/workspace.js.map +0 -1
  216. package/src/__tests__/blob-ref.test.ts +0 -103
  217. package/src/__tests__/branded.test.ts +0 -148
  218. package/src/__tests__/collections.test.ts +0 -126
  219. package/src/__tests__/context.test.ts +0 -66
  220. package/src/__tests__/derive.test.ts +0 -203
  221. package/src/__tests__/errors.test.ts +0 -309
  222. package/src/__tests__/event.test.ts +0 -82
  223. package/src/__tests__/fetch.test.ts +0 -217
  224. package/src/__tests__/guards.test.ts +0 -102
  225. package/src/__tests__/hike.test.ts +0 -117
  226. package/src/__tests__/job.test.ts +0 -98
  227. package/src/__tests__/layer.test.ts +0 -224
  228. package/src/__tests__/path-security.test.ts +0 -114
  229. package/src/__tests__/patterns.test.ts +0 -273
  230. package/src/__tests__/redaction.test.ts +0 -244
  231. package/src/__tests__/resilience.test.ts +0 -246
  232. package/src/__tests__/result.test.ts +0 -155
  233. package/src/__tests__/serialization.test.ts +0 -401
  234. package/src/__tests__/topo.test.ts +0 -220
  235. package/src/__tests__/trail.test.ts +0 -179
  236. package/src/__tests__/validate-topo.test.ts +0 -280
  237. package/src/__tests__/validation.test.ts +0 -283
  238. package/src/__tests__/workspace.test.ts +0 -183
  239. package/src/adapters.ts +0 -68
  240. package/src/event.ts +0 -77
  241. package/src/health.ts +0 -23
  242. package/src/hike.ts +0 -77
  243. package/src/job.ts +0 -20
  244. package/tsconfig.json +0 -9
  245. package/tsconfig.tsbuildinfo +0 -1
@@ -0,0 +1,9 @@
1
+ export { deriveTrail } from './derive-trail.js';
2
+ export type {
3
+ DeriveTrailInput,
4
+ DeriveTrailOperation,
5
+ DeriveTrailOutput,
6
+ DeriveTrailSpec,
7
+ } from './derive-trail.js';
8
+ export { ingest } from './ingest.js';
9
+ export type { IngestOptions, IngestTransform } from './ingest.js';
@@ -0,0 +1,139 @@
1
+ import { z } from 'zod';
2
+
3
+ import { InternalError } from '../errors.js';
4
+ import { composeLayers } from '../layer.js';
5
+ import type { Layer } from '../layer.js';
6
+ import { Result } from '../result.js';
7
+ import type { Signal } from '../signal.js';
8
+ import { trail } from '../trail.js';
9
+ import type { Trail, TrailExample, TrailSpec } from '../trail.js';
10
+ import type { TrailContext } from '../types.js';
11
+
12
+ type SchemaValue<TSchema extends z.ZodType> = z.output<TSchema>;
13
+
14
+ type ExampleBearingSchema<TSchema extends z.ZodType> = TSchema & {
15
+ readonly examples?: readonly Partial<SchemaValue<TSchema>>[] | undefined;
16
+ };
17
+
18
+ interface IngestBaseOptions<TSchema extends z.ZodType, TSignal> extends Omit<
19
+ TrailSpec<SchemaValue<TSchema>, void>,
20
+ 'blaze' | 'examples' | 'fires' | 'input' | 'intent' | 'output' | 'pattern'
21
+ > {
22
+ /** Override the derived trail id. Defaults to `${signal}.ingest`. */
23
+ readonly id?: string | undefined;
24
+ /** Validated external payload shape. */
25
+ readonly schema: TSchema;
26
+ /** Signal to fire after verification and optional transformation. */
27
+ readonly signal: Signal<TSignal>;
28
+ /** Optional per-trail verification layer, e.g. HMAC signature checks. */
29
+ readonly verify?: Layer | undefined;
30
+ }
31
+
32
+ export type IngestTransform<TInput, TSignal> = (
33
+ payload: TInput,
34
+ ctx: TrailContext
35
+ ) => TSignal | Promise<TSignal>;
36
+
37
+ export interface IngestOptions<
38
+ TSchema extends z.ZodType,
39
+ TSignal,
40
+ > extends IngestBaseOptions<TSchema, TSignal> {
41
+ readonly transform?:
42
+ | IngestTransform<SchemaValue<TSchema>, TSignal>
43
+ | undefined;
44
+ }
45
+
46
+ const deriveExampleName = (signalId: string, index: number): string =>
47
+ `Ingest ${signalId} ${index + 1}`;
48
+
49
+ const deriveExamples = <TSchema extends z.ZodType>(
50
+ schema: ExampleBearingSchema<TSchema>,
51
+ signalId: string
52
+ ): readonly TrailExample<SchemaValue<TSchema>, void>[] | undefined => {
53
+ const { examples } = schema;
54
+ if (examples === undefined || examples.length === 0) {
55
+ return undefined;
56
+ }
57
+
58
+ return Object.freeze(
59
+ examples.map((example, index) => ({
60
+ input: example,
61
+ name: deriveExampleName(signalId, index),
62
+ }))
63
+ );
64
+ };
65
+
66
+ const createIngestBlaze =
67
+ <TSchema extends z.ZodType, TSignal>(
68
+ signalRef: Signal<TSignal>,
69
+ signalId: string,
70
+ trailId: string,
71
+ transform: IngestTransform<SchemaValue<TSchema>, TSignal> | undefined
72
+ ) =>
73
+ async (
74
+ input: SchemaValue<TSchema>,
75
+ ctx: TrailContext
76
+ ): Promise<Result<void, Error>> => {
77
+ if (ctx.fire === undefined) {
78
+ return Result.err(
79
+ new InternalError(
80
+ `ingest("${trailId}") requires topo-backed execution to fire "${signalId}"`
81
+ )
82
+ );
83
+ }
84
+
85
+ try {
86
+ const payload =
87
+ transform === undefined
88
+ ? (input as TSignal)
89
+ : await transform(input, ctx);
90
+ await ctx.fire(signalRef, payload);
91
+ return Result.ok();
92
+ } catch (error) {
93
+ const message = `ingest("${trailId}"): ${error instanceof Error ? error.message : String(error)}`;
94
+ return Result.err(
95
+ error instanceof Error
96
+ ? new InternalError(message, { cause: error })
97
+ : new InternalError(message)
98
+ );
99
+ }
100
+ };
101
+
102
+ export const ingest = <
103
+ TSchema extends z.ZodType,
104
+ TSignal = SchemaValue<TSchema>,
105
+ >(
106
+ options: IngestOptions<TSchema, TSignal>
107
+ ): Trail<SchemaValue<TSchema>, void> => {
108
+ const signalId = options.signal.id;
109
+ const id = options.id ?? `${signalId}.ingest`;
110
+ const { id: _id, schema, signal, transform, verify, ...trailSpec } = options;
111
+ const baseBlaze = createIngestBlaze<TSchema, TSignal>(
112
+ signal,
113
+ signalId,
114
+ id,
115
+ transform
116
+ );
117
+ const baseSpec = {
118
+ ...trailSpec,
119
+ blaze: baseBlaze as TrailSpec<unknown, unknown>['blaze'],
120
+ examples: deriveExamples(schema as ExampleBearingSchema<TSchema>, signalId),
121
+ fires: [signal],
122
+ input: schema as z.ZodType<unknown>,
123
+ intent: 'write',
124
+ output: z.void(),
125
+ pattern: 'ingest',
126
+ } as TrailSpec<unknown, unknown>;
127
+ const baseTrail = trail(id, baseSpec) as Trail<SchemaValue<TSchema>, void>;
128
+
129
+ if (verify === undefined) {
130
+ return baseTrail;
131
+ }
132
+
133
+ // Verification is a per-factory concern, so compose it locally instead of
134
+ // mutating runner-wide layer configuration.
135
+ return Object.freeze({
136
+ ...baseTrail,
137
+ blaze: composeLayers([verify], baseTrail, baseTrail.blaze),
138
+ }) as Trail<SchemaValue<TSchema>, void>;
139
+ };
@@ -0,0 +1,206 @@
1
+ import { Database } from 'bun:sqlite';
2
+ import { createHash } from 'node:crypto';
3
+ import { existsSync, mkdirSync } from 'node:fs';
4
+ import { homedir } from 'node:os';
5
+ import { basename, dirname, join, resolve } from 'node:path';
6
+
7
+ import { NotFoundError } from './errors.js';
8
+
9
+ const TRAILS_DIR = '.trails';
10
+ const TRAILS_DB_FILE = 'trails.db';
11
+ const TRAILS_STORE_DIR = 'trails';
12
+ const TRAILS_PROJECTS_DIR = 'projects';
13
+ const SCHEMA_VERSION_TABLE = 'meta_schema_versions';
14
+ const SQLITE_BUSY_TIMEOUT_MS = 5000;
15
+ const PROJECT_KEY_HASH_LENGTH = 16;
16
+ const PROJECT_KEY_NAME_FALLBACK = 'project';
17
+
18
+ /**
19
+ * Legacy no-op compatibility export.
20
+ *
21
+ * `.trails/` is committed project control, not disposable cache/state. New
22
+ * code should not write a `.trails/.gitignore`; keep this export available for
23
+ * older callers during the pre-1.0 cutover.
24
+ */
25
+ export const WORKSPACE_GITIGNORE_LINES = [] as const;
26
+
27
+ /**
28
+ * Legacy no-op compatibility export. See {@link WORKSPACE_GITIGNORE_LINES}.
29
+ */
30
+ export const WORKSPACE_GITIGNORE_CONTENT = '';
31
+
32
+ export interface TrailsDbLocationOptions {
33
+ readonly env?: Record<string, string | undefined>;
34
+ readonly path?: string;
35
+ readonly rootDir?: string;
36
+ }
37
+
38
+ export interface EnsureSubsystemSchemaOptions {
39
+ readonly migrate: (currentVersion: number) => void;
40
+ readonly subsystem: string;
41
+ readonly version: number;
42
+ }
43
+
44
+ interface SchemaVersionRow {
45
+ readonly version: number;
46
+ }
47
+
48
+ const deriveRootDir = (rootDir?: string): string =>
49
+ resolve(rootDir ?? process.cwd());
50
+
51
+ const sanitizeProjectKeyName = (name: string): string => {
52
+ const normalized = name.replaceAll(/[^a-zA-Z0-9._-]+/g, '-');
53
+ return normalized.length > 0 ? normalized : PROJECT_KEY_NAME_FALLBACK;
54
+ };
55
+
56
+ const projectHash = (rootDir: string): string =>
57
+ createHash('sha256')
58
+ .update(rootDir)
59
+ .digest('hex')
60
+ .slice(0, PROJECT_KEY_HASH_LENGTH);
61
+
62
+ export const deriveTrailsProjectKey = (
63
+ options?: TrailsDbLocationOptions
64
+ ): string => {
65
+ const rootDir = deriveRootDir(options?.rootDir);
66
+ return `${sanitizeProjectKeyName(basename(rootDir))}-${projectHash(rootDir)}`;
67
+ };
68
+
69
+ export const deriveTrailsStateHome = (
70
+ options?: TrailsDbLocationOptions
71
+ ): string => {
72
+ const env = options?.env ?? process.env;
73
+ return resolve(
74
+ env['TRAILS_STATE_HOME'] ??
75
+ env['XDG_STATE_HOME'] ??
76
+ join(homedir(), '.local', 'state')
77
+ );
78
+ };
79
+
80
+ export const deriveTrailsStateDir = (
81
+ options?: TrailsDbLocationOptions
82
+ ): string =>
83
+ join(
84
+ deriveTrailsStateHome(options),
85
+ TRAILS_STORE_DIR,
86
+ TRAILS_PROJECTS_DIR,
87
+ deriveTrailsProjectKey(options)
88
+ );
89
+
90
+ export const deriveTrailsDir = (options?: TrailsDbLocationOptions): string =>
91
+ join(deriveRootDir(options?.rootDir), TRAILS_DIR);
92
+
93
+ export const deriveTrailsDbPath = (options?: TrailsDbLocationOptions): string =>
94
+ options?.path
95
+ ? resolve(options.path)
96
+ : join(deriveTrailsStateDir(options), TRAILS_DB_FILE);
97
+
98
+ const ensureDbParentDir = (dbPath: string): void => {
99
+ mkdirSync(dirname(dbPath), { recursive: true });
100
+ };
101
+
102
+ /**
103
+ * Bootstrap the `.trails/` workspace at `rootDir`.
104
+ *
105
+ * Creates only the committed-control directory. Derived cache and observed
106
+ * state live in the per-user Trails store, so this helper intentionally does
107
+ * not create `.trails/cache`, `.trails/state`, or `.trails/.gitignore`.
108
+ */
109
+ export const ensureTrailsWorkspace = (rootDir: string): void => {
110
+ const trailsDir = deriveTrailsDir({ rootDir });
111
+ mkdirSync(trailsDir, { recursive: true });
112
+ };
113
+
114
+ const initializeWritePragmas = (db: Database): void => {
115
+ db.run(`PRAGMA busy_timeout = ${SQLITE_BUSY_TIMEOUT_MS.toString()}`);
116
+ db.run('PRAGMA journal_mode = WAL');
117
+ db.run('PRAGMA synchronous = NORMAL');
118
+ db.run('PRAGMA foreign_keys = ON');
119
+ };
120
+
121
+ const initializeReadPragmas = (db: Database): void => {
122
+ db.run(`PRAGMA busy_timeout = ${SQLITE_BUSY_TIMEOUT_MS.toString()}`);
123
+ db.run('PRAGMA foreign_keys = ON');
124
+ };
125
+
126
+ const ensureSchemaVersionTable = (db: Database): void => {
127
+ db.run(`CREATE TABLE IF NOT EXISTS ${SCHEMA_VERSION_TABLE} (
128
+ subsystem TEXT PRIMARY KEY,
129
+ version INTEGER NOT NULL,
130
+ updated_at TEXT NOT NULL
131
+ )`);
132
+ };
133
+
134
+ const readSubsystemVersion = (db: Database, subsystem: string): number => {
135
+ const row = db
136
+ .query<SchemaVersionRow, [string]>(
137
+ `SELECT version FROM ${SCHEMA_VERSION_TABLE} WHERE subsystem = ?`
138
+ )
139
+ .get(subsystem);
140
+ return row?.version ?? 0;
141
+ };
142
+
143
+ const writeSubsystemVersion = (
144
+ db: Database,
145
+ subsystem: string,
146
+ version: number
147
+ ): void => {
148
+ db.run(
149
+ `INSERT INTO ${SCHEMA_VERSION_TABLE} (subsystem, version, updated_at)
150
+ VALUES (?, ?, ?)
151
+ ON CONFLICT(subsystem) DO UPDATE SET
152
+ version = excluded.version,
153
+ updated_at = excluded.updated_at`,
154
+ [subsystem, version, new Date().toISOString()]
155
+ );
156
+ };
157
+
158
+ export const openWriteTrailsDb = (
159
+ options?: TrailsDbLocationOptions
160
+ ): Database => {
161
+ const rootDir = deriveRootDir(options?.rootDir);
162
+ const locationOptions: TrailsDbLocationOptions = {
163
+ ...(options?.env === undefined ? {} : { env: options.env }),
164
+ ...(options?.path === undefined ? {} : { path: options.path }),
165
+ rootDir,
166
+ };
167
+ const dbPath = deriveTrailsDbPath(locationOptions);
168
+
169
+ ensureDbParentDir(dbPath);
170
+
171
+ const db = new Database(dbPath, { create: true });
172
+ initializeWritePragmas(db);
173
+ ensureSchemaVersionTable(db);
174
+ return db;
175
+ };
176
+
177
+ export const openReadTrailsDb = (
178
+ options?: TrailsDbLocationOptions
179
+ ): Database => {
180
+ const dbPath = deriveTrailsDbPath(options);
181
+ if (!existsSync(dbPath)) {
182
+ throw new NotFoundError(
183
+ `Trails database not found at "${dbPath}". Run a write operation first to initialize it.`
184
+ );
185
+ }
186
+ const db = new Database(dbPath, { readonly: true });
187
+ initializeReadPragmas(db);
188
+ return db;
189
+ };
190
+
191
+ export const ensureSubsystemSchema = (
192
+ db: Database,
193
+ options: EnsureSubsystemSchemaOptions
194
+ ): void => {
195
+ ensureSchemaVersionTable(db);
196
+
197
+ db.transaction(() => {
198
+ const currentVersion = readSubsystemVersion(db, options.subsystem);
199
+ if (currentVersion >= options.version) {
200
+ return;
201
+ }
202
+
203
+ options.migrate(currentVersion);
204
+ writeSubsystemVersion(db, options.subsystem, options.version);
205
+ })();
206
+ };
@@ -0,0 +1,174 @@
1
+ import type {
2
+ ErrorCategory,
3
+ ErrorCategoryCodes,
4
+ ErrorClassRegistryEntry,
5
+ FixedErrorClassRegistryEntry,
6
+ TrailsError,
7
+ } from './errors.js';
8
+ import {
9
+ codesByCategory,
10
+ errorClasses,
11
+ exitCodeMap,
12
+ isTrailsError,
13
+ jsonRpcCodeMap,
14
+ statusCodeMap,
15
+ } from './errors.js';
16
+ import {
17
+ INTERNAL_ERROR_PUBLIC_MESSAGE,
18
+ redactErrorString,
19
+ } from './error-projection.js';
20
+
21
+ export const surfaceNames = ['cli', 'http', 'jsonRpc', 'mcp'] as const;
22
+
23
+ export type SurfaceName = (typeof surfaceNames)[number];
24
+
25
+ const surfaceCodeKeys = {
26
+ cli: 'exit',
27
+ http: 'http',
28
+ jsonRpc: 'jsonRpc',
29
+ mcp: 'jsonRpc',
30
+ } as const satisfies Record<SurfaceName, keyof ErrorCategoryCodes>;
31
+
32
+ export type SurfaceErrorMapper<T> = (error: TrailsError) => T;
33
+
34
+ export type SurfaceErrorMappings<T> = Record<ErrorCategory, T>;
35
+
36
+ /**
37
+ * Union of every surface-specific error code emitted by {@link surfaceErrorMap}.
38
+ *
39
+ * @remarks
40
+ * Previously parameterized by surface (`SurfaceErrorCode<'cli'>` etc.), but
41
+ * the generic collapsed to `number` because the underlying maps were typed as
42
+ * `Record<ErrorCategory, number>`. With `as const satisfies` on the maps the
43
+ * per-surface literals are now observable, but TypeScript cannot narrow
44
+ * `surfaceErrorMap[surface][error.category]` through a generic `TSurface`
45
+ * without an unsound cast. The non-generic union honestly reflects what
46
+ * `mapSurfaceError` returns at the call site.
47
+ */
48
+ export type SurfaceErrorCode =
49
+ (typeof codesByCategory)[ErrorCategory][(typeof surfaceCodeKeys)[SurfaceName]];
50
+
51
+ export interface SurfaceErrorProjection {
52
+ readonly category: ErrorCategory;
53
+ readonly code: SurfaceErrorCode;
54
+ readonly message: string;
55
+ readonly name: string;
56
+ readonly retryable: boolean;
57
+ readonly surface: SurfaceName;
58
+ }
59
+
60
+ export interface ErrorClassSurfaceProjection {
61
+ readonly category: ErrorCategory;
62
+ readonly code: SurfaceErrorCode;
63
+ readonly name: string;
64
+ readonly retryable: boolean;
65
+ readonly surface: SurfaceName;
66
+ }
67
+
68
+ export const createSurfaceErrorMapper =
69
+ <T>(mappings: SurfaceErrorMappings<T>): SurfaceErrorMapper<T> =>
70
+ (error) =>
71
+ mappings[error.category];
72
+
73
+ export const surfaceErrorMap = {
74
+ cli: exitCodeMap,
75
+ http: statusCodeMap,
76
+ jsonRpc: jsonRpcCodeMap,
77
+ mcp: jsonRpcCodeMap,
78
+ } as const satisfies Record<SurfaceName, SurfaceErrorMappings<number>>;
79
+
80
+ export const surfaceErrorRegistry = {
81
+ cli: {
82
+ map: createSurfaceErrorMapper(surfaceErrorMap.cli),
83
+ values: surfaceErrorMap.cli,
84
+ },
85
+ http: {
86
+ map: createSurfaceErrorMapper(surfaceErrorMap.http),
87
+ values: surfaceErrorMap.http,
88
+ },
89
+ jsonRpc: {
90
+ map: createSurfaceErrorMapper(surfaceErrorMap.jsonRpc),
91
+ values: surfaceErrorMap.jsonRpc,
92
+ },
93
+ mcp: {
94
+ map: createSurfaceErrorMapper(surfaceErrorMap.mcp),
95
+ values: surfaceErrorMap.mcp,
96
+ },
97
+ } as const;
98
+
99
+ export const mapSurfaceError = (
100
+ surface: SurfaceName,
101
+ error: TrailsError
102
+ ): SurfaceErrorCode =>
103
+ codesByCategory[error.category][surfaceCodeKeys[surface]];
104
+
105
+ export const projectSurfaceError = (
106
+ surface: SurfaceName,
107
+ error: TrailsError
108
+ ): SurfaceErrorProjection => ({
109
+ category: error.category,
110
+ code: mapSurfaceError(surface, error),
111
+ message: error.message,
112
+ name: error.name,
113
+ retryable: error.retryable,
114
+ surface,
115
+ });
116
+
117
+ export const projectPublicSurfaceError = (
118
+ surface: SurfaceName,
119
+ error: Error
120
+ ): SurfaceErrorProjection => {
121
+ if (isTrailsError(error)) {
122
+ const projection = projectSurfaceError(surface, error);
123
+ return {
124
+ ...projection,
125
+ message:
126
+ projection.category === 'internal'
127
+ ? INTERNAL_ERROR_PUBLIC_MESSAGE
128
+ : redactErrorString(projection.message),
129
+ };
130
+ }
131
+
132
+ return {
133
+ category: 'internal',
134
+ code: codesByCategory.internal[surfaceCodeKeys[surface]],
135
+ message: INTERNAL_ERROR_PUBLIC_MESSAGE,
136
+ name: 'InternalError',
137
+ retryable: false,
138
+ surface,
139
+ };
140
+ };
141
+
142
+ const isFixedErrorClassEntry = (
143
+ entry: ErrorClassRegistryEntry
144
+ ): entry is FixedErrorClassRegistryEntry => entry.category !== 'dynamic';
145
+
146
+ const fixedErrorClassByName: ReadonlyMap<string, FixedErrorClassRegistryEntry> =
147
+ new Map(
148
+ errorClasses.flatMap((entry): [string, FixedErrorClassRegistryEntry][] =>
149
+ isFixedErrorClassEntry(entry) ? [[entry.name, entry]] : []
150
+ )
151
+ );
152
+
153
+ /**
154
+ * Project a known error class name onto a surface without constructing it.
155
+ *
156
+ * Dynamic-category errors such as `RetryExhaustedError` return `undefined`
157
+ * because their surface code depends on the wrapped runtime error.
158
+ */
159
+ export const projectErrorClassSurface = (
160
+ surface: SurfaceName,
161
+ errorName: string
162
+ ): ErrorClassSurfaceProjection | undefined => {
163
+ const entry = fixedErrorClassByName.get(errorName);
164
+ if (entry === undefined) {
165
+ return undefined;
166
+ }
167
+ return {
168
+ category: entry.category,
169
+ code: codesByCategory[entry.category][surfaceCodeKeys[surface]],
170
+ name: entry.name,
171
+ retryable: entry.retryable,
172
+ surface,
173
+ };
174
+ };
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Type utilities for extracting input/output types from trails.
3
+ */
4
+
5
+ import type { Result } from './result.js';
6
+ import type { AnyTrail, Trail } from './trail.js';
7
+ import type { Implementation } from './types.js';
8
+ import type { z } from 'zod';
9
+
10
+ // ---------------------------------------------------------------------------
11
+ // Utility types
12
+ // ---------------------------------------------------------------------------
13
+
14
+ /* oxlint-disable no-explicit-any -- `any` required for conditional type inference; `unknown` breaks inference */
15
+
16
+ type SchemaInputOrFallback<TSchema extends z.ZodType, TFallback> =
17
+ unknown extends z.input<TSchema> ? TFallback : z.input<TSchema>;
18
+
19
+ type ComposeSchemaOf<T extends AnyTrail> = T extends {
20
+ readonly composeInput?: (infer TComposeSchema) | undefined;
21
+ }
22
+ ? NonNullable<TComposeSchema>
23
+ : never;
24
+
25
+ type ComposeInputPart<T extends AnyTrail> =
26
+ ComposeSchemaOf<T> extends z.ZodType
27
+ ? T extends Trail<any, any, infer CI>
28
+ ? SchemaInputOrFallback<ComposeSchemaOf<T>, CI>
29
+ : z.input<ComposeSchemaOf<T>>
30
+ : T extends Trail<any, any, infer CI>
31
+ ? CI
32
+ : never;
33
+
34
+ /** Extract the input type from a Trail. */
35
+ export type TrailInput<T extends AnyTrail> = T extends {
36
+ readonly input: infer TInputSchema extends z.ZodType;
37
+ }
38
+ ? T extends Trail<infer I, any, any>
39
+ ? SchemaInputOrFallback<TInputSchema, I>
40
+ : z.input<TInputSchema>
41
+ : never;
42
+
43
+ /** Extract the output type from a Trail. */
44
+ export type TrailOutput<T extends AnyTrail> = T extends {
45
+ readonly blaze: Implementation<any, infer O>;
46
+ }
47
+ ? O
48
+ : never;
49
+
50
+ /**
51
+ * Extract the compose-callable input type from a trail.
52
+ *
53
+ * When a trail declares `composeInput`, callers via `ctx.compose()` must pass
54
+ * both the public input fields and the composition-only fields. This type
55
+ * merges both schemas so the compiler enforces the full shape at the call
56
+ * site. Falls back to plain `TrailInput<T>` when no `composeInput` exists.
57
+ */
58
+ export type ComposeInput<T extends AnyTrail> = [ComposeInputPart<T>] extends [
59
+ never,
60
+ ]
61
+ ? TrailInput<T>
62
+ : TrailInput<T> & ComposeInputPart<T>;
63
+
64
+ /**
65
+ * Extracts the full `Result<Output, Error>` type from a trail definition.
66
+ *
67
+ * @example
68
+ * ```typescript
69
+ * type SearchResult = TrailResult<typeof searchTrail>;
70
+ * // Result<{ results: Item[]; count: number }, Error>
71
+ * ```
72
+ */
73
+ export type TrailResult<T extends AnyTrail> = Result<TrailOutput<T>, Error>;
74
+
75
+ /* oxlint-enable no-explicit-any */
76
+
77
+ // ---------------------------------------------------------------------------
78
+ // Runtime schema accessors
79
+ // ---------------------------------------------------------------------------
80
+
81
+ /** Get the input Zod schema from a trail, preserving the specific schema type. */
82
+ export const inputOf = <T extends AnyTrail>(trail: T): T['input'] =>
83
+ trail.input;
84
+
85
+ /** Get the output Zod schema from a trail, if defined, preserving the specific schema type. */
86
+ export const outputOf = <T extends AnyTrail>(trail: T): T['output'] =>
87
+ trail.output;