ttsc 0.34.3 → 0.36.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 (87) hide show
  1. package/driver/compilation_snapshot.go +267 -0
  2. package/driver/compilation_snapshot_keeps_inputs_across_stages_test.go +130 -0
  3. package/driver/compilation_snapshot_preserves_checked_emission_test.go +100 -0
  4. package/driver/graph.go +9 -3
  5. package/driver/program.go +45 -14
  6. package/lib/compiler/internal/CompilationSnapshot.d.ts +33 -0
  7. package/lib/compiler/internal/CompilationSnapshot.js +90 -0
  8. package/lib/compiler/internal/CompilationSnapshot.js.map +1 -0
  9. package/lib/compiler/internal/build/BuildExecution.d.ts +33 -4
  10. package/lib/compiler/internal/build/BuildExecution.js +81 -8
  11. package/lib/compiler/internal/build/BuildExecution.js.map +1 -1
  12. package/lib/compiler/internal/build/RunBuildOptions.d.ts +2 -0
  13. package/lib/compiler/internal/build/RuntimeBuildCache.d.ts +47 -0
  14. package/lib/compiler/internal/build/RuntimeBuildCache.js +235 -0
  15. package/lib/compiler/internal/build/RuntimeBuildCache.js.map +1 -0
  16. package/lib/compiler/internal/build/RuntimeBuildInputs.d.ts +44 -0
  17. package/lib/compiler/internal/build/RuntimeBuildInputs.js +282 -0
  18. package/lib/compiler/internal/build/RuntimeBuildInputs.js.map +1 -0
  19. package/lib/compiler/internal/build/RuntimeInputProof.d.ts +50 -0
  20. package/lib/compiler/internal/build/RuntimeInputProof.js +315 -0
  21. package/lib/compiler/internal/build/RuntimeInputProof.js.map +1 -0
  22. package/lib/compiler/internal/build/TsgoArguments.d.ts +5 -4
  23. package/lib/compiler/internal/build/TsgoArguments.js +11 -5
  24. package/lib/compiler/internal/build/TsgoArguments.js.map +1 -1
  25. package/lib/compiler/internal/build/appendBuildOutput.js +4 -0
  26. package/lib/compiler/internal/build/appendBuildOutput.js.map +1 -1
  27. package/lib/compiler/internal/build/runBuild.d.ts +3 -3
  28. package/lib/compiler/internal/build/runBuild.js +17 -4
  29. package/lib/compiler/internal/build/runBuild.js.map +1 -1
  30. package/lib/compiler/internal/build/runExternalEmitProvenance.d.ts +12 -13
  31. package/lib/compiler/internal/build/runExternalEmitProvenance.js +24 -18
  32. package/lib/compiler/internal/build/runExternalEmitProvenance.js.map +1 -1
  33. package/lib/compiler/internal/parseNativeTransformOutput.js +4 -0
  34. package/lib/compiler/internal/parseNativeTransformOutput.js.map +1 -1
  35. package/lib/compiler/internal/runNativeCheckWithObservations.d.ts +18 -14
  36. package/lib/compiler/internal/runNativeCheckWithObservations.js +42 -18
  37. package/lib/compiler/internal/runNativeCheckWithObservations.js.map +1 -1
  38. package/lib/compiler/internal/sharedHost/inheritedSidecarEnv.d.ts +2 -1
  39. package/lib/compiler/internal/sharedHost/inheritedSidecarEnv.js +4 -1
  40. package/lib/compiler/internal/sharedHost/inheritedSidecarEnv.js.map +1 -1
  41. package/lib/compiler/internal/transformProjectInMemory.d.ts +3 -3
  42. package/lib/compiler/internal/transformProjectInMemory.js +29 -5
  43. package/lib/compiler/internal/transformProjectInMemory.js.map +1 -1
  44. package/lib/flags/FLAG_SCHEMA.js +7 -0
  45. package/lib/flags/FLAG_SCHEMA.js.map +1 -1
  46. package/lib/launcher/internal/parseTtsxCLI.d.ts +1 -0
  47. package/lib/launcher/internal/parseTtsxCLI.js +1 -0
  48. package/lib/launcher/internal/parseTtsxCLI.js.map +1 -1
  49. package/lib/launcher/internal/prepareExecution.d.ts +2 -0
  50. package/lib/launcher/internal/prepareExecution.js +6 -0
  51. package/lib/launcher/internal/prepareExecution.js.map +1 -1
  52. package/lib/launcher/internal/runTtsx.js +5 -0
  53. package/lib/launcher/internal/runTtsx.js.map +1 -1
  54. package/lib/launcher/internal/runtime/installRuntimeHooks.js +7 -0
  55. package/lib/launcher/internal/runtime/installRuntimeHooks.js.map +1 -1
  56. package/lib/plugin/internal/load/loadProjectPlugins.js +1 -0
  57. package/lib/plugin/internal/load/loadProjectPlugins.js.map +1 -1
  58. package/lib/plugin/internal/source/SourceBuildCacheLayout.d.ts +2 -0
  59. package/lib/plugin/internal/source/SourceBuildCacheLayout.js +3 -0
  60. package/lib/plugin/internal/source/SourceBuildCacheLayout.js.map +1 -1
  61. package/lib/structures/ITtscCompilerTransformation.d.ts +5 -0
  62. package/lib/structures/ITtscPluginCapabilities.d.ts +13 -2
  63. package/package.json +8 -8
  64. package/src/compiler/internal/CompilationSnapshot.ts +97 -0
  65. package/src/compiler/internal/build/BuildExecution.ts +128 -20
  66. package/src/compiler/internal/build/RunBuildOptions.ts +3 -0
  67. package/src/compiler/internal/build/RuntimeBuildCache.ts +252 -0
  68. package/src/compiler/internal/build/RuntimeBuildInputs.ts +349 -0
  69. package/src/compiler/internal/build/RuntimeInputProof.ts +346 -0
  70. package/src/compiler/internal/build/TsgoArguments.ts +11 -5
  71. package/src/compiler/internal/build/appendBuildOutput.ts +4 -0
  72. package/src/compiler/internal/build/runBuild.ts +20 -5
  73. package/src/compiler/internal/build/runExternalEmitProvenance.ts +25 -23
  74. package/src/compiler/internal/parseNativeTransformOutput.ts +5 -0
  75. package/src/compiler/internal/runNativeCheckWithObservations.ts +41 -18
  76. package/src/compiler/internal/sharedHost/inheritedSidecarEnv.ts +8 -1
  77. package/src/compiler/internal/transformProjectInMemory.ts +46 -5
  78. package/src/flags/FLAG_SCHEMA.ts +7 -0
  79. package/src/launcher/internal/parseTtsxCLI.ts +1 -0
  80. package/src/launcher/internal/prepareExecution.ts +13 -0
  81. package/src/launcher/internal/runTtsx.ts +5 -0
  82. package/src/launcher/internal/runtime/installRuntimeHooks.ts +11 -0
  83. package/src/plugin/internal/load/loadProjectPlugins.ts +1 -0
  84. package/src/plugin/internal/source/SourceBuildCacheLayout.ts +4 -0
  85. package/src/structures/ITtscCompilerTransformation.ts +6 -0
  86. package/src/structures/ITtscPluginCapabilities.ts +14 -2
  87. package/utility/host.go +22 -1
