@ontrails/trails 0.2.0

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 (121) hide show
  1. package/CHANGELOG.md +1906 -0
  2. package/README.md +48 -0
  3. package/bin/trails.ts +3 -0
  4. package/package.json +57 -0
  5. package/src/app.ts +167 -0
  6. package/src/clack.ts +111 -0
  7. package/src/cli.ts +308 -0
  8. package/src/completions.ts +431 -0
  9. package/src/lifecycle-source-io.ts +33 -0
  10. package/src/load-app-mirror.ts +202 -0
  11. package/src/local-state-io.ts +129 -0
  12. package/src/mcp-app.ts +42 -0
  13. package/src/mcp-options.ts +92 -0
  14. package/src/mcp.ts +8 -0
  15. package/src/project-writes.ts +377 -0
  16. package/src/regrade/audit.ts +571 -0
  17. package/src/regrade/config.ts +152 -0
  18. package/src/regrade/history.ts +636 -0
  19. package/src/regrade/lifecycle.ts +76 -0
  20. package/src/regrade/live-api-preserve.ts +123 -0
  21. package/src/regrade/plan-artifact.ts +515 -0
  22. package/src/regrade/plan-derivation.ts +301 -0
  23. package/src/regrade/prepared-run.ts +259 -0
  24. package/src/regrade/receipt-history.ts +446 -0
  25. package/src/regrade/source-transaction.ts +185 -0
  26. package/src/release/bindings.ts +58 -0
  27. package/src/release/changeset-packages.ts +99 -0
  28. package/src/release/check.ts +1191 -0
  29. package/src/release/cli-bundle.ts +575 -0
  30. package/src/release/config.ts +73 -0
  31. package/src/release/contract-facts.ts +425 -0
  32. package/src/release/homebrew.ts +221 -0
  33. package/src/release/index.ts +180 -0
  34. package/src/release/lock-roundtrip-smoke.ts +255 -0
  35. package/src/release/lock-roundtrip-workspace.ts +107 -0
  36. package/src/release/native-bun-publish.ts +964 -0
  37. package/src/release/native-bun-registry.ts +848 -0
  38. package/src/release/notes-cli.ts +171 -0
  39. package/src/release/notes.ts +390 -0
  40. package/src/release/pack-coherence.ts +455 -0
  41. package/src/release/package-route-facts.ts +146 -0
  42. package/src/release/packed-artifacts-smoke.ts +236 -0
  43. package/src/release/policy.ts +1780 -0
  44. package/src/release/semver.ts +104 -0
  45. package/src/release/smoke.ts +56 -0
  46. package/src/release/stable-version-release.ts +80 -0
  47. package/src/release/wayfinder-dogfood-smoke.ts +762 -0
  48. package/src/release/zero-line-transition.ts +68 -0
  49. package/src/retired-topo-command.ts +36 -0
  50. package/src/run-adapter-check.ts +76 -0
  51. package/src/run-argv.ts +133 -0
  52. package/src/run-collision.ts +126 -0
  53. package/src/run-completions-install.ts +179 -0
  54. package/src/run-example.ts +149 -0
  55. package/src/run-examples.ts +148 -0
  56. package/src/run-quiet.ts +75 -0
  57. package/src/run-regrade-progress.ts +47 -0
  58. package/src/run-release-check.ts +74 -0
  59. package/src/run-schema.ts +74 -0
  60. package/src/run-trace.ts +273 -0
  61. package/src/run-warden.ts +39 -0
  62. package/src/run-watch-project.ts +52 -0
  63. package/src/run-watch.ts +381 -0
  64. package/src/run-wayfind-outline.ts +170 -0
  65. package/src/scaffold-version-sync.ts +183 -0
  66. package/src/scaffold-versions.generated.ts +12 -0
  67. package/src/trails/adapter-check.ts +244 -0
  68. package/src/trails/add-surface.ts +816 -0
  69. package/src/trails/add-trail.ts +141 -0
  70. package/src/trails/add-verify.ts +252 -0
  71. package/src/trails/compile.ts +118 -0
  72. package/src/trails/completions-complete.ts +236 -0
  73. package/src/trails/completions.ts +47 -0
  74. package/src/trails/config-explain.ts +43 -0
  75. package/src/trails/create-adapter.ts +785 -0
  76. package/src/trails/create-scaffold.ts +1215 -0
  77. package/src/trails/create-versions.ts +62 -0
  78. package/src/trails/create.ts +652 -0
  79. package/src/trails/deprecate.ts +59 -0
  80. package/src/trails/dev-clean.ts +80 -0
  81. package/src/trails/dev-reset.ts +48 -0
  82. package/src/trails/dev-stats.ts +71 -0
  83. package/src/trails/dev-support.ts +360 -0
  84. package/src/trails/doctor.ts +77 -0
  85. package/src/trails/draft-promote.ts +949 -0
  86. package/src/trails/guide.ts +106 -0
  87. package/src/trails/load-app.ts +1145 -0
  88. package/src/trails/operator-context.ts +66 -0
  89. package/src/trails/project-context-output.ts +304 -0
  90. package/src/trails/project-context.ts +613 -0
  91. package/src/trails/project.ts +65 -0
  92. package/src/trails/regrade.ts +4951 -0
  93. package/src/trails/release-check.ts +113 -0
  94. package/src/trails/release-smoke.ts +49 -0
  95. package/src/trails/revise.ts +53 -0
  96. package/src/trails/root-dir.ts +21 -0
  97. package/src/trails/run-example.ts +592 -0
  98. package/src/trails/run-examples.ts +149 -0
  99. package/src/trails/run.ts +496 -0
  100. package/src/trails/scaffold-json.ts +60 -0
  101. package/src/trails/scaffold-topo-identity.ts +479 -0
  102. package/src/trails/survey.ts +990 -0
  103. package/src/trails/topo-activation.ts +14 -0
  104. package/src/trails/topo-constants.ts +2 -0
  105. package/src/trails/topo-history.ts +47 -0
  106. package/src/trails/topo-output-schemas.ts +259 -0
  107. package/src/trails/topo-pin.ts +38 -0
  108. package/src/trails/topo-read-support.ts +368 -0
  109. package/src/trails/topo-reports.ts +809 -0
  110. package/src/trails/topo-store-support.ts +323 -0
  111. package/src/trails/topo-support.ts +247 -0
  112. package/src/trails/topo-unpin.ts +61 -0
  113. package/src/trails/topo.ts +92 -0
  114. package/src/trails/validate.ts +348 -0
  115. package/src/trails/version-lifecycle-support.ts +936 -0
  116. package/src/trails/warden-guide.ts +134 -0
  117. package/src/trails/warden.ts +598 -0
  118. package/src/trails/wayfind-diff.ts +716 -0
  119. package/src/trails/wayfind-outline.ts +876 -0
  120. package/src/trails/wayfind.ts +1319 -0
  121. package/src/versions.ts +31 -0
