@ontrails/trails 1.0.0-beta.4 → 1.0.0-beta.42

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 (165) hide show
  1. package/CHANGELOG.md +1106 -4
  2. package/README.md +27 -0
  3. package/package.json +31 -7
  4. package/src/app.ts +147 -3
  5. package/src/cli.ts +345 -11
  6. package/src/completions.ts +240 -0
  7. package/src/lifecycle-source-io.ts +33 -0
  8. package/src/load-app-mirror.ts +202 -0
  9. package/src/local-state-io.ts +173 -0
  10. package/src/mcp-app.ts +42 -0
  11. package/src/mcp-options.ts +91 -0
  12. package/src/mcp.ts +8 -0
  13. package/src/project-writes.ts +377 -0
  14. package/src/regrade/config.ts +152 -0
  15. package/src/regrade/history.ts +430 -0
  16. package/src/regrade/live-api-preserve.ts +8 -0
  17. package/src/regrade/plan-artifact.ts +285 -0
  18. package/src/release/bindings.ts +39 -0
  19. package/src/release/check.ts +844 -0
  20. package/src/release/config.ts +63 -0
  21. package/src/release/contract-facts.ts +425 -0
  22. package/src/release/index.ts +142 -0
  23. package/src/release/lock-roundtrip-smoke.ts +230 -0
  24. package/src/release/native-bun-publish.ts +651 -0
  25. package/src/release/native-bun-registry.ts +765 -0
  26. package/src/release/notes-cli.ts +171 -0
  27. package/src/release/notes.ts +390 -0
  28. package/src/release/pack-coherence.ts +455 -0
  29. package/src/release/packed-artifacts-smoke.ts +236 -0
  30. package/src/release/policy.ts +1687 -0
  31. package/src/release/semver.ts +104 -0
  32. package/src/release/smoke.ts +56 -0
  33. package/src/release/wayfinder-dogfood-smoke.ts +760 -0
  34. package/src/retired-topo-command.ts +36 -0
  35. package/src/run-adapter-check.ts +76 -0
  36. package/src/run-collision.ts +126 -0
  37. package/src/run-completions-install.ts +179 -0
  38. package/src/run-example.ts +149 -0
  39. package/src/run-examples.ts +148 -0
  40. package/src/run-quiet.ts +75 -0
  41. package/src/run-release-check.ts +74 -0
  42. package/src/run-schema.ts +74 -0
  43. package/src/run-trace.ts +273 -0
  44. package/src/run-warden.ts +39 -0
  45. package/src/run-watch.ts +432 -0
  46. package/src/run-wayfind-outline.ts +170 -0
  47. package/src/scaffold-version-sync.ts +183 -0
  48. package/src/scaffold-versions.generated.ts +12 -0
  49. package/src/trails/adapter-check.ts +244 -0
  50. package/src/trails/add-surface.ts +99 -45
  51. package/src/trails/add-trail.ts +84 -37
  52. package/src/trails/add-verify.ts +100 -30
  53. package/src/trails/compile.ts +58 -0
  54. package/src/trails/completions-complete.ts +165 -0
  55. package/src/trails/completions.ts +47 -0
  56. package/src/trails/create-adapter.ts +785 -0
  57. package/src/trails/create-scaffold.ts +401 -106
  58. package/src/trails/create-versions.ts +62 -0
  59. package/src/trails/create.ts +186 -72
  60. package/src/trails/deprecate.ts +59 -0
  61. package/src/trails/dev-clean.ts +82 -0
  62. package/src/trails/dev-reset.ts +50 -0
  63. package/src/trails/dev-stats.ts +72 -0
  64. package/src/trails/dev-support.ts +360 -0
  65. package/src/trails/doctor.ts +77 -0
  66. package/src/trails/draft-promote.ts +949 -0
  67. package/src/trails/guide.ts +70 -68
  68. package/src/trails/load-app.ts +1123 -15
  69. package/src/trails/operator-context.ts +66 -0
  70. package/src/trails/project.ts +17 -3
  71. package/src/trails/regrade.ts +3091 -0
  72. package/src/trails/release-check.ts +105 -0
  73. package/src/trails/release-smoke.ts +49 -0
  74. package/src/trails/revise.ts +53 -0
  75. package/src/trails/root-dir.ts +21 -0
  76. package/src/trails/run-example.ts +475 -0
  77. package/src/trails/run-examples.ts +129 -0
  78. package/src/trails/run.ts +434 -0
  79. package/src/trails/scaffold-json.ts +58 -0
  80. package/src/trails/survey.ts +877 -214
  81. package/src/trails/topo-activation.ts +14 -0
  82. package/src/trails/topo-constants.ts +2 -0
  83. package/src/trails/topo-history.ts +47 -0
  84. package/src/trails/topo-output-schemas.ts +259 -0
  85. package/src/trails/topo-pin.ts +38 -0
  86. package/src/trails/topo-read-support.ts +368 -0
  87. package/src/trails/topo-reports.ts +809 -0
  88. package/src/trails/topo-store-support.ts +325 -0
  89. package/src/trails/topo-support.ts +220 -0
  90. package/src/trails/topo-unpin.ts +61 -0
  91. package/src/trails/topo.ts +92 -0
  92. package/src/trails/validate.ts +27 -0
  93. package/src/trails/version-lifecycle-support.ts +936 -0
  94. package/src/trails/warden-guide.ts +134 -0
  95. package/src/trails/warden.ts +198 -58
  96. package/src/trails/wayfind-outline.ts +876 -0
  97. package/src/trails/wayfind.ts +1053 -0
  98. package/src/versions.ts +31 -0
  99. package/.turbo/turbo-build.log +0 -1
  100. package/.turbo/turbo-lint.log +0 -3
  101. package/.turbo/turbo-typecheck.log +0 -1
  102. package/__tests__/examples.test.ts +0 -6
  103. package/dist/bin/trails.d.ts +0 -3
  104. package/dist/bin/trails.d.ts.map +0 -1
  105. package/dist/bin/trails.js +0 -4
  106. package/dist/bin/trails.js.map +0 -1
  107. package/dist/src/app.d.ts +0 -2
  108. package/dist/src/app.d.ts.map +0 -1
  109. package/dist/src/app.js +0 -11
  110. package/dist/src/app.js.map +0 -1
  111. package/dist/src/clack.d.ts +0 -9
  112. package/dist/src/clack.d.ts.map +0 -1
  113. package/dist/src/clack.js +0 -84
  114. package/dist/src/clack.js.map +0 -1
  115. package/dist/src/cli.d.ts +0 -2
  116. package/dist/src/cli.d.ts.map +0 -1
  117. package/dist/src/cli.js +0 -13
  118. package/dist/src/cli.js.map +0 -1
  119. package/dist/src/trails/add-surface.d.ts +0 -13
  120. package/dist/src/trails/add-surface.d.ts.map +0 -1
  121. package/dist/src/trails/add-surface.js +0 -88
  122. package/dist/src/trails/add-surface.js.map +0 -1
  123. package/dist/src/trails/add-trail.d.ts +0 -10
  124. package/dist/src/trails/add-trail.d.ts.map +0 -1
  125. package/dist/src/trails/add-trail.js +0 -77
  126. package/dist/src/trails/add-trail.js.map +0 -1
  127. package/dist/src/trails/add-verify.d.ts +0 -10
  128. package/dist/src/trails/add-verify.d.ts.map +0 -1
  129. package/dist/src/trails/add-verify.js +0 -67
  130. package/dist/src/trails/add-verify.js.map +0 -1
  131. package/dist/src/trails/create-scaffold.d.ts +0 -15
  132. package/dist/src/trails/create-scaffold.d.ts.map +0 -1
  133. package/dist/src/trails/create-scaffold.js +0 -288
  134. package/dist/src/trails/create-scaffold.js.map +0 -1
  135. package/dist/src/trails/create.d.ts +0 -22
  136. package/dist/src/trails/create.d.ts.map +0 -1
  137. package/dist/src/trails/create.js +0 -121
  138. package/dist/src/trails/create.js.map +0 -1
  139. package/dist/src/trails/guide.d.ts +0 -11
  140. package/dist/src/trails/guide.d.ts.map +0 -1
  141. package/dist/src/trails/guide.js +0 -80
  142. package/dist/src/trails/guide.js.map +0 -1
  143. package/dist/src/trails/load-app.d.ts +0 -4
  144. package/dist/src/trails/load-app.d.ts.map +0 -1
  145. package/dist/src/trails/load-app.js +0 -24
  146. package/dist/src/trails/load-app.js.map +0 -1
  147. package/dist/src/trails/project.d.ts +0 -8
  148. package/dist/src/trails/project.d.ts.map +0 -1
  149. package/dist/src/trails/project.js +0 -43
  150. package/dist/src/trails/project.js.map +0 -1
  151. package/dist/src/trails/survey.d.ts +0 -31
  152. package/dist/src/trails/survey.d.ts.map +0 -1
  153. package/dist/src/trails/survey.js +0 -221
  154. package/dist/src/trails/survey.js.map +0 -1
  155. package/dist/src/trails/warden.d.ts +0 -19
  156. package/dist/src/trails/warden.d.ts.map +0 -1
  157. package/dist/src/trails/warden.js +0 -88
  158. package/dist/src/trails/warden.js.map +0 -1
  159. package/dist/tsconfig.tsbuildinfo +0 -1
  160. package/src/__tests__/create.test.ts +0 -349
  161. package/src/__tests__/guide.test.ts +0 -91
  162. package/src/__tests__/load-app.test.ts +0 -15
  163. package/src/__tests__/survey.test.ts +0 -159
  164. package/src/__tests__/warden.test.ts +0 -74
  165. package/tsconfig.json +0 -9