@@ -0,0 +1,346 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+
5
+ import type { ITtscCompilerTransformation } from "../../../structures/ITtscCompilerTransformation";
6
+ import type { TtscBuildResult } from "../../../structures/internal/TtscBuildResult";
7
+
8
+ /**
9
+ * Replay the compiler and native input witnesses of a completed runtime build.
10
+ * Read predicates keep their original text or raw-byte codec; absence, entry
11
+ * kind, physical target and directory membership remain independent predicates.
12
+ * Failed or unsupported observations withhold reuse.
13
+ *
14
+ * @evidence contracts/common.md#principled-implementation Replay compares generation witnesses with current existence, stat, decoded text, physical identity and directory membership. Native version-one file, optional-file, entry and directory codecs use explicit tags, raw file/link bytes and sorted nul-delimited records. Compiler text strips UTF-8 BOM or decodes even UTF-16LE/BE bytes before SHA-256; host directory presence uses its separate domain marker.
15
+ * @evidence contracts/common.md#clear-and-simple-design One namespace separates result admission, declared host inputs, compiler predicates and the native version-one codec. Private physical/absence and SHA-256 helpers serve the codecs without merging their meanings.
16
+ * @evidence contracts/common.md#prohibited-implementation-shortcuts Unknown codecs, failed reads and producer proof failures decline admission. Only ENOENT/ENOTDIR prove absence; other physical-resolution errors remain unavailable. Following stat classifies compiler views while lstat retains native link kinds; only the producer private output subtree is excluded.
17
+ * @evidence contracts/common.md#meaningful-documentation Native prose identifies generation proof, codec ownership and refusal semantics; private helper comments identify query, byte, decoded-text and null/error boundaries.
18
+ * @evidence contracts/portability.md#os-neutral-implementation Native stat, lstat and realpath retain actual kinds, targets and spellings without case assumptions. POSIX directory names/link targets stay raw bytes, Windows names follow the producer UTF-8 codec, and compiler directory entries sort by UTF-8 bytes.
19
+ * @evidence contracts/performance.md#efficient-algorithms Replay visits recorded predicates and their bytes or immediate directory entries rather than unrelated trees. Hashing and BOM decoding cost O(bytes), including a big-endian copy; directory codecs cost O(N log N) sorting plus encoded bytes and link queries. Physical resolution follows native path/link traversal.
20
+ * @evidence contracts/performance.md#reuse-equivalent-work Every retained predicate is observed anew to authorize completed-result reuse. Host capture and admission share the producer codec; no path memo, watcher silence or historical hash independently grants authority.
21
+ * @evidence contracts/performance.md#bound-retention-and-release-resources Read buffers, decoded text, paths and sorted directory members are call-local and have no proof-reader byte or entry cap. Synchronous calls retain no handle, watcher, process or historical population; only returned proof values escape.
22
+ */
23
+ export namespace RuntimeInputProof {
24
+ /**
25
+ * Validate result-level host witnesses and every reported compiler predicate.
26
+ * The caller independently proves the selected compiler, project membership
27
+ * and plugin selection; an absent graph alone grants no completeness.
28
+ *
29
+ * @evidence contracts/common.md#principled-implementation Explicit incomplete observations and any graph failure reject reuse; host paths require both content and physical witnesses, and rich compiler predicates are replayed under their own codec.
30
+ * @evidence contracts/common.md#clear-and-simple-design One admission pass delegates individual compiler observations and native codecs.
31
+ * @evidence contracts/common.md#prohibited-implementation-shortcuts Missing witness fields never become an empty successful observation, and only the caller-owned private output subtree is excluded.
32
+ * @evidence contracts/common.md#meaningful-documentation Native prose identifies result admission and the caller's separate completeness obligations.
33
+ * @evidence contracts/portability.md#os-neutral-implementation Native path resolution anchors producer-relative graph keys, and current physical paths come from native realpath.
34
+ * @evidence contracts/performance.md#efficient-algorithms Input and predicate populations drive replay; each read hashes its actual bytes and directories sort immediate entry records.
35
+ * @evidence contracts/performance.md#reuse-equivalent-work Generation witnesses, rather than an identity-key match, decide whether a completed build remains reusable.
36
+ * @evidence contracts/performance.md#bound-retention-and-release-resources Temporary path and predicate records are invocation-owned without retained handles or history.
37
+ */
38
+ export function holds(
39
+ result: TtscBuildResult,
40
+ projectRoot: string,
41
+ emitDir: string,
42
+ ): boolean {
43
+ if (
44
+ result.observationsComplete === false ||
45
+ Object.keys(result.graph?.inputProofFailures ?? {}).length !== 0
46
+ )
47
+ return false;
48
+ try {
49
+ for (const file of result.hostInputs ?? []) {
50
+ const [currentPhysical, hash] = observeHostInput(file);
51
+ if (
52
+ !Object.hasOwn(result.hostInputHashes ?? {}, file) ||
53
+ !Object.hasOwn(result.hostInputRealpaths ?? {}, file) ||
54
+ currentPhysical !== result.hostInputRealpaths![file] ||
55
+ hash !== result.hostInputHashes![file]
56
+ )
57
+ return false;
58
+ }
59
+ const graph = result.graph;
60
+ for (const [name, observed] of Object.entries(
61
+ graph?.inputObservations ?? {},
62
+ )) {
63
+ const file = path.resolve(projectRoot, name);
64
+ const relative = path.relative(emitDir, file);
65
+ if (
66
+ relative === "" ||
67
+ (!path.isAbsolute(relative) &&
68
+ relative !== ".." &&
69
+ !relative.startsWith(".." + path.sep))
70
+ )
71
+ continue;
72
+ if (!observationHolds(file, observed)) return false;
73
+ }
74
+ for (const [name, expected] of Object.entries(graph?.inputHashes ?? {})) {
75
+ if (Object.hasOwn(graph?.inputObservations ?? {}, name)) continue;
76
+ const file = path.resolve(projectRoot, name);
77
+ if (physical(file) !== graph?.inputRealpaths?.[name]) return false;
78
+ let current: string | null = null;
79
+ try {
80
+ if (fs.statSync(file).isFile())
81
+ current = textHash(fs.readFileSync(file));
82
+ } catch (error) {
83
+ if (!missing(error)) return false;
84
+ }
85
+ if (current !== expected) return false;
86
+ }
87
+ return true;
88
+ } catch {
89
+ return false;
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Observe a declared host input under its existing raw-file or directory-kind
95
+ * codec. Descriptor resolution can declare directories as presence inputs;
96
+ * those are distinct from compiler source reads and directory enumeration.
97
+ * Native identity and metadata bracket the observation. Missing paths carry
98
+ * null witnesses, while unavailable or changing observations throw.
99
+ *
100
+ * @evidence contracts/common.md#principled-implementation Raw file bytes and the existing ttsc:host-input:directory domain marker reproduce the descriptor/native host-input contract, with physical identity and full native metadata checked before and after.
101
+ * @evidence contracts/common.md#clear-and-simple-design One observer supplies the same declared-host codec to input capture and retained-result admission, independently of compiler text and enumeration predicates.
102
+ * @evidence contracts/common.md#prohibited-implementation-shortcuts Only ENOENT/ENOTDIR establish absence; unsupported entry kinds, read failures and changing witnesses refuse reuse instead of becoming empty content.
103
+ * @evidence contracts/common.md#meaningful-documentation Native prose distinguishes directory presence from directory membership, states the producer codec and explains failure semantics.
104
+ * @evidence contracts/portability.md#os-neutral-implementation Native following stat, realpath and byte reads retain actual host links and physical spellings without OS-name or separator guesses.
105
+ * @evidence contracts/performance.md#efficient-algorithms File observations hash their complete byte buffer and bracket native metadata; directory presence hashes a fixed marker without scanning members.
106
+ * @evidence contracts/performance.md#reuse-equivalent-work Capture and admission share the producer's codec, but every invocation observes current witnesses and retains no path-only truth.
107
+ * @evidence contracts/performance.md#bound-retention-and-release-resources Read buffers and stat records are call-local; synchronous filesystem calls leave no retained handle or watcher.
108
+ */
109
+ export function observeHostInput(
110
+ file: string,
111
+ ): readonly [string | null, string | null] {
112
+ const beforePhysical = physical(file);
113
+ let before: fs.BigIntStats;
114
+ try {
115
+ before = fs.statSync(file, { bigint: true });
116
+ } catch (error) {
117
+ if (!missing(error)) throw error;
118
+ if (beforePhysical !== null || physical(file) !== null)
119
+ throw new Error("Host input changed during absence observation.");
120
+ return [null, null];
121
+ }
122
+ if (!before.isFile() && !before.isDirectory())
123
+ throw new Error("Unsupported runtime host input kind.");
124
+ const hash = before.isDirectory()
125
+ ? digest("ttsc:host-input:directory\0")
126
+ : digest(fs.readFileSync(file));
127
+ const after = fs.statSync(file, { bigint: true });
128
+ const signature = (stat: fs.BigIntStats): string =>
129
+ [stat.dev, stat.ino, stat.size, stat.mtimeNs, stat.ctimeNs].join(":");
130
+ if (
131
+ signature(before) !== signature(after) ||
132
+ beforePhysical !== physical(file)
133
+ )
134
+ throw new Error("Host input changed during observation.");
135
+ return [beforePhysical, hash];
136
+ }
137
+
138
+ /** Compare one compiler query record with the corresponding current queries. */
139
+ function observationHolds(
140
+ file: string,
141
+ observed: ITtscCompilerTransformation.IInputObservation,
142
+ ): boolean {
143
+ for (const predicate of observed.nativePredicates ?? [])
144
+ if (
145
+ predicate.version !== 1 ||
146
+ !predicate.identityStable ||
147
+ physical(file) !== predicate.realpath ||
148
+ nativeDigest(file, predicate.kind) !== predicate.digest
149
+ )
150
+ return false;
151
+ let kind: "file" | "directory" | "missing" = "missing";
152
+ try {
153
+ const stat = fs.statSync(file);
154
+ kind = stat.isDirectory() ? "directory" : "file";
155
+ } catch (error) {
156
+ if (!missing(error)) return false;
157
+ }
158
+ if (
159
+ observed.fileExists !== undefined &&
160
+ observed.fileExists !== (kind === "file")
161
+ )
162
+ return false;
163
+ if (
164
+ observed.directoryExists !== undefined &&
165
+ observed.directoryExists !== (kind === "directory")
166
+ )
167
+ return false;
168
+ if (observed.stat !== undefined && observed.stat !== kind) return false;
169
+ if (observed.readFile !== undefined) {
170
+ let hash: string | null = null;
171
+ try {
172
+ if (kind !== "directory") hash = textHash(fs.readFileSync(file));
173
+ } catch {
174
+ /* Compiler read failed. */
175
+ }
176
+ if (
177
+ observed.readFile.ok ? hash !== observed.readFile.hash : hash !== null
178
+ )
179
+ return false;
180
+ }
181
+ if (observed.realpath !== undefined) {
182
+ const current = physical(file);
183
+ if (
184
+ observed.realpath.ok
185
+ ? current !== observed.realpath.path
186
+ : current !== null
187
+ )
188
+ return false;
189
+ }
190
+ if (observed.accessibleEntries !== undefined) {
191
+ const directories: string[] = [];
192
+ const files: string[] = [];
193
+ let entries: fs.Dirent[] = [];
194
+ try {
195
+ entries = fs.readdirSync(file, { withFileTypes: true });
196
+ } catch {
197
+ /* Compiler enumeration returns an empty view. */
198
+ }
199
+ for (const entry of entries) {
200
+ try {
201
+ const stat = entry.isSymbolicLink()
202
+ ? fs.statSync(path.join(file, entry.name))
203
+ : entry;
204
+ if (stat.isDirectory()) directories.push(entry.name);
205
+ else if (stat.isFile()) files.push(entry.name);
206
+ } catch {
207
+ /* Compiler enumeration omits inaccessible link targets. */
208
+ }
209
+ }
210
+ const compare = (a: string, b: string): number =>
211
+ Buffer.compare(Buffer.from(a), Buffer.from(b));
212
+ if (
213
+ JSON.stringify({
214
+ directories: directories.sort(compare),
215
+ files: files.sort(compare),
216
+ }) !== JSON.stringify(observed.accessibleEntries)
217
+ )
218
+ return false;
219
+ }
220
+ return true;
221
+ }
222
+
223
+ /**
224
+ * Reproduce native version-one file, optional-file, entry and directory
225
+ * bytes.
226
+ */
227
+ function nativeDigest(file: string, kind: string): string {
228
+ if (kind === "file") return digest(fs.readFileSync(file));
229
+ if (kind === "optional-file") {
230
+ try {
231
+ return fs.statSync(file).isFile()
232
+ ? digest(
233
+ Buffer.concat([Buffer.from("file\0"), fs.readFileSync(file)]),
234
+ )
235
+ : digest("missing\0");
236
+ } catch (error) {
237
+ if (missing(error)) return digest("missing\0");
238
+ throw error;
239
+ }
240
+ }
241
+ if (kind === "entry") {
242
+ try {
243
+ const entry = fs.lstatSync(file);
244
+ return entry.isSymbolicLink()
245
+ ? digest(
246
+ Buffer.concat([
247
+ Buffer.from("symlink\0"),
248
+ fs.readlinkSync(file, { encoding: "buffer" }),
249
+ ]),
250
+ )
251
+ : digest(
252
+ (entry.isDirectory()
253
+ ? "directory"
254
+ : entry.isFile()
255
+ ? "file"
256
+ : "other") + "\0",
257
+ );
258
+ } catch (error) {
259
+ if (missing(error)) return digest("missing\0");
260
+ throw error;
261
+ }
262
+ }
263
+ if (kind !== "directory") throw new Error("unsupported native input codec");
264
+ const records: Buffer[] = [];
265
+ const names =
266
+ process.platform === "win32"
267
+ ? fs.readdirSync(file).map((name) => Buffer.from(name))
268
+ : fs.readdirSync(file, { encoding: "buffer" });
269
+ for (const name of names) {
270
+ const target =
271
+ process.platform === "win32"
272
+ ? path.join(file, name.toString())
273
+ : Buffer.concat([Buffer.from(file + path.sep), name]);
274
+ const entry = fs.lstatSync(target);
275
+ const entryKind = entry.isDirectory()
276
+ ? "directory"
277
+ : entry.isFile()
278
+ ? "file"
279
+ : entry.isSymbolicLink()
280
+ ? "symlink"
281
+ : "other";
282
+ const link = entry.isSymbolicLink()
283
+ ? fs.readlinkSync(target, { encoding: "buffer" })
284
+ : Buffer.alloc(0);
285
+ records.push(
286
+ Buffer.concat([name, Buffer.from("\0" + entryKind + "\0"), link]),
287
+ );
288
+ }
289
+ records.sort(Buffer.compare);
290
+ return digest(
291
+ Buffer.concat(
292
+ records.flatMap((record, index) =>
293
+ index === 0 ? [record] : [Buffer.from([0]), record],
294
+ ),
295
+ ),
296
+ );
297
+ }
298
+
299
+ /** Hash compiler-decoded text, retaining the BOM and UTF-16 producer policy. */
300
+ function textHash(bytes: Buffer): string {
301
+ if (
302
+ bytes.length >= 2 &&
303
+ ((bytes[0] === 0xff && bytes[1] === 0xfe) ||
304
+ (bytes[0] === 0xfe && bytes[1] === 0xff))
305
+ ) {
306
+ const text = Buffer.from(
307
+ bytes.subarray(2, 2 + Math.floor((bytes.length - 2) / 2) * 2),
308
+ );
309
+ if (bytes[0] === 0xfe) text.swap16();
310
+ return digest(Buffer.from(text.toString("utf16le"), "utf8"));
311
+ }
312
+ return digest(
313
+ bytes.length >= 3 &&
314
+ bytes[0] === 0xef &&
315
+ bytes[1] === 0xbb &&
316
+ bytes[2] === 0xbf
317
+ ? bytes.subarray(3)
318
+ : bytes,
319
+ );
320
+ }
321
+
322
+ /** Obtain a current physical coordinate, with null only for native absence. */
323
+ function physical(file: string): string | null {
324
+ try {
325
+ return fs.realpathSync.native(file);
326
+ } catch (error) {
327
+ if (missing(error)) return null;
328
+ throw error;
329
+ }
330
+ }
331
+
332
+ /** Classify only native absent-path errors. */
333
+ function missing(error: unknown): boolean {
334
+ return (
335
+ typeof error === "object" &&
336
+ error !== null &&
337
+ "code" in error &&
338
+ (error.code === "ENOENT" || error.code === "ENOTDIR")
339
+ );
340
+ }
341
+
342
+ /** SHA-256 of supplied text or raw bytes. */
343
+ function digest(bytes: string | Buffer): string {
344
+ return crypto.createHash("sha256").update(bytes).digest("hex");
345
+ }
346
+ }
@@ -195,11 +195,12 @@ export namespace TsgoArguments {
195
195
  /**
196
196
  * The forwarded-tsgo payload for a native `build`/`check` emit invocation.
197
197
  *
198
- * The sidecar builds its Program in-process, so the pinned `rootDir` has to
199
- * travel the same channel every other tsgo option takes to it — the host flag
200
- * set does not declare `--rootDir`, and `filterHostArgs` would strip it.
198
+ * The sidecar builds its Program in-process, so runtime source-map defaults
199
+ * and the pinned `rootDir` travel the same channel as other tsgo options —
200
+ * the host flag set does not declare `--rootDir`, and `filterHostArgs` would
201
+ * strip it.
201
202
  *
202
- * @evidence contracts/common.md#principled-implementation The same private layout root used by direct builds is placed in the sidecar compiler-option channel, preserving declared/composite containment while avoiding a new ordinary config-directory restriction without a new host flag.
203
+ * @evidence contracts/common.md#principled-implementation The same private layout root and forced runtime source-map default used by direct builds precede user arguments in the sidecar compiler-option channel, preserving explicit overrides and declared/composite containment without a new host flag.
203
204
  * @evidence contracts/common.md#clear-and-simple-design Root pinning stays in one helper and general payload ordering/serialization stays in createNativeTsgoArgs.
204
205
  * @evidence contracts/common.md#prohibited-implementation-shortcuts The supported environment payload carries compiler options instead of injecting unknown flags into strict foreign host parsers.
205
206
  * @evidence contracts/common.md#meaningful-documentation Native prose explains why rootDir travels with compiler options rather than through the host flag set.
@@ -215,7 +216,12 @@ export namespace TsgoArguments {
215
216
  ): string | undefined {
216
217
  return createNativeTsgoArgs(
217
218
  options,
218
- pinnedRootDirArgs(execution, options),
219
+ [
220
+ ...(options.forceRuntimeSourceMap === true
221
+ ? ["--sourceMap", "true"]
222
+ : []),
223
+ ...pinnedRootDirArgs(execution, options),
224
+ ],
219
225
  false,
220
226
  );
221
227
  }
@@ -186,6 +186,10 @@ export function mergeCheckGraphs(
186
186
  observations[key] = merged;
187
187
  }
188
188
  return {
189
+ ...(left.compilationSnapshot !== undefined &&
190
+ left.compilationSnapshot === right.compilationSnapshot
191
+ ? { compilationSnapshot: left.compilationSnapshot }
192
+ : {}),
189
193
  edges: mergeLists(left.edges, right.edges),
190
194
  ...(membershipConflict ||
191
195
  (left.membership ?? right.membership) === undefined
@@ -2,6 +2,8 @@ import type { TtscBuildResult } from "../../../structures/internal/TtscBuildResu
2
2
  import { BuildExecution } from "./BuildExecution";
3
3
  import { BuildTiming } from "./BuildTiming";
4
4
  import type { RunBuildOptions } from "./RunBuildOptions";
5
+ import { RuntimeBuildCache } from "./RuntimeBuildCache";
6
+ import { RuntimeBuildInputs } from "./RuntimeBuildInputs";
5
7
  import { WatchInputPublication } from "./WatchInputPublication";
6
8
 
7
9
  /**
@@ -21,7 +23,7 @@ import { WatchInputPublication } from "./WatchInputPublication";
21
23
  * @evidence contracts/common.md#meaningful-documentation Native prose distinguishes returned exit failures from thrown setup/launch errors and explains the project-free branch.
22
24
  * @evidence contracts/portability.md#os-neutral-implementation Execution selection and spawning use the shared native path/process boundaries with cwd and separate argv, rather than constructing a shell command here.
23
25
  * @evidence contracts/performance.md#efficient-algorithms Timing creation and terminal selection make their own flag projections before the selected preparation/execution path. Delegated configuration, plugin, native/provenance and diagnostic work follows its actual input/report sizes; timing formatting scans ledger labels and output. No measured dominance or duration/output ceiling is established by this wrapper.
24
- * @evidence contracts/performance.md#reuse-equivalent-work A resolved execution context is carried through preparation and execution, so this build does not reload its plugin selection between phases.
26
+ * @evidence contracts/performance.md#reuse-equivalent-work A resolved execution context is carried through preparation and execution without another plugin load; private runtime requests delegate verified completed-emission reuse to RuntimeBuildCache with current input and producer proofs.
25
27
  * @evidence contracts/performance.md#bound-retention-and-release-resources The ledger and execution state are build-owned, while returned output/proof/diagnostic records transfer to the caller; no resident handle or historical build is stored here. Delegated native/probe/artifact acquisition and cleanup may be best effort, and thrown setup can precede some cleanup boundaries. This wrapper supplies no duration/output bound or descendant-release certification.
26
28
  */
27
29
  export function runBuild(options: RunBuildOptions = {}): TtscBuildResult {
@@ -36,8 +38,8 @@ export function runBuild(options: RunBuildOptions = {}): TtscBuildResult {
36
38
  * @evidence contracts/common.md#prohibited-implementation-shortcuts Awaiting changes only publication completion, preserves compiler/plugin selection and project-free terminal behavior, and sends publication failure through existing setup and cleanup rather than bypassing a pending baseline.
37
39
  * @evidence contracts/common.md#meaningful-documentation Entry prose states the publication barrier, order before compilation and internal callers' obligation to complete the sequence and deliver rejection.
38
40
  * @evidence contracts/portability.md#os-neutral-implementation BuildExecution retains native cwd, path identity and argument-array ownership across suspension; the namespace adds no independent native boundary.
39
- * @evidence contracts/performance.md#efficient-algorithms Each selected terminal, context, discovery, preparation and compile phase runs once; each publication adds one await and constant sequence state.
40
- * @evidence contracts/performance.md#reuse-equivalent-work One resolved execution context serves preparation and compilation without reloading plugins; the namespace retains no completed build or in-flight cache.
41
+ * @evidence contracts/performance.md#efficient-algorithms Each selected terminal, context, discovery and preparation phase runs once; eligible runtime requests add native source/configuration queries and content proofs before restoring or compiling. Each publication adds one await and constant sequence state.
42
+ * @evidence contracts/performance.md#reuse-equivalent-work One resolved execution context serves preparation and compilation without reloading plugins; the delegated runtime store reuses completed bytes only under current equal input snapshots and valid producer witnesses, with ordinary compilation on any miss.
41
43
  * @evidence contracts/performance.md#bound-retention-and-release-resources The invocation owns its sequence, ledger, context and current handoff while callbacks settle. Selected results transfer to the caller, delegated resource ownership and cleanup stay unchanged, and no resident history is retained.
42
44
  */
43
45
  export namespace runBuild {
@@ -72,14 +74,27 @@ export namespace runBuild {
72
74
  execution,
73
75
  setupStartedAt,
74
76
  );
75
- const result =
76
- prepared.result ??
77
+ const build = () =>
77
78
  BuildExecution.runPreparedBuild(
78
79
  options,
79
80
  timing,
80
81
  execution,
81
82
  prepared.buildOptions,
82
83
  );
84
+ const proof =
85
+ prepared.result === undefined
86
+ ? RuntimeBuildInputs.create(prepared.buildOptions, execution)
87
+ : undefined;
88
+ const result =
89
+ prepared.result ??
90
+ (proof === undefined
91
+ ? build()
92
+ : RuntimeBuildCache.run({
93
+ directory: options.runtimeCacheDir,
94
+ emitDir: options.isolateOutputsTo!,
95
+ ...proof,
96
+ build,
97
+ }));
83
98
  return BuildTiming.appendTimingOutput(result, timing);
84
99
  }
85
100
  }
@@ -17,17 +17,16 @@ import { PassthroughFlags } from "./PassthroughFlags";
17
17
  * diagnostics and user-requested file-list display remain owned by that run.
18
18
  *
19
19
  * Admission requires stable effective options, identical source selection and
20
- * stable physical paths, file identities and bytes before and after emission,
21
- * including response files and the selected executable itself. Response
22
- * inspection preserves native argument-frame boundaries and operand positions;
23
- * the producer and its probes receive the original argv. The executable's
24
- * change time is excluded from cross-command equality because that metadata
25
- * changed in real executions without changing the executable object or bytes;
26
- * source change times remain proof premises and each read brackets its full
27
- * metadata. This is an external observation, not an atomic compiler-generation
28
- * ledger; a concurrent change restored between observations can remain
29
- * invisible. Unsupported layouts and ambiguous outputs carry an empty ownership
30
- * list.
20
+ * stable physical source paths before and after emission, plus unchanged
21
+ * response files and selected executable bytes. Response inspection preserves
22
+ * native argument-frame boundaries and operand positions; the producer and its
23
+ * probes receive the original argv. The executable's change time is excluded
24
+ * from cross-command equality because that metadata changed in real executions
25
+ * without changing the executable object or bytes; source contents belong to
26
+ * the compiler's own Program. Each executable read brackets its full metadata.
27
+ * This is an external observation, not an atomic compiler-generation ledger; a
28
+ * concurrent change restored between observations can remain invisible.
29
+ * Unsupported layouts and ambiguous outputs carry an empty ownership list.
31
30
  *
32
31
  * A nonzero compiler status can still carry proved writes for an unchecked
33
32
  * consumer. Ownership metadata never changes that status or its diagnostics.
@@ -47,12 +46,12 @@ import { PassthroughFlags } from "./PassthroughFlags";
47
46
  * in emittedSourceProofFailures. These explanations preserve compiler streams
48
47
  * and status; they do not replace missing ownership with a successful claim.
49
48
  *
50
- * @evidence contracts/common.md#principled-implementation Actual TSFILE writes are matched against the supported upstream per-source extension and explicit-root layout under matching compiler-selected inputs and stable physical/content observations. No emitted filename alone establishes ownership; observation gaps remain documented.
49
+ * @evidence contracts/common.md#principled-implementation Actual TSFILE writes are matched against the supported upstream per-source extension and explicit-root layout under matching compiler-selected inputs and stable physical source identities and response/executable content observations. No emitted filename alone establishes ownership; observation gaps remain documented.
51
50
  * @evidence contracts/common.md#clear-and-simple-design One adapter owns read-only compiler probes, the single delegated emission and admission; private helpers isolate option parsing, physical observation and path prediction.
52
51
  * @evidence contracts/common.md#prohibited-implementation-shortcuts The selected executable and original arguments remain authoritative. Unknown layouts are reported unknown instead of switching compilers, guessing same-stem ownership or consulting source maps.
53
52
  * @evidence contracts/common.md#meaningful-documentation Native paragraphs explain producer preservation, unknown states and the non-atomic observation limitation; the investigation record documents the supported upstream naming subset.
54
53
  * @evidence contracts/portability.md#os-neutral-implementation Native node:path and filesystem realpath/stat separate writer spelling from physical source identity. Executables receive separate argv entries through spawnNative, without a shell or OS-based case folding.
55
- * @evidence contracts/performance.md#efficient-algorithms Source and output indexes avoid cross-product matching. Response inspection uses an iterative frame stack and active physical-path set. Repeated response/source/executable observations read and hash complete files; showConfig text, source/output lists, signature JSON, candidate path components and byte buffers are processed at their actual sizes alongside native probes/path operations. No native duration or report-size ceiling follows from using one index.
54
+ * @evidence contracts/performance.md#efficient-algorithms Source and output indexes avoid cross-product matching. Response inspection uses an iterative frame stack and active physical-path set. Response/executable observations read and hash complete files; source identity checks resolve paths without comparing mutable text; showConfig text, source/output lists, signature JSON, candidate path components and byte buffers are processed at their actual sizes alongside native probes/path operations. No native duration or report-size ceiling follows from using one index.
56
55
  * @evidence contracts/performance.md#reuse-equivalent-work Each source observation and predicted output index is shared by all outputs in this invocation. Cross-build reuse is unavailable because arbitrary external producer and filesystem dependencies have no invalidation contract.
57
56
  * @evidence contracts/performance.md#bound-retention-and-release-resources Response/config/source tokens and predicted owner sets live for this invocation; returned provenance/refusal records transfer to the caller. Retained bytes grow with complete reports, expanded arguments, paths and observations, while individual file reads allocate full file buffers. Probe capture cleanup is delegated and may be best effort; no timeout, output ceiling or descendant-release certification is provided here.
58
57
  */
@@ -144,7 +143,7 @@ export function runExternalEmitProvenance(options: {
144
143
  }
145
144
 
146
145
  // An observed host lists nothing; it compiles the same selected tsconfig, and
147
- // the source observations below still prove that selection held still.
146
+ // the source identity observations below still prove that selection retained its physical owners.
148
147
  const listed = observed
149
148
  ? probe.files
150
149
  : compilerSourceList(lines, options.cwd);
@@ -185,10 +184,10 @@ export function runExternalEmitProvenance(options: {
185
184
  for (const [source, before] of probe.observations) {
186
185
  if (!stable) break;
187
186
  stage = `source observation of ${JSON.stringify(source)}`;
188
- const after = CompilerArgumentsInspection.observeInputFile(source);
187
+ const after = observeSourceIdentity(source);
189
188
  stable = after === before;
190
189
  if (!stable)
191
- failure = `Selected source changed across emission: ${JSON.stringify(source)} (${observationDifference(before, after)}).`;
190
+ failure = `Selected source identity changed across emission: ${JSON.stringify(source)}.`;
192
191
  }
193
192
  for (const [file, before] of probe.responseObservations) {
194
193
  if (!stable) break;
@@ -207,9 +206,7 @@ export function runExternalEmitProvenance(options: {
207
206
  if (outputs.length === 0) continue;
208
207
  predictedSources++;
209
208
  sourceExample ??= source;
210
- const physicalSource: string = JSON.parse(
211
- probe.observations.get(source)!,
212
- )[0];
209
+ const physicalSource = probe.observations.get(source)!;
213
210
  for (const output of outputs) {
214
211
  const sources = owners.get(output) ?? new Set<string>();
215
212
  sources.add(physicalSource);
@@ -368,10 +365,7 @@ function prepareProbe(
368
365
  const observations = new Map<string, string>();
369
366
  for (const source of files) {
370
367
  stage = `initial source observation of ${JSON.stringify(source)}`;
371
- observations.set(
372
- source,
373
- CompilerArgumentsInspection.observeInputFile(source),
374
- );
368
+ observations.set(source, observeSourceIdentity(source));
375
369
  }
376
370
  for (const [file, before] of inspected.observations)
377
371
  if (CompilerArgumentsInspection.observeInputFile(file) !== before)
@@ -644,3 +638,11 @@ function writtenJavaScript(stdout: string, cwd: string): string[] {
644
638
  }
645
639
  return [...outputs];
646
640
  }
641
+
642
+ /**
643
+ * Source ownership is a physical path; text freshness belongs to cache
644
+ * admission.
645
+ */
646
+ function observeSourceIdentity(source: string): string {
647
+ return fs.realpathSync.native(source);
648
+ }
@@ -339,6 +339,7 @@ export function parseReferenceGraph(
339
339
  return undefined;
340
340
  }
341
341
  const section = value as {
342
+ compilationSnapshot?: unknown;
342
343
  candidates?: unknown;
343
344
  configs?: unknown;
344
345
  edges?: unknown;
@@ -420,6 +421,10 @@ export function parseReferenceGraph(
420
421
  }
421
422
  return {
422
423
  ...(Object.keys(candidates).length === 0 ? {} : { candidates }),
424
+ ...(typeof section.compilationSnapshot === "string" &&
425
+ section.compilationSnapshot.length !== 0
426
+ ? { compilationSnapshot: section.compilationSnapshot }
427
+ : {}),
423
428
  configs,
424
429
  edges,
425
430
  globals,