@ontrails/core 1.0.0-beta.2 → 1.0.0-beta.21

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 +283 -5
  2. package/README.md +113 -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 +59 -18
  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 +309 -48
  19. package/src/execute.ts +1577 -0
  20. package/src/fire.ts +1169 -0
  21. package/src/index.ts +477 -32
  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 +36 -4
  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 +119 -39
  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 -57
  47. package/src/tracing.ts +345 -0
  48. package/src/trail.ts +1161 -29
  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 +208 -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 +442 -35
  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 -122
  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 -34
  117. package/dist/index.d.ts.map +0 -1
  118. package/dist/index.js +0 -38
  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 -145
  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 -115
  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 -74
  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 -108
  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 -159
  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 -236
  234. package/src/__tests__/topo.test.ts +0 -184
  235. package/src/__tests__/trail.test.ts +0 -179
  236. package/src/__tests__/validate-topo.test.ts +0 -201
  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
package/src/signal.ts ADDED
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Signal — a named payload schema with optional provenance meta.
3
+ */
4
+
5
+ import type { z } from 'zod';
6
+
7
+ const formatExampleIssues = (issues: readonly z.core.$ZodIssue[]): string =>
8
+ issues
9
+ .map((issue) => {
10
+ const path = issue.path.length > 0 ? issue.path.join('.') : '<root>';
11
+ return `${path}: ${issue.message}`;
12
+ })
13
+ .join('; ');
14
+
15
+ const assertSignalExamples = <T>(
16
+ id: string,
17
+ payload: z.ZodType<T>,
18
+ examples: readonly T[]
19
+ ): void => {
20
+ for (const [index, example] of examples.entries()) {
21
+ const parsed = payload.safeParse(example);
22
+ if (!parsed.success) {
23
+ throw new TypeError(
24
+ `signal("${id}") example ${index} is invalid: ${formatExampleIssues(parsed.error.issues)}`
25
+ );
26
+ }
27
+ }
28
+ };
29
+
30
+ // ---------------------------------------------------------------------------
31
+ // Spec (input to the factory)
32
+ // ---------------------------------------------------------------------------
33
+
34
+ export interface SignalSpec<T> {
35
+ readonly payload: z.ZodType<T>;
36
+ readonly description?: string | undefined;
37
+ /** Example payloads validated against the signal payload schema. */
38
+ readonly examples?: readonly T[] | undefined;
39
+ readonly meta?: Readonly<Record<string, unknown>> | undefined;
40
+ /** Trail IDs that produce this signal (e.g. the trails it originates from). */
41
+ readonly from?: readonly string[] | undefined;
42
+ /** Reserved for future signal-specific design; trail versioning is trail-only. */
43
+ readonly version?: never;
44
+ }
45
+
46
+ // ---------------------------------------------------------------------------
47
+ // Shape (output of the factory)
48
+ // ---------------------------------------------------------------------------
49
+
50
+ export interface Signal<T> {
51
+ readonly id: string;
52
+ readonly kind: 'signal';
53
+ readonly payload: z.ZodType<T>;
54
+ readonly description?: string | undefined;
55
+ /** Example payloads validated against the signal payload schema. */
56
+ readonly examples?: readonly T[] | undefined;
57
+ readonly meta?: Readonly<Record<string, unknown>> | undefined;
58
+ /** Trail IDs that produce this signal (e.g. the trails it originates from). */
59
+ readonly from?: readonly string[] | undefined;
60
+ }
61
+
62
+ // ---------------------------------------------------------------------------
63
+ // Factory
64
+ // ---------------------------------------------------------------------------
65
+
66
+ /**
67
+ * Create a signal definition.
68
+ *
69
+ * A signal is a named payload schema describing something that happened.
70
+ * Returns a frozen object with `kind: "signal"` and all spec fields.
71
+ */
72
+ export function signal<T>(id: string, spec: SignalSpec<T>): Signal<T>;
73
+ export function signal<T>(
74
+ spec: SignalSpec<T> & { readonly id: string }
75
+ ): Signal<T>;
76
+ export function signal<T>(
77
+ idOrSpec: string | (SignalSpec<T> & { readonly id: string }),
78
+ maybeSpec?: SignalSpec<T>
79
+ ): Signal<T> {
80
+ const resolvedId = typeof idOrSpec === 'string' ? idOrSpec : idOrSpec.id;
81
+ // oxlint-disable-next-line no-non-null-assertion -- overload guarantees maybeSpec when idOrSpec is string
82
+ const resolvedSpec = typeof idOrSpec === 'string' ? maybeSpec! : idOrSpec;
83
+ if (resolvedSpec.examples !== undefined) {
84
+ assertSignalExamples(
85
+ resolvedId,
86
+ resolvedSpec.payload,
87
+ resolvedSpec.examples
88
+ );
89
+ }
90
+ return Object.freeze({
91
+ description: resolvedSpec.description,
92
+ examples: resolvedSpec.examples
93
+ ? Object.freeze([...resolvedSpec.examples])
94
+ : undefined,
95
+ from: resolvedSpec.from ? Object.freeze([...resolvedSpec.from]) : undefined,
96
+ id: resolvedId,
97
+ kind: 'signal' as const,
98
+ meta: resolvedSpec.meta,
99
+ payload: resolvedSpec.payload,
100
+ });
101
+ }
102
+
103
+ /** Existential type for heterogeneous signal collections */
104
+ export type AnySignal = Signal<unknown>;
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Structural accessor protocol used by `deriveTrail()` to synthesize default
3
+ * blazes for standard CRUD operations without depending on `@ontrails/store`.
4
+ *
5
+ * @remarks
6
+ * This type is intentionally minimal and structural. `@ontrails/store`'s
7
+ * `StoreAccessor` / `StoreTableAccessor` interfaces satisfy this protocol
8
+ * through a compile-time extends check (see `packages/store/src/types.ts`).
9
+ * Keeping the protocol in core avoids a core → store dependency while still
10
+ * allowing the derivation helper to call accessors by convention.
11
+ *
12
+ * Required methods (`get`, `list`, `upsert`, `remove`) match the
13
+ * backend-agnostic write contract every bound store must expose. Optional
14
+ * methods (`insert`, `update`) are declared by tabular adapters that
15
+ * distinguish create-only and patch-only operations from the generalized
16
+ * `upsert` contract.
17
+ */
18
+ export interface StoreAccessorProtocol<
19
+ TInput,
20
+ TEntity,
21
+ TId,
22
+ TFilters = unknown,
23
+ > {
24
+ /** Retrieve a single entity by identity. Returns `null` when not found. */
25
+ get(id: TId): Promise<TEntity | null>;
26
+ /** List entities, optionally filtered. Returns `[]` when no rows match. */
27
+ list(filters?: TFilters): Promise<readonly TEntity[]>;
28
+ /** Create-or-replace one entity using the backend-agnostic contract. */
29
+ upsert(input: TInput): Promise<TEntity>;
30
+ /**
31
+ * Remove an entity by identity. Returns `{ deleted: true }` when the row
32
+ * was found and removed, `{ deleted: false }` when no matching row
33
+ * existed (not an error).
34
+ */
35
+ remove(id: TId): Promise<{ readonly deleted: boolean }>;
36
+ /**
37
+ * Optional insert — available on tabular adapters that distinguish
38
+ * create from update. When absent, synthesized blazes fall back to
39
+ * `upsert`.
40
+ */
41
+ insert?(input: TInput): Promise<TEntity>;
42
+ /**
43
+ * Optional patch-by-identity — available on tabular adapters. Returns
44
+ * `null` when no row with the given identity exists. When absent,
45
+ * synthesized update blazes fall back to `get` + merge + `upsert`.
46
+ */
47
+ update?(id: TId, patch: Partial<TInput>): Promise<TEntity | null>;
48
+ }
49
+
50
+ /**
51
+ * Record shape returned by a resource's `from(ctx)` call, keyed by accessor
52
+ * name. Used by `deriveTrail()` to resolve an accessor by contour name.
53
+ */
54
+ export type StoreAccessorRecord = Readonly<
55
+ Record<string, StoreAccessorProtocol<unknown, unknown, unknown, unknown>>
56
+ >;
@@ -0,0 +1,4 @@
1
+ export type {
2
+ StoreAccessorProtocol,
3
+ StoreAccessorRecord,
4
+ } from './accessor-protocol.js';
@@ -0,0 +1,248 @@
1
+ import type { TrailExample, TrailExampleSignalAssertion } from './trail.js';
2
+
3
+ export interface StructuredTrailExampleProvenance {
4
+ readonly source: 'trail.examples' | 'trail.versions.examples';
5
+ }
6
+
7
+ export interface StructuredSignalExampleProvenance {
8
+ readonly source: 'signal.examples';
9
+ }
10
+
11
+ export type StructuredTrailExampleKind = 'success' | 'error';
12
+
13
+ export interface StructuredTrailExample {
14
+ readonly description?: string | undefined;
15
+ readonly error?: string | undefined;
16
+ readonly expected?: unknown | undefined;
17
+ readonly expectedMatch?: unknown | undefined;
18
+ readonly input: unknown;
19
+ readonly kind: StructuredTrailExampleKind;
20
+ readonly name: string;
21
+ readonly provenance: StructuredTrailExampleProvenance;
22
+ readonly signals?:
23
+ | readonly StructuredTrailExampleSignalAssertion[]
24
+ | undefined;
25
+ }
26
+
27
+ export interface StructuredTrailExampleSignalAssertion {
28
+ readonly payload?: unknown | undefined;
29
+ readonly payloadMatch?: unknown | undefined;
30
+ readonly signalId: string;
31
+ readonly times?: number | undefined;
32
+ }
33
+
34
+ export interface StructuredSignalExample {
35
+ readonly kind: 'payload';
36
+ readonly payload: unknown;
37
+ readonly provenance: StructuredSignalExampleProvenance;
38
+ }
39
+
40
+ // `Date`, `RegExp`, `Map`, and `Set` are objects (`typeof === 'object'`),
41
+ // so they would pass the structural walk and reach `JSON.stringify`, which
42
+ // silently coerces them: a `Date` becomes its ISO string, a `RegExp` and
43
+ // any `Map`/`Set` become `{}`. Either way the projected shape diverges
44
+ // from the example author's declared input. Treat them as non-serializable
45
+ // leaves so the example is dropped rather than misrepresented to MCP
46
+ // clients.
47
+ const isNonJsonLeaf = (value: unknown): boolean => {
48
+ const kind = typeof value;
49
+ if (kind === 'function' || kind === 'symbol' || kind === 'bigint') {
50
+ return true;
51
+ }
52
+ return (
53
+ value instanceof Date ||
54
+ value instanceof RegExp ||
55
+ value instanceof Map ||
56
+ value instanceof Set
57
+ );
58
+ };
59
+
60
+ // `JSON.stringify` silently drops function / symbol property values rather than
61
+ // throwing, so we walk the value first and reject any example whose graph
62
+ // contains a non-serializable leaf. Without this, an MCP client consuming
63
+ // `ontrails/examples` would receive structurally incorrect inputs.
64
+ const containsNonSerializableLeaf = (
65
+ value: unknown,
66
+ seen: WeakSet<object>
67
+ ): boolean => {
68
+ if (isNonJsonLeaf(value)) {
69
+ return true;
70
+ }
71
+ if (value === null || typeof value !== 'object') {
72
+ return false;
73
+ }
74
+ const obj = value as object;
75
+ if (seen.has(obj)) {
76
+ return false;
77
+ }
78
+ seen.add(obj);
79
+ if (Array.isArray(value)) {
80
+ return value.some((entry) => containsNonSerializableLeaf(entry, seen));
81
+ }
82
+ return Object.values(obj).some((entry) =>
83
+ containsNonSerializableLeaf(entry, seen)
84
+ );
85
+ };
86
+
87
+ const toJsonSerializable = (value: unknown): unknown | undefined => {
88
+ if (containsNonSerializableLeaf(value, new WeakSet<object>())) {
89
+ return undefined;
90
+ }
91
+ try {
92
+ const encoded = JSON.stringify(value);
93
+ return encoded === undefined ? undefined : JSON.parse(encoded);
94
+ } catch {
95
+ return undefined;
96
+ }
97
+ };
98
+
99
+ const signalIdFromAssertion = (
100
+ assertion: TrailExampleSignalAssertion
101
+ ): string | undefined => {
102
+ if (typeof assertion.signal === 'string') {
103
+ return assertion.signal;
104
+ }
105
+ return typeof assertion.signal.id === 'string'
106
+ ? assertion.signal.id
107
+ : undefined;
108
+ };
109
+
110
+ const projectSignalAssertion = (
111
+ assertion: TrailExampleSignalAssertion
112
+ ): StructuredTrailExampleSignalAssertion | undefined => {
113
+ const signalId = signalIdFromAssertion(assertion);
114
+ if (signalId === undefined) {
115
+ return undefined;
116
+ }
117
+
118
+ const projected: Record<string, unknown> = { signalId };
119
+ if (assertion.payload !== undefined) {
120
+ const payload = toJsonSerializable(assertion.payload);
121
+ if (payload === undefined) {
122
+ return undefined;
123
+ }
124
+ projected['payload'] = payload;
125
+ }
126
+ if (assertion.payloadMatch !== undefined) {
127
+ const payloadMatch = toJsonSerializable(assertion.payloadMatch);
128
+ if (payloadMatch === undefined) {
129
+ return undefined;
130
+ }
131
+ projected['payloadMatch'] = payloadMatch;
132
+ }
133
+ if (assertion.times !== undefined) {
134
+ projected['times'] = assertion.times;
135
+ }
136
+ return Object.freeze(
137
+ projected
138
+ ) as unknown as StructuredTrailExampleSignalAssertion;
139
+ };
140
+
141
+ const projectSignalAssertions = (
142
+ assertions: readonly TrailExampleSignalAssertion[] | undefined
143
+ ): readonly StructuredTrailExampleSignalAssertion[] | undefined => {
144
+ if (assertions === undefined) {
145
+ return undefined;
146
+ }
147
+ const projected = assertions.map(projectSignalAssertion);
148
+ if (projected.some((assertion) => assertion === undefined)) {
149
+ return undefined;
150
+ }
151
+ return Object.freeze(projected as StructuredTrailExampleSignalAssertion[]);
152
+ };
153
+
154
+ const projectExample = (
155
+ example: TrailExample<unknown, unknown>,
156
+ provenance: StructuredTrailExampleProvenance
157
+ ): StructuredTrailExample | undefined => {
158
+ const input = toJsonSerializable(example.input);
159
+ if (input === undefined) {
160
+ return undefined;
161
+ }
162
+
163
+ const projected: Record<string, unknown> = {
164
+ input,
165
+ kind: example.error === undefined ? 'success' : 'error',
166
+ name: example.name,
167
+ provenance,
168
+ };
169
+
170
+ if (example.description !== undefined) {
171
+ projected['description'] = example.description;
172
+ }
173
+ if (example.expected !== undefined) {
174
+ const expected = toJsonSerializable(example.expected);
175
+ if (expected === undefined) {
176
+ return undefined;
177
+ }
178
+ projected['expected'] = expected;
179
+ }
180
+ if (example.expectedMatch !== undefined) {
181
+ const expectedMatch = toJsonSerializable(example.expectedMatch);
182
+ if (expectedMatch === undefined) {
183
+ return undefined;
184
+ }
185
+ projected['expectedMatch'] = expectedMatch;
186
+ }
187
+ if (example.error !== undefined) {
188
+ projected['error'] = example.error;
189
+ }
190
+ if (example.signals !== undefined) {
191
+ const signals = projectSignalAssertions(example.signals);
192
+ if (signals === undefined) {
193
+ return undefined;
194
+ }
195
+ projected['signals'] = signals;
196
+ }
197
+
198
+ return Object.freeze(projected) as unknown as StructuredTrailExample;
199
+ };
200
+
201
+ const projectSignalExample = (
202
+ payload: unknown
203
+ ): StructuredSignalExample | undefined => {
204
+ const serializablePayload = toJsonSerializable(payload);
205
+ if (serializablePayload === undefined) {
206
+ return undefined;
207
+ }
208
+
209
+ return Object.freeze({
210
+ kind: 'payload',
211
+ payload: serializablePayload,
212
+ provenance: { source: 'signal.examples' },
213
+ } satisfies StructuredSignalExample);
214
+ };
215
+
216
+ export const deriveStructuredTrailExamples = (
217
+ examples: readonly TrailExample<unknown, unknown>[] | undefined,
218
+ options?: { readonly provenance?: StructuredTrailExampleProvenance }
219
+ ): readonly StructuredTrailExample[] | undefined => {
220
+ if (examples === undefined || examples.length === 0) {
221
+ return undefined;
222
+ }
223
+
224
+ const provenance = options?.provenance ?? { source: 'trail.examples' };
225
+ const projected = examples
226
+ .map((example) => projectExample(example, provenance))
227
+ .filter(
228
+ (example): example is StructuredTrailExample => example !== undefined
229
+ );
230
+
231
+ return projected.length > 0 ? Object.freeze(projected) : undefined;
232
+ };
233
+
234
+ export const deriveStructuredSignalExamples = (
235
+ examples: readonly unknown[] | undefined
236
+ ): readonly StructuredSignalExample[] | undefined => {
237
+ if (examples === undefined || examples.length === 0) {
238
+ return undefined;
239
+ }
240
+
241
+ const projected = examples
242
+ .map(projectSignalExample)
243
+ .filter(
244
+ (example): example is StructuredSignalExample => example !== undefined
245
+ );
246
+
247
+ return projected.length > 0 ? Object.freeze(projected) : undefined;
248
+ };
@@ -0,0 +1,91 @@
1
+ import { Result } from './result.js';
2
+ import type { Layer } from './layer.js';
3
+ import type { Intent } from './trail.js';
4
+ import type { Topo } from './topo.js';
5
+ import type { SurfaceName } from './transport-error-map.js';
6
+ import type { TrailContextInit } from './types.js';
7
+ import { SURFACE_KEY, SURFACE_LAYER_NAMES_KEY } from './types.js';
8
+ import { validateEstablishedTopo } from './validate-established-topo.js';
9
+
10
+ export type SurfaceConfigValues = Readonly<
11
+ Record<string, Record<string, unknown>>
12
+ >;
13
+
14
+ export interface SurfaceSelectionOptions {
15
+ /** Glob patterns that remove matching trail IDs. */
16
+ readonly exclude?: readonly string[] | undefined;
17
+ /** Glob patterns that keep only matching trail IDs when provided. */
18
+ readonly include?: readonly string[] | undefined;
19
+ /** Allowed intents for exposed surfaces. Empty arrays act as no filter. */
20
+ readonly intent?: readonly Intent[] | undefined;
21
+ }
22
+
23
+ export interface SurfaceValidationOptions {
24
+ /** Set to `false` to skip established-topo validation during projection. */
25
+ readonly validate?: boolean | undefined;
26
+ }
27
+
28
+ export interface BaseSurfaceOptions
29
+ extends SurfaceSelectionOptions, SurfaceValidationOptions {
30
+ /** Config values for resources that declare a `config` schema, keyed by resource ID. */
31
+ readonly configValues?: SurfaceConfigValues | undefined;
32
+ }
33
+
34
+ export const shouldValidateSurfaceTopo = (
35
+ options?: SurfaceValidationOptions
36
+ ): boolean => options?.validate !== false;
37
+
38
+ export const validateSurfaceTopo = (
39
+ graph: Topo,
40
+ options?: SurfaceValidationOptions
41
+ ): Result<void, Error> => {
42
+ if (!shouldValidateSurfaceTopo(options)) {
43
+ return Result.ok();
44
+ }
45
+
46
+ const validated = validateEstablishedTopo(graph);
47
+ return validated.isErr() ? Result.err(validated.error) : Result.ok();
48
+ };
49
+
50
+ export type SurfaceMarkedContext = Partial<TrailContextInit> & {
51
+ readonly extensions: Readonly<Record<string, unknown>>;
52
+ };
53
+
54
+ export const withSurfaceMarker = (
55
+ surface: SurfaceName,
56
+ ctx: Partial<TrailContextInit> = {}
57
+ ): SurfaceMarkedContext => ({
58
+ ...ctx,
59
+ extensions: {
60
+ ...ctx.extensions,
61
+ [SURFACE_KEY]: surface,
62
+ },
63
+ });
64
+
65
+ const readSurfaceLayerNameRecord = (
66
+ value: unknown
67
+ ): Record<string, readonly string[]> =>
68
+ value !== null && typeof value === 'object' && !Array.isArray(value)
69
+ ? (value as Record<string, readonly string[]>)
70
+ : {};
71
+
72
+ export const withSurfaceLayerNames = (
73
+ surface: SurfaceName,
74
+ layers: readonly Layer[],
75
+ ctx: Partial<TrailContextInit> = {}
76
+ ): SurfaceMarkedContext => {
77
+ const existing = readSurfaceLayerNameRecord(
78
+ ctx.extensions?.[SURFACE_LAYER_NAMES_KEY]
79
+ );
80
+ return {
81
+ ...ctx,
82
+ extensions: {
83
+ ...ctx.extensions,
84
+ [SURFACE_KEY]: surface,
85
+ [SURFACE_LAYER_NAMES_KEY]: {
86
+ ...existing,
87
+ [surface]: layers.map((layer) => layer.name),
88
+ },
89
+ },
90
+ };
91
+ };
@@ -0,0 +1,176 @@
1
+ import type { Intent, Trail } from './trail.js';
2
+ import type { SurfaceSelectionOptions } from './surface-derivation.js';
3
+
4
+ // ---------------------------------------------------------------------------
5
+ // Public types
6
+ // ---------------------------------------------------------------------------
7
+
8
+ export type SurfaceFilterOptions = SurfaceSelectionOptions;
9
+
10
+ // ---------------------------------------------------------------------------
11
+ // Glob matching
12
+ // ---------------------------------------------------------------------------
13
+
14
+ const trailIdSegments = (trailId: string): readonly string[] =>
15
+ trailId.split('.');
16
+
17
+ const patternSegments = (pattern: string): readonly string[] =>
18
+ pattern.split('.');
19
+
20
+ type SegmentMatcher = (
21
+ trail: readonly string[],
22
+ pattern: readonly string[],
23
+ trailIndex: number,
24
+ patternIndex: number
25
+ ) => boolean;
26
+
27
+ const matchesDoubleStar = (
28
+ trail: readonly string[],
29
+ pattern: readonly string[],
30
+ trailIndex: number,
31
+ patternIndex: number,
32
+ matchSegments: SegmentMatcher
33
+ ): boolean =>
34
+ patternIndex === pattern.length - 1 ||
35
+ Array.from(
36
+ { length: trail.length - trailIndex + 1 },
37
+ (_, offset) => trailIndex + offset
38
+ ).some((index) => matchSegments(trail, pattern, index, patternIndex + 1));
39
+
40
+ const matchesSingleSegment = (
41
+ trail: readonly string[],
42
+ pattern: readonly string[],
43
+ trailIndex: number,
44
+ patternIndex: number,
45
+ current: string,
46
+ matchSegments: SegmentMatcher
47
+ ): boolean =>
48
+ trailIndex < trail.length &&
49
+ (current === '*' || current === trail[trailIndex]) &&
50
+ matchSegments(trail, pattern, trailIndex + 1, patternIndex + 1);
51
+
52
+ const matchesFrom = function matchesFrom(
53
+ trail: readonly string[],
54
+ pattern: readonly string[],
55
+ trailIndex: number,
56
+ patternIndex: number
57
+ ): boolean {
58
+ if (patternIndex >= pattern.length) {
59
+ return trailIndex >= trail.length;
60
+ }
61
+
62
+ const current = pattern[patternIndex];
63
+ if (current === undefined) {
64
+ return false;
65
+ }
66
+
67
+ return current === '**'
68
+ ? matchesDoubleStar(trail, pattern, trailIndex, patternIndex, matchesFrom)
69
+ : matchesSingleSegment(
70
+ trail,
71
+ pattern,
72
+ trailIndex,
73
+ patternIndex,
74
+ current,
75
+ matchesFrom
76
+ );
77
+ };
78
+
79
+ export const matchesTrailPattern = (
80
+ trailId: string,
81
+ pattern: string
82
+ ): boolean => {
83
+ if (pattern === trailId) {
84
+ return true;
85
+ }
86
+ return matchesFrom(trailIdSegments(trailId), patternSegments(pattern), 0, 0);
87
+ };
88
+
89
+ // ---------------------------------------------------------------------------
90
+ // Surface filtering
91
+ // ---------------------------------------------------------------------------
92
+
93
+ const matchesAnyPattern = (
94
+ trailId: string,
95
+ patterns: readonly string[] | undefined
96
+ ): boolean =>
97
+ patterns !== undefined &&
98
+ patterns.some((pattern) => matchesTrailPattern(trailId, pattern));
99
+
100
+ const isExplicitInternalInclude = (
101
+ trailId: string,
102
+ include: readonly string[] | undefined
103
+ ): boolean => include !== undefined && include.includes(trailId);
104
+
105
+ /**
106
+ * Resolve the effective visibility for a trail.
107
+ *
108
+ * Returns `'internal'` when either the explicit `visibility` field is
109
+ * `'internal'` or the legacy `meta.internal === true` convention is set.
110
+ * Honoring the legacy flag keeps trails authored before the visibility
111
+ * field was introduced (e.g. `meta: { internal: true }`) off surfaces.
112
+ *
113
+ * The runtime always fills in `visibility: 'public'` when the spec did not
114
+ * declare it, so we cannot distinguish explicit `'public'` from the default.
115
+ * This means a trail that sets both `meta.internal = true` and
116
+ * `visibility: 'public'` will still be treated as internal — that
117
+ * combination has never been a documented override and, if the author
118
+ * really means "public", they should remove the legacy flag.
119
+ */
120
+ const effectiveVisibility = (
121
+ trail: Trail<unknown, unknown, unknown>
122
+ ): 'public' | 'internal' => {
123
+ if (trail.visibility === 'internal') {
124
+ return 'internal';
125
+ }
126
+ return trail.meta?.['internal'] === true ? 'internal' : 'public';
127
+ };
128
+
129
+ const isVisibleToSurfaces = (
130
+ trail: Trail<unknown, unknown, unknown>,
131
+ include: readonly string[] | undefined
132
+ ): boolean =>
133
+ effectiveVisibility(trail) !== 'internal' ||
134
+ isExplicitInternalInclude(trail.id, include);
135
+
136
+ const passesIncludeFilter = (
137
+ trailId: string,
138
+ include: readonly string[] | undefined
139
+ ): boolean =>
140
+ include === undefined ||
141
+ include.length === 0 ||
142
+ matchesAnyPattern(trailId, include);
143
+
144
+ const passesIntentFilter = (
145
+ trail: Trail<unknown, unknown, unknown>,
146
+ intent: readonly Intent[] | undefined
147
+ ): boolean =>
148
+ intent === undefined || intent.length === 0 || intent.includes(trail.intent);
149
+
150
+ export const shouldIncludeTrailForSurface = (
151
+ trail: Trail<unknown, unknown, unknown>,
152
+ options: SurfaceFilterOptions = {}
153
+ ): boolean => {
154
+ if (trail.activationSources.length > 0) {
155
+ return false;
156
+ }
157
+
158
+ const { exclude, include, intent } = options;
159
+ if (!isVisibleToSurfaces(trail, include)) {
160
+ return false;
161
+ }
162
+
163
+ if (matchesAnyPattern(trail.id, exclude)) {
164
+ return false;
165
+ }
166
+
167
+ return (
168
+ passesIncludeFilter(trail.id, include) && passesIntentFilter(trail, intent)
169
+ );
170
+ };
171
+
172
+ export const filterSurfaceTrails = (
173
+ trails: readonly Trail<unknown, unknown, unknown>[],
174
+ options: SurfaceFilterOptions = {}
175
+ ): Trail<unknown, unknown, unknown>[] =>
176
+ trails.filter((trail) => shouldIncludeTrailForSurface(trail, options));