@@ -0,0 +1,129 @@
1
+ import { existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { tmpdir } from 'node:os';
3
+ import { dirname, isAbsolute, join } from 'node:path';
4
+ import { pathToFileURL } from 'node:url';
5
+
6
+ import {
7
+ deriveSafePath,
8
+ InternalError,
9
+ Result,
10
+ ValidationError,
11
+ } from '@ontrails/core';
12
+ import type { Result as TrailsResult } from '@ontrails/core';
13
+
14
+ const EXAMPLE_ROOT_PARENT = join(tmpdir(), 'ontrails-trails-examples');
15
+ const EXAMPLE_ROOT_NAME_PATTERN = /^[a-z0-9][a-z0-9._-]*$/u;
16
+
17
+ const asError = (error: unknown): Error =>
18
+ error instanceof Error ? error : new Error(String(error));
19
+
20
+ const resolveExampleRoot = (name: string): TrailsResult<string, Error> => {
21
+ if (!EXAMPLE_ROOT_NAME_PATTERN.test(name)) {
22
+ return Result.err(
23
+ new ValidationError(
24
+ 'Example root name must be lowercase and contain only letters, digits, ".", "_", or "-".',
25
+ { context: { name } }
26
+ )
27
+ );
28
+ }
29
+
30
+ return deriveSafePath(EXAMPLE_ROOT_PARENT, name);
31
+ };
32
+
33
+ export const createIsolatedExampleRoot = (name: string): string => {
34
+ const root = resolveExampleRoot(name);
35
+ if (root.isErr()) {
36
+ throw root.error;
37
+ }
38
+
39
+ try {
40
+ rmSync(root.value, { force: true, recursive: true });
41
+ mkdirSync(root.value, { recursive: true });
42
+ return root.value;
43
+ } catch (error) {
44
+ throw new InternalError(`Failed to recreate example root "${name}"`, {
45
+ cause: asError(error),
46
+ context: { name, rootDir: root.value },
47
+ });
48
+ }
49
+ };
50
+
51
+ export const writeIsolatedExampleAppModule = (
52
+ rootDir: string,
53
+ sourceModulePath: string
54
+ ): string => {
55
+ if (!isAbsolute(sourceModulePath)) {
56
+ throw new ValidationError(
57
+ 'Example app source module path must be absolute.',
58
+ {
59
+ context: { rootDir, sourceModulePath },
60
+ }
61
+ );
62
+ }
63
+
64
+ const modulePath = './src/app.ts';
65
+ const target = deriveSafePath(rootDir, modulePath);
66
+ if (target.isErr()) {
67
+ throw target.error;
68
+ }
69
+
70
+ try {
71
+ mkdirSync(dirname(target.value), { recursive: true });
72
+ writeFileSync(
73
+ target.value,
74
+ `export { app } from ${JSON.stringify(pathToFileURL(sourceModulePath).href)};\n`
75
+ );
76
+ return modulePath;
77
+ } catch (error) {
78
+ throw new InternalError('Failed to write isolated example app module', {
79
+ cause: asError(error),
80
+ context: { rootDir, sourceModulePath, targetPath: target.value },
81
+ });
82
+ }
83
+ };
84
+
85
+ export const removeRootRelativeFileIfPresent = (
86
+ rootDir: string,
87
+ relativePath: string
88
+ ): TrailsResult<boolean, Error> => {
89
+ const target = deriveSafePath(rootDir, relativePath);
90
+ if (target.isErr()) {
91
+ return target;
92
+ }
93
+
94
+ if (!existsSync(target.value)) {
95
+ return Result.ok(false);
96
+ }
97
+
98
+ try {
99
+ rmSync(target.value, { force: true });
100
+ return Result.ok(true);
101
+ } catch (error) {
102
+ return Result.err(
103
+ new InternalError(`Failed to remove local state file "${relativePath}"`, {
104
+ cause: asError(error),
105
+ context: { relativePath, rootDir, targetPath: target.value },
106
+ })
107
+ );
108
+ }
109
+ };
110
+
111
+ export const removeFileIfPresent = (
112
+ path: string
113
+ ): TrailsResult<boolean, Error> => {
114
+ if (!existsSync(path)) {
115
+ return Result.ok(false);
116
+ }
117
+
118
+ try {
119
+ rmSync(path, { force: true });
120
+ return Result.ok(true);
121
+ } catch (error) {
122
+ return Result.err(
123
+ new InternalError(`Failed to remove local state file "${path}"`, {
124
+ cause: asError(error),
125
+ context: { path },
126
+ })
127
+ );
128
+ }
129
+ };
package/src/mcp-app.ts ADDED
@@ -0,0 +1,42 @@
1
+ import { topo } from '@ontrails/core';
2
+ import {
3
+ wayfindAdaptersTrail,
4
+ wayfindContractTrail,
5
+ wayfindDescribeTrail,
6
+ wayfindErrorsTrail,
7
+ wayfindExamplesTrail,
8
+ wayfindOverlayTrail,
9
+ wayfindImpactTrail,
10
+ wayfindNearbyTrail,
11
+ wayfindOverviewTrail,
12
+ wayfindResourcesTrail,
13
+ wayfindSearchTrail,
14
+ wayfindSurfacesTrail,
15
+ wayfindTrailsTrail,
16
+ } from '@ontrails/topography';
17
+
18
+ import { operatorApp } from './app.js';
19
+ import { wayfindDiffTrail } from './trails/wayfind.js';
20
+ import { wayfindOutlineTrail } from './trails/wayfind-outline.js';
21
+
22
+ const operatorTrails = Object.fromEntries(
23
+ operatorApp.list().map((trailItem) => [trailItem.id, trailItem])
24
+ );
25
+
26
+ export const trailsMcpApp = topo('trails', operatorTrails, {
27
+ wayfindAdaptersTrail,
28
+ wayfindContractTrail,
29
+ wayfindDescribeTrail,
30
+ wayfindDiffTrail,
31
+ wayfindErrorsTrail,
32
+ wayfindExamplesTrail,
33
+ wayfindImpactTrail,
34
+ wayfindNearbyTrail,
35
+ wayfindOutlineTrail,
36
+ wayfindOverlayTrail,
37
+ wayfindOverviewTrail,
38
+ wayfindResourcesTrail,
39
+ wayfindSearchTrail,
40
+ wayfindSurfacesTrail,
41
+ wayfindTrailsTrail,
42
+ });
@@ -0,0 +1,92 @@
1
+ import type {
2
+ CreateServerOptions,
3
+ McpSurfaceTrailheadMap,
4
+ } from '@ontrails/mcp';
5
+
6
+ import { trailsOverlays } from './app.js';
7
+
8
+ export const trailsMcpIncludedTrails = [
9
+ 'adapter.check',
10
+ 'add.surface',
11
+ 'add.trail',
12
+ 'compile',
13
+ 'create',
14
+ 'create.adapter',
15
+ 'deprecate',
16
+ 'dev.clean',
17
+ 'dev.reset',
18
+ 'dev.stats',
19
+ 'doctor',
20
+ 'draft.promote',
21
+ 'guide',
22
+ 'adjust.regrade',
23
+ 'apply.regrade',
24
+ 'audit.regrade',
25
+ 'check.regrade',
26
+ 'list.regrades',
27
+ 'plan.regrade',
28
+ 'preview.regrade',
29
+ 'release.check',
30
+ 'release.smoke',
31
+ 'revise',
32
+ 'run',
33
+ 'run.example',
34
+ 'run.examples',
35
+ 'survey',
36
+ 'survey.brief',
37
+ 'survey.diff',
38
+ 'survey.resource',
39
+ 'survey.signal',
40
+ 'survey.surfaces',
41
+ 'survey.trail',
42
+ 'topo',
43
+ 'topo.history',
44
+ 'topo.pin',
45
+ 'topo.unpin',
46
+ 'validate',
47
+ 'warden',
48
+ 'warden.guide',
49
+ 'wayfind.adapters',
50
+ 'wayfind.contract',
51
+ 'wayfind.diff',
52
+ 'wayfind.errors',
53
+ 'wayfind.examples',
54
+ 'wayfind.impact',
55
+ 'wayfind.nearby',
56
+ 'wayfind.overview',
57
+ 'wayfind.search',
58
+ 'wayfind.trails',
59
+ ] as const;
60
+
61
+ export const trailsMcpTrailheads = {
62
+ inspect: {
63
+ description:
64
+ 'Inspect saved topo structure, resources, signals, surfaces, and diffs.',
65
+ mcp: { loading: 'deferred' },
66
+ trails: [
67
+ 'survey',
68
+ 'topo',
69
+ 'guide',
70
+ 'survey.brief',
71
+ 'survey.diff',
72
+ 'survey.resource',
73
+ 'survey.signal',
74
+ 'survey.surfaces',
75
+ 'survey.trail',
76
+ 'topo.history',
77
+ ],
78
+ },
79
+ } satisfies McpSurfaceTrailheadMap;
80
+
81
+ export const trailsMcpSurfaceOptions = {
82
+ description:
83
+ 'Trails framework operator surface. Use MCP resources for cold context, direct tools for high-signal work, and the inspect trailhead for saved topo reads.',
84
+ include: trailsMcpIncludedTrails,
85
+ mcpResources: { examples: true, graph: true, surfaceMap: true },
86
+ name: 'trails',
87
+ // The overlay authors the lockable `inspect` default; the call-site map
88
+ // below is the runtime override-in-context with richer metadata
89
+ // (description, deferred loading) over the same member selectors.
90
+ overlays: trailsOverlays,
91
+ trailheads: trailsMcpTrailheads,
92
+ } satisfies CreateServerOptions;
package/src/mcp.ts ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bun
2
+ /* oxlint-disable eslint-plugin-jest/require-hook -- MCP stdio entrypoints execute at module scope */
3
+ import { surface } from '@ontrails/mcp';
4
+
5
+ import { trailsMcpApp } from './mcp-app.js';
6
+ import { trailsMcpSurfaceOptions } from './mcp-options.js';
7
+
8
+ await surface(trailsMcpApp, trailsMcpSurfaceOptions);
@@ -0,0 +1,377 @@
1
+ import { existsSync, mkdirSync, renameSync } from 'node:fs';
2
+ import { dirname, relative, resolve } from 'node:path';
3
+
4
+ import {
5
+ DRAFT_ID_PREFIX,
6
+ deriveSafePath,
7
+ InternalError,
8
+ Result,
9
+ ValidationError,
10
+ } from '@ontrails/core';
11
+ import type { Result as TrailsResult } from '@ontrails/core';
12
+
13
+ export const PROJECT_NAME_PATTERN = /^[a-z0-9][a-z0-9._-]*$/u;
14
+ export const PROJECT_NAME_MESSAGE =
15
+ 'Project name must start with a lowercase letter or digit and contain only lowercase letters, digits, ".", "_", or "-".';
16
+
17
+ export const TRAIL_ID_PATTERN =
18
+ /^(?:_draft\.)?[a-z][a-z0-9]*(?:\.[a-z][a-z0-9]*)*$/u;
19
+ export const TRAIL_ID_MESSAGE =
20
+ 'Trail ID must be lowercase dotted segments, optionally prefixed with "_draft.", with each non-draft segment starting with a letter and containing only letters or digits.';
21
+
22
+ const asError = (error: unknown): Error =>
23
+ error instanceof Error ? error : new Error(String(error));
24
+
25
+ export type PlannedProjectOperation =
26
+ | { readonly kind: 'mkdir'; readonly path: string }
27
+ | { readonly kind: 'rename'; readonly from: string; readonly to: string }
28
+ | { readonly kind: 'write'; readonly path: string };
29
+
30
+ export type ProjectWriteOperation =
31
+ | { readonly kind: 'mkdir'; readonly path: string }
32
+ | { readonly kind: 'rename'; readonly from: string; readonly to: string }
33
+ | {
34
+ readonly content: string | Uint8Array;
35
+ readonly kind: 'write';
36
+ readonly path: string;
37
+ };
38
+
39
+ interface ProjectOperationOptions {
40
+ readonly existing?: 'overwrite' | 'preserve';
41
+ }
42
+
43
+ export const validateProjectName = (
44
+ name: string
45
+ ): TrailsResult<string, ValidationError> =>
46
+ PROJECT_NAME_PATTERN.test(name)
47
+ ? Result.ok(name)
48
+ : Result.err(new ValidationError(PROJECT_NAME_MESSAGE));
49
+
50
+ export const validateTrailId = (
51
+ trailId: string
52
+ ): TrailsResult<string, ValidationError> =>
53
+ TRAIL_ID_PATTERN.test(trailId)
54
+ ? Result.ok(trailId)
55
+ : Result.err(new ValidationError(TRAIL_ID_MESSAGE));
56
+
57
+ export const trailIdToModuleName = (trailId: string): string =>
58
+ trailId.startsWith(DRAFT_ID_PREFIX)
59
+ ? `${DRAFT_ID_PREFIX}${trailId.slice(DRAFT_ID_PREFIX.length).replaceAll('.', '-')}`
60
+ : trailId.replaceAll('.', '-');
61
+
62
+ export const trailIdToExportName = (trailId: string): string =>
63
+ trailId.replaceAll('.', '_');
64
+
65
+ export const resolveProjectDir = (
66
+ parentDir: string,
67
+ projectName: string
68
+ ): TrailsResult<string, Error> => {
69
+ const validated = validateProjectName(projectName);
70
+ if (validated.isErr()) {
71
+ return validated;
72
+ }
73
+
74
+ return deriveSafePath(resolve(parentDir), validated.value);
75
+ };
76
+
77
+ export const resolveProjectPath = (
78
+ projectDir: string,
79
+ relativePath: string
80
+ ): TrailsResult<string, Error> => deriveSafePath(projectDir, relativePath);
81
+
82
+ export const projectPathExists = (
83
+ projectDir: string,
84
+ pathWithinProject: string
85
+ ): TrailsResult<boolean, Error> => {
86
+ const target = resolveProjectPath(projectDir, pathWithinProject);
87
+ if (target.isErr()) {
88
+ return target;
89
+ }
90
+
91
+ return Result.ok(existsSync(target.value));
92
+ };
93
+
94
+ /** Write a generated project-relative file and return the relative path. */
95
+ export const writeProjectFile = async (
96
+ projectDir: string,
97
+ relativePath: string,
98
+ content: string | Uint8Array
99
+ ): Promise<TrailsResult<string, Error>> => {
100
+ const target = resolveProjectPath(projectDir, relativePath);
101
+ if (target.isErr()) {
102
+ return target;
103
+ }
104
+
105
+ try {
106
+ mkdirSync(dirname(target.value), { recursive: true });
107
+ await Bun.write(target.value, content);
108
+ return Result.ok(relativePath);
109
+ } catch (error) {
110
+ return Result.err(
111
+ new InternalError(`Failed to write project file "${relativePath}"`, {
112
+ cause: asError(error),
113
+ context: { projectDir, relativePath },
114
+ })
115
+ );
116
+ }
117
+ };
118
+
119
+ /** Write an already-derived path that must stay contained under the project. */
120
+ export const writeContainedProjectPath = async (
121
+ projectDir: string,
122
+ pathWithinProject: string,
123
+ content: string | Uint8Array
124
+ ): Promise<TrailsResult<string, Error>> => {
125
+ const target = resolveProjectPath(projectDir, pathWithinProject);
126
+ if (target.isErr()) {
127
+ return target;
128
+ }
129
+
130
+ try {
131
+ mkdirSync(dirname(target.value), { recursive: true });
132
+ await Bun.write(target.value, content);
133
+ return Result.ok(target.value);
134
+ } catch (error) {
135
+ return Result.err(
136
+ new InternalError(
137
+ `Failed to write contained project path "${pathWithinProject}"`,
138
+ {
139
+ cause: asError(error),
140
+ context: { pathWithinProject, projectDir },
141
+ }
142
+ )
143
+ );
144
+ }
145
+ };
146
+
147
+ export const renameContainedProjectPath = (
148
+ projectDir: string,
149
+ fromPath: string,
150
+ toPath: string
151
+ ): TrailsResult<void, Error> => {
152
+ const from = resolveProjectPath(projectDir, fromPath);
153
+ if (from.isErr()) {
154
+ return from;
155
+ }
156
+
157
+ const to = resolveProjectPath(projectDir, toPath);
158
+ if (to.isErr()) {
159
+ return to;
160
+ }
161
+
162
+ try {
163
+ renameSync(from.value, to.value);
164
+ return Result.ok();
165
+ } catch (error) {
166
+ return Result.err(
167
+ new InternalError(
168
+ `Failed to rename contained project path "${fromPath}"`,
169
+ {
170
+ cause: asError(error),
171
+ context: { fromPath, projectDir, toPath },
172
+ }
173
+ )
174
+ );
175
+ }
176
+ };
177
+
178
+ const toProjectRelativePath = (
179
+ projectDir: string,
180
+ pathWithinProject: string
181
+ ): TrailsResult<string, Error> => {
182
+ const target = resolveProjectPath(projectDir, pathWithinProject);
183
+ if (target.isErr()) {
184
+ return target;
185
+ }
186
+
187
+ return Result.ok(
188
+ relative(resolve(projectDir), target.value).replaceAll('\\', '/')
189
+ );
190
+ };
191
+
192
+ export const planProjectOperation = (
193
+ projectDir: string,
194
+ operation: ProjectWriteOperation
195
+ ): TrailsResult<PlannedProjectOperation, Error> => {
196
+ switch (operation.kind) {
197
+ case 'mkdir': {
198
+ const path = toProjectRelativePath(projectDir, operation.path);
199
+ return path.isErr()
200
+ ? path
201
+ : Result.ok({ kind: 'mkdir', path: path.value });
202
+ }
203
+ case 'rename': {
204
+ const from = toProjectRelativePath(projectDir, operation.from);
205
+ if (from.isErr()) {
206
+ return from;
207
+ }
208
+ const to = toProjectRelativePath(projectDir, operation.to);
209
+ return to.isErr()
210
+ ? to
211
+ : Result.ok({ from: from.value, kind: 'rename', to: to.value });
212
+ }
213
+ case 'write': {
214
+ const path = toProjectRelativePath(projectDir, operation.path);
215
+ return path.isErr()
216
+ ? path
217
+ : Result.ok({ kind: 'write', path: path.value });
218
+ }
219
+ default: {
220
+ return Result.err(
221
+ new InternalError('Unknown project operation kind', {
222
+ context: { operation },
223
+ })
224
+ );
225
+ }
226
+ }
227
+ };
228
+
229
+ const shouldApplyProjectOperation = (
230
+ projectDir: string,
231
+ operation: ProjectWriteOperation,
232
+ options: ProjectOperationOptions
233
+ ): TrailsResult<boolean, Error> => {
234
+ if (options.existing !== 'preserve' || operation.kind === 'rename') {
235
+ return Result.ok(true);
236
+ }
237
+
238
+ const { path } = operation;
239
+ const target = resolveProjectPath(projectDir, path);
240
+ if (target.isErr()) {
241
+ return target;
242
+ }
243
+
244
+ return Result.ok(!existsSync(target.value));
245
+ };
246
+
247
+ const selectProjectOperations = (
248
+ projectDir: string,
249
+ operations: readonly ProjectWriteOperation[],
250
+ options: ProjectOperationOptions
251
+ ): TrailsResult<ProjectWriteOperation[], Error> => {
252
+ const selected: ProjectWriteOperation[] = [];
253
+ for (const operation of operations) {
254
+ const shouldApply = shouldApplyProjectOperation(
255
+ projectDir,
256
+ operation,
257
+ options
258
+ );
259
+ if (shouldApply.isErr()) {
260
+ return shouldApply;
261
+ }
262
+ if (shouldApply.value) {
263
+ selected.push(operation);
264
+ }
265
+ }
266
+
267
+ return Result.ok(selected);
268
+ };
269
+
270
+ export const planProjectOperations = (
271
+ projectDir: string,
272
+ operations: readonly ProjectWriteOperation[],
273
+ options: ProjectOperationOptions = {}
274
+ ): TrailsResult<PlannedProjectOperation[], Error> => {
275
+ const selected = selectProjectOperations(projectDir, operations, options);
276
+ if (selected.isErr()) {
277
+ return selected;
278
+ }
279
+
280
+ const planned: PlannedProjectOperation[] = [];
281
+ for (const operation of selected.value) {
282
+ const result = planProjectOperation(projectDir, operation);
283
+ if (result.isErr()) {
284
+ return result;
285
+ }
286
+ planned.push(result.value);
287
+ }
288
+ return Result.ok(planned);
289
+ };
290
+
291
+ const applyProjectOperation = async (
292
+ projectDir: string,
293
+ operation: ProjectWriteOperation
294
+ ): Promise<TrailsResult<void, Error>> => {
295
+ switch (operation.kind) {
296
+ case 'mkdir': {
297
+ const target = resolveProjectPath(projectDir, operation.path);
298
+ if (target.isErr()) {
299
+ return target;
300
+ }
301
+ try {
302
+ mkdirSync(target.value, { recursive: true });
303
+ return Result.ok();
304
+ } catch (error) {
305
+ return Result.err(
306
+ new InternalError(
307
+ `Failed to create project directory "${operation.path}"`,
308
+ {
309
+ cause: asError(error),
310
+ context: { projectDir, relativePath: operation.path },
311
+ }
312
+ )
313
+ );
314
+ }
315
+ }
316
+ case 'rename': {
317
+ return renameContainedProjectPath(
318
+ projectDir,
319
+ operation.from,
320
+ operation.to
321
+ );
322
+ }
323
+ case 'write': {
324
+ const target = resolveProjectPath(projectDir, operation.path);
325
+ if (target.isErr()) {
326
+ return target;
327
+ }
328
+ try {
329
+ mkdirSync(dirname(target.value), { recursive: true });
330
+ await Bun.write(target.value, operation.content);
331
+ return Result.ok();
332
+ } catch (error) {
333
+ return Result.err(
334
+ new InternalError(
335
+ `Failed to write project file "${operation.path}"`,
336
+ {
337
+ cause: asError(error),
338
+ context: { projectDir, relativePath: operation.path },
339
+ }
340
+ )
341
+ );
342
+ }
343
+ }
344
+ default: {
345
+ return Result.err(
346
+ new InternalError('Unknown project operation kind', {
347
+ context: { operation },
348
+ })
349
+ );
350
+ }
351
+ }
352
+ };
353
+
354
+ export const applyProjectOperations = async (
355
+ projectDir: string,
356
+ operations: readonly ProjectWriteOperation[],
357
+ options: ProjectOperationOptions = {}
358
+ ): Promise<TrailsResult<PlannedProjectOperation[], Error>> => {
359
+ const selected = selectProjectOperations(projectDir, operations, options);
360
+ if (selected.isErr()) {
361
+ return selected;
362
+ }
363
+
364
+ const planned = planProjectOperations(projectDir, selected.value);
365
+ if (planned.isErr()) {
366
+ return planned;
367
+ }
368
+
369
+ for (const operation of selected.value) {
370
+ const applied = await applyProjectOperation(projectDir, operation);
371
+ if (applied.isErr()) {
372
+ return applied;
373
+ }
374
+ }
375
+
376
+ return planned;
377
+ };