@@ -0,0 +1,105 @@
1
+ /**
2
+ * `release.check` trail -- Branch-local release rule evaluation.
3
+ */
4
+
5
+ import { Result, trail, ValidationError } from '@ontrails/core';
6
+ import { z } from 'zod';
7
+
8
+ import { runReleaseCheck } from '../release/check.js';
9
+ import { resolveTrailRootDir } from './root-dir.js';
10
+
11
+ const releaseCheckInputSchema = z.object({
12
+ baseRef: z
13
+ .string()
14
+ .optional()
15
+ .describe('Base git ref for changed-file and contract fact comparison'),
16
+ changedFiles: z
17
+ .string()
18
+ .optional()
19
+ .describe('Path to a newline-delimited changed-file list'),
20
+ configPath: z.string().optional().describe('Path to trails.config.ts'),
21
+ releaseNone: z
22
+ .boolean()
23
+ .default(false)
24
+ .describe('Compatibility no-release override'),
25
+ rootDir: z.string().optional().describe('Workspace root directory'),
26
+ });
27
+
28
+ const contractReleaseFactAspectSchema = z.enum([
29
+ 'input',
30
+ 'output',
31
+ 'surfaces',
32
+ 'trail',
33
+ 'visibility',
34
+ ]);
35
+
36
+ const contractReleaseFactSchema = z.object({
37
+ aspect: contractReleaseFactAspectSchema,
38
+ baseHash: z.string().nullable(),
39
+ changedFiles: z.array(z.string()).readonly(),
40
+ currentHash: z.string().nullable(),
41
+ packageName: z.string().optional(),
42
+ path: z.string(),
43
+ trailId: z.string(),
44
+ workspacePath: z.string().optional(),
45
+ });
46
+
47
+ const releaseCheckOutputSchema = z.object({
48
+ activePackageChangesetsWithoutReleaseFacts: z.array(z.string()).readonly(),
49
+ affectedPackages: z.array(z.string()).readonly(),
50
+ changedChangesets: z.array(z.string()).readonly(),
51
+ configPath: z.string().optional(),
52
+ contractFacts: z.array(contractReleaseFactSchema).readonly(),
53
+ coveredPackages: z.array(z.string()).readonly(),
54
+ errors: z.array(z.string()).readonly(),
55
+ formatted: z.string(),
56
+ matchedRuleIds: z.array(z.string()).readonly(),
57
+ noReleaseOverride: z.boolean(),
58
+ passed: z.boolean(),
59
+ releaseNone: z.boolean(),
60
+ uncoveredContractFacts: z.array(contractReleaseFactSchema).readonly(),
61
+ versionRelease: z.boolean(),
62
+ });
63
+
64
+ export const releaseCheckTrail = trail('release.check', {
65
+ description: 'Check branch-local release rules',
66
+ examples: [
67
+ {
68
+ input: { baseRef: 'HEAD' },
69
+ name: 'Check release rules from the current HEAD',
70
+ },
71
+ ],
72
+ implementation: async (input, ctx) => {
73
+ const rootDirResult = resolveTrailRootDir(input.rootDir, ctx.cwd);
74
+ if (rootDirResult.isErr()) {
75
+ return rootDirResult;
76
+ }
77
+
78
+ try {
79
+ return Result.ok(
80
+ await runReleaseCheck({
81
+ ...(input.baseRef === undefined ? {} : { baseRef: input.baseRef }),
82
+ ...(input.changedFiles === undefined
83
+ ? {}
84
+ : { changedFilesPath: input.changedFiles }),
85
+ ...(input.configPath === undefined
86
+ ? {}
87
+ : { configPath: input.configPath }),
88
+ env: ctx.env ?? {},
89
+ releaseNone: input.releaseNone,
90
+ repoRoot: rootDirResult.value,
91
+ })
92
+ );
93
+ } catch (error) {
94
+ return Result.err(
95
+ new ValidationError(
96
+ error instanceof Error ? error.message : String(error)
97
+ )
98
+ );
99
+ }
100
+ },
101
+ input: releaseCheckInputSchema,
102
+ intent: 'read',
103
+ output: releaseCheckOutputSchema,
104
+ permit: 'public',
105
+ });
@@ -0,0 +1,49 @@
1
+ /**
2
+ * `release.smoke` trail -- Local release confidence checks.
3
+ */
4
+
5
+ import { Result, trail, ValidationError } from '@ontrails/core';
6
+ import { z } from 'zod';
7
+
8
+ import { releaseSmokeCheckValues, runReleaseSmoke } from '../release/smoke.js';
9
+
10
+ const releaseSmokeCheckSchema = z.enum(releaseSmokeCheckValues);
11
+
12
+ const releaseSmokeInputSchema = z.object({
13
+ check: z.string().default('all').describe('Release smoke check to run'),
14
+ });
15
+
16
+ const releaseSmokeCheckResultSchema = z.object({
17
+ check: z.enum(['lock-roundtrip', 'packed-artifacts', 'wayfinder-dogfood']),
18
+ lockCount: z.number().optional(),
19
+ message: z.string(),
20
+ packageCount: z.number().optional(),
21
+ passed: z.literal(true),
22
+ trailCount: z.number().optional(),
23
+ });
24
+
25
+ const releaseSmokeOutputSchema = z.object({
26
+ checks: z.array(releaseSmokeCheckResultSchema).readonly(),
27
+ message: z.string(),
28
+ passed: z.literal(true),
29
+ });
30
+
31
+ export const releaseSmokeTrail = trail('release.smoke', {
32
+ description: 'Run local release confidence smoke checks',
33
+ implementation: async (input) => {
34
+ try {
35
+ const check = releaseSmokeCheckSchema.parse(input.check);
36
+ return Result.ok(await runReleaseSmoke(check));
37
+ } catch (error) {
38
+ return Result.err(
39
+ new ValidationError(
40
+ error instanceof Error ? error.message : String(error)
41
+ )
42
+ );
43
+ }
44
+ },
45
+ input: releaseSmokeInputSchema,
46
+ intent: 'read',
47
+ output: releaseSmokeOutputSchema,
48
+ permit: 'public',
49
+ });
@@ -0,0 +1,53 @@
1
+ import { Result, ValidationError, trail } from '@ontrails/core';
2
+ import { z } from 'zod';
3
+
4
+ import {
5
+ findLifecycleTrail,
6
+ forkVersionEntrySource,
7
+ parseLifecycleTarget,
8
+ reviseTrailSource,
9
+ withLifecycleApp,
10
+ } from './version-lifecycle-support.js';
11
+
12
+ export const reviseTrail = trail('revise', {
13
+ args: ['target'],
14
+ description: 'Scaffold the next trail version entry',
15
+ implementation: async (input, ctx) =>
16
+ withLifecycleApp(input, ctx.cwd, async (app, rootDir) => {
17
+ const target = parseLifecycleTarget(input.target);
18
+ if (target.isErr()) {
19
+ return target;
20
+ }
21
+ if (target.value.version !== undefined) {
22
+ return input.as === 'fork'
23
+ ? forkVersionEntrySource(rootDir, target.value)
24
+ : Result.err(
25
+ new ValidationError(
26
+ 'Revising a specific historical entry requires --as fork'
27
+ )
28
+ );
29
+ }
30
+ const found = findLifecycleTrail(app, target.value.trailId);
31
+ if (found.isErr()) {
32
+ return found;
33
+ }
34
+ return reviseTrailSource(rootDir, found.value, input.as);
35
+ }),
36
+ input: z.object({
37
+ as: z
38
+ .enum(['revision', 'fork'])
39
+ .default('revision')
40
+ .describe('Version entry shape to scaffold'),
41
+ module: z.string().optional().describe('Path to the app module'),
42
+ rootDir: z.string().optional().describe('Workspace root directory'),
43
+ target: z.string().min(1).describe('Trail target, optionally trail.id@N'),
44
+ }),
45
+ intent: 'write',
46
+ output: z.object({
47
+ filePath: z.string(),
48
+ trailId: z.string(),
49
+ updated: z.boolean(),
50
+ warnings: z.array(z.string()).optional(),
51
+ }),
52
+ permit: { scopes: ['version:write'] },
53
+ });
@@ -0,0 +1,21 @@
1
+ import { Result, ValidationError } from '@ontrails/core';
2
+
3
+ const ROOT_DIR_MESSAGE =
4
+ 'Trail execution requires rootDir input or ctx.cwd from the runtime context.';
5
+
6
+ export const resolveTrailRootDir = (
7
+ rootDir: string | undefined,
8
+ cwd: string | undefined
9
+ ): Result<string, ValidationError> => {
10
+ const resolved = rootDir ?? cwd;
11
+ return resolved === undefined
12
+ ? Result.err(new ValidationError(ROOT_DIR_MESSAGE))
13
+ : Result.ok(resolved);
14
+ };
15
+
16
+ export const requireTrailRootDir = (rootDir: string | undefined): string => {
17
+ if (rootDir === undefined) {
18
+ throw new ValidationError(ROOT_DIR_MESSAGE);
19
+ }
20
+ return rootDir;
21
+ };
@@ -0,0 +1,475 @@
1
+ /**
2
+ * `run.example` trail -- run one named example and compare the result.
3
+ */
4
+
5
+ import {
6
+ NotFoundError,
7
+ Result,
8
+ TrailsError,
9
+ deriveStructuredTrailExamples,
10
+ run,
11
+ trail,
12
+ } from '@ontrails/core';
13
+ import type { BasePermit, StructuredTrailExample, Topo } from '@ontrails/core';
14
+ import { z } from 'zod';
15
+
16
+ import { withFreshAppLease, withOperatorRootDir } from './operator-context.js';
17
+ import { resolveRunModulePath } from './run.js';
18
+ import { createIsolatedExampleInput } from './topo-support.js';
19
+
20
+ export const RUN_EXAMPLE_COMPARISON_KIND = 'example-comparison' as const;
21
+
22
+ export const runExampleComparisonSchema = z.object({
23
+ actual: z.unknown(),
24
+ diff: z.array(z.string()).readonly().optional(),
25
+ exampleName: z.string(),
26
+ expected: z.unknown(),
27
+ input: z.unknown(),
28
+ kind: z.literal(RUN_EXAMPLE_COMPARISON_KIND),
29
+ match: z.boolean(),
30
+ mode: z.union([
31
+ z.literal('expected'),
32
+ z.literal('expectedMatch'),
33
+ z.literal('error'),
34
+ z.literal('none'),
35
+ ]),
36
+ trailId: z.string(),
37
+ });
38
+
39
+ export type RunExampleComparison = z.infer<typeof runExampleComparisonSchema>;
40
+ export type RunExampleComparisonMode = RunExampleComparison['mode'];
41
+
42
+ interface ActualOutcomeOk {
43
+ readonly outcome: 'ok';
44
+ readonly value: unknown;
45
+ }
46
+
47
+ interface ActualOutcomeErr {
48
+ readonly errorCategory?: string;
49
+ readonly errorClassName: string;
50
+ readonly errorMessage: string;
51
+ readonly outcome: 'err';
52
+ }
53
+
54
+ type ActualOutcome = ActualOutcomeOk | ActualOutcomeErr;
55
+
56
+ const buildHappyExampleInput = (): {
57
+ readonly exampleName: string;
58
+ readonly id: string;
59
+ readonly module: string;
60
+ readonly rootDir: string;
61
+ } => ({
62
+ ...createIsolatedExampleInput('run-example-happy'),
63
+ exampleName: 'Brief capability report',
64
+ id: 'survey.brief',
65
+ });
66
+
67
+ const projectActual = (result: Result<unknown, Error>): ActualOutcome => {
68
+ if (result.isOk()) {
69
+ return { outcome: 'ok', value: result.value };
70
+ }
71
+ const { error } = result;
72
+ return {
73
+ errorClassName: error.constructor.name,
74
+ errorMessage: error.message,
75
+ outcome: 'err',
76
+ ...(error instanceof TrailsError ? { errorCategory: error.category } : {}),
77
+ };
78
+ };
79
+
80
+ const formatLeaf = (value: unknown): string => {
81
+ try {
82
+ const encoded = JSON.stringify(value);
83
+ return encoded === undefined ? String(value) : encoded;
84
+ } catch {
85
+ return String(value);
86
+ }
87
+ };
88
+
89
+ const formatPath = (segments: readonly string[]): string =>
90
+ segments.length === 0 ? 'value' : `value.${segments.join('.')}`;
91
+
92
+ const isPlainObject = (value: unknown): value is Record<string, unknown> =>
93
+ typeof value === 'object' && value !== null && !Array.isArray(value);
94
+
95
+ const deepEqualWithDiff = (
96
+ actual: unknown,
97
+ expected: unknown,
98
+ path: readonly string[],
99
+ diffs: string[]
100
+ ): boolean => {
101
+ if (Array.isArray(expected)) {
102
+ if (!Array.isArray(actual)) {
103
+ diffs.push(`${formatPath(path)}: expected array, got ${typeof actual}`);
104
+ return false;
105
+ }
106
+ if (actual.length !== expected.length) {
107
+ diffs.push(
108
+ `${formatPath(path)}: array length ${actual.length} != ${expected.length}`
109
+ );
110
+ return false;
111
+ }
112
+ let ok = true;
113
+ for (let i = 0; i < expected.length; i += 1) {
114
+ if (
115
+ !deepEqualWithDiff(actual[i], expected[i], [...path, `[${i}]`], diffs)
116
+ ) {
117
+ ok = false;
118
+ }
119
+ }
120
+ return ok;
121
+ }
122
+
123
+ if (isPlainObject(expected)) {
124
+ if (!isPlainObject(actual)) {
125
+ diffs.push(`${formatPath(path)}: expected object, got ${typeof actual}`);
126
+ return false;
127
+ }
128
+ let ok = true;
129
+ for (const key of Object.keys(expected)) {
130
+ if (!(key in actual)) {
131
+ diffs.push(`${formatPath([...path, key])}: missing in actual`);
132
+ ok = false;
133
+ continue;
134
+ }
135
+ if (
136
+ !deepEqualWithDiff(actual[key], expected[key], [...path, key], diffs)
137
+ ) {
138
+ ok = false;
139
+ }
140
+ }
141
+ for (const key of Object.keys(actual)) {
142
+ if (!(key in expected)) {
143
+ diffs.push(`${formatPath([...path, key])}: unexpected key in actual`);
144
+ ok = false;
145
+ }
146
+ }
147
+ return ok;
148
+ }
149
+
150
+ if (actual !== expected) {
151
+ if (
152
+ typeof actual === 'number' &&
153
+ typeof expected === 'number' &&
154
+ Number.isNaN(actual) &&
155
+ Number.isNaN(expected)
156
+ ) {
157
+ return true;
158
+ }
159
+ diffs.push(
160
+ `${formatPath(path)}: ${formatLeaf(actual)} != ${formatLeaf(expected)}`
161
+ );
162
+ return false;
163
+ }
164
+ return true;
165
+ };
166
+
167
+ const partialMatchWithDiff = (
168
+ actual: unknown,
169
+ expected: unknown,
170
+ path: readonly string[],
171
+ diffs: string[]
172
+ ): boolean => {
173
+ if (Array.isArray(expected)) {
174
+ if (!Array.isArray(actual)) {
175
+ diffs.push(`${formatPath(path)}: expected array, got ${typeof actual}`);
176
+ return false;
177
+ }
178
+ let ok = true;
179
+ const consumed = new Set<number>();
180
+ for (const [index, expectedEntry] of expected.entries()) {
181
+ const matchIndex = actual.findIndex((candidate, candidateIndex) => {
182
+ if (consumed.has(candidateIndex)) {
183
+ return false;
184
+ }
185
+ const probe: string[] = [];
186
+ return partialMatchWithDiff(candidate, expectedEntry, [], probe);
187
+ });
188
+ if (matchIndex === -1) {
189
+ diffs.push(
190
+ `${formatPath([...path, `[${index}]`])}: expected array to contain ${formatLeaf(expectedEntry)}`
191
+ );
192
+ ok = false;
193
+ continue;
194
+ }
195
+ consumed.add(matchIndex);
196
+ }
197
+ return ok;
198
+ }
199
+
200
+ if (isPlainObject(expected)) {
201
+ if (!isPlainObject(actual)) {
202
+ diffs.push(`${formatPath(path)}: expected object, got ${typeof actual}`);
203
+ return false;
204
+ }
205
+ let ok = true;
206
+ for (const key of Object.keys(expected)) {
207
+ if (!(key in actual)) {
208
+ diffs.push(`${formatPath([...path, key])}: missing in actual`);
209
+ ok = false;
210
+ continue;
211
+ }
212
+ if (
213
+ !partialMatchWithDiff(actual[key], expected[key], [...path, key], diffs)
214
+ ) {
215
+ ok = false;
216
+ }
217
+ }
218
+ return ok;
219
+ }
220
+
221
+ if (actual !== expected) {
222
+ diffs.push(
223
+ `${formatPath(path)}: ${formatLeaf(actual)} != ${formatLeaf(expected)}`
224
+ );
225
+ return false;
226
+ }
227
+ return true;
228
+ };
229
+
230
+ const compareExpected = (
231
+ result: Result<unknown, Error>,
232
+ expected: unknown
233
+ ): {
234
+ readonly diff?: readonly string[] | undefined;
235
+ readonly match: boolean;
236
+ } => {
237
+ if (result.isErr()) {
238
+ return {
239
+ diff: [
240
+ `value: expected Result.ok(...), got Result.err(${result.error.constructor.name}: ${result.error.message})`,
241
+ ],
242
+ match: false,
243
+ };
244
+ }
245
+ const diffs: string[] = [];
246
+ const match = deepEqualWithDiff(result.value, expected, [], diffs);
247
+ return { diff: match ? undefined : diffs, match };
248
+ };
249
+
250
+ const compareExpectedMatch = (
251
+ result: Result<unknown, Error>,
252
+ expectedMatch: unknown
253
+ ): {
254
+ readonly diff?: readonly string[] | undefined;
255
+ readonly match: boolean;
256
+ } => {
257
+ if (result.isErr()) {
258
+ return {
259
+ diff: [
260
+ `value: expected Result.ok(...), got Result.err(${result.error.constructor.name}: ${result.error.message})`,
261
+ ],
262
+ match: false,
263
+ };
264
+ }
265
+ const diffs: string[] = [];
266
+ const match = partialMatchWithDiff(result.value, expectedMatch, [], diffs);
267
+ return { diff: match ? undefined : diffs, match };
268
+ };
269
+
270
+ const compareError = (
271
+ result: Result<unknown, Error>,
272
+ expectedErrorName: string
273
+ ): {
274
+ readonly diff?: readonly string[] | undefined;
275
+ readonly match: boolean;
276
+ } => {
277
+ if (result.isOk()) {
278
+ return {
279
+ diff: [
280
+ `value: expected Result.err(${expectedErrorName}), got Result.ok(${formatLeaf(result.value)})`,
281
+ ],
282
+ match: false,
283
+ };
284
+ }
285
+ const className = result.error.constructor.name;
286
+ if (className === expectedErrorName) {
287
+ return { diff: undefined, match: true };
288
+ }
289
+ return {
290
+ diff: [
291
+ `value: expected Result.err(${expectedErrorName}), got Result.err(${className}: ${result.error.message})`,
292
+ ],
293
+ match: false,
294
+ };
295
+ };
296
+
297
+ const findExample = (
298
+ app: Topo,
299
+ trailId: string,
300
+ exampleName: string
301
+ ): Result<StructuredTrailExample, Error> => {
302
+ const target = app.get(trailId);
303
+ if (target === undefined) {
304
+ return Result.err(
305
+ new NotFoundError(
306
+ `Trail '${trailId}' was not found in the resolved app.`,
307
+ { context: { trailId } }
308
+ )
309
+ );
310
+ }
311
+
312
+ const structured = deriveStructuredTrailExamples(target.examples) ?? [];
313
+ const match = structured.find((entry) => entry.name === exampleName);
314
+ if (match !== undefined) {
315
+ return Result.ok(match);
316
+ }
317
+
318
+ const available = structured.map((entry) => entry.name);
319
+ const listing = available.length === 0 ? '<none>' : available.join(', ');
320
+ return Result.err(
321
+ new NotFoundError(
322
+ `Example '${exampleName}' not found on trail '${trailId}'. Available: ${listing}.`,
323
+ {
324
+ context: {
325
+ available,
326
+ exampleName,
327
+ trailId,
328
+ },
329
+ }
330
+ )
331
+ );
332
+ };
333
+
334
+ const determineMode = (
335
+ example: StructuredTrailExample
336
+ ): RunExampleComparisonMode => {
337
+ if (example.error !== undefined) {
338
+ return 'error';
339
+ }
340
+ if (example.expectedMatch !== undefined) {
341
+ return 'expectedMatch';
342
+ }
343
+ if (example.expected !== undefined) {
344
+ return 'expected';
345
+ }
346
+ return 'none';
347
+ };
348
+
349
+ const buildComparisonEnvelope = async (
350
+ app: Topo,
351
+ trailId: string,
352
+ exampleName: string,
353
+ permit: BasePermit | undefined
354
+ ): Promise<Result<RunExampleComparison, Error>> => {
355
+ const exampleResult = findExample(app, trailId, exampleName);
356
+ if (exampleResult.isErr()) {
357
+ return exampleResult;
358
+ }
359
+ const example = exampleResult.value;
360
+ const mode = determineMode(example);
361
+ const executed = await run(app, trailId, example.input, {
362
+ ctx: permit === undefined ? {} : { permit },
363
+ });
364
+ const actual = projectActual(executed);
365
+
366
+ if (mode === 'error') {
367
+ const expectedName = example.error ?? '';
368
+ const { diff, match } = compareError(executed, expectedName);
369
+ return Result.ok({
370
+ actual,
371
+ diff,
372
+ exampleName,
373
+ expected: { errorClassName: expectedName },
374
+ input: example.input,
375
+ kind: RUN_EXAMPLE_COMPARISON_KIND,
376
+ match,
377
+ mode,
378
+ trailId,
379
+ });
380
+ }
381
+ if (mode === 'expectedMatch') {
382
+ const { diff, match } = compareExpectedMatch(
383
+ executed,
384
+ example.expectedMatch
385
+ );
386
+ return Result.ok({
387
+ actual,
388
+ diff,
389
+ exampleName,
390
+ expected: example.expectedMatch,
391
+ input: example.input,
392
+ kind: RUN_EXAMPLE_COMPARISON_KIND,
393
+ match,
394
+ mode,
395
+ trailId,
396
+ });
397
+ }
398
+ if (mode === 'none') {
399
+ return Result.ok({
400
+ actual,
401
+ exampleName,
402
+ expected: undefined,
403
+ input: example.input,
404
+ kind: RUN_EXAMPLE_COMPARISON_KIND,
405
+ match: true,
406
+ mode,
407
+ trailId,
408
+ });
409
+ }
410
+
411
+ const { diff, match } = compareExpected(executed, example.expected);
412
+ return Result.ok({
413
+ actual,
414
+ diff,
415
+ exampleName,
416
+ expected: example.expected,
417
+ input: example.input,
418
+ kind: RUN_EXAMPLE_COMPARISON_KIND,
419
+ match,
420
+ mode,
421
+ trailId,
422
+ });
423
+ };
424
+
425
+ const runExampleTrailInputSchema = z.object({
426
+ app: z
427
+ .string()
428
+ .optional()
429
+ .describe(
430
+ 'Workspace app to resolve the trail ID against; required when the ID is exposed by more than one app'
431
+ ),
432
+ exampleName: z.string().describe('Name of the example to run'),
433
+ id: z.string().describe('Trail ID whose example should run'),
434
+ module: z.string().optional().describe('Path to the app module'),
435
+ rootDir: z.string().optional().describe('Workspace root directory'),
436
+ });
437
+
438
+ type RunExampleTrailInput = z.output<typeof runExampleTrailInputSchema>;
439
+
440
+ export const runExampleTrail = trail('run.example', {
441
+ args: ['id', 'exampleName'],
442
+ description: 'Run a named example on a trail and compare actual vs expected',
443
+ examples: [
444
+ {
445
+ description: 'Run a named example on a target trail',
446
+ input: buildHappyExampleInput(),
447
+ name: 'Run named example',
448
+ },
449
+ ],
450
+ implementation: async (input: RunExampleTrailInput, ctx) =>
451
+ withOperatorRootDir(input, ctx, async (rootDir) => {
452
+ const moduleResolution = await resolveRunModulePath(
453
+ rootDir,
454
+ input.module,
455
+ input.id,
456
+ input.app
457
+ );
458
+ if (moduleResolution.isErr()) {
459
+ return moduleResolution;
460
+ }
461
+
462
+ return withFreshAppLease(moduleResolution.value, rootDir, (lease) =>
463
+ buildComparisonEnvelope(
464
+ lease.app,
465
+ input.id,
466
+ input.exampleName,
467
+ ctx.permit
468
+ )
469
+ );
470
+ }),
471
+ input: runExampleTrailInputSchema,
472
+ intent: 'write',
473
+ output: runExampleComparisonSchema,
474
+ permit: { scopes: ['trails:run'] },
475
+ });