@native-sdk/cli 0.8.4 → 0.9.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 (146) hide show
  1. package/build/app.zig +859 -62
  2. package/build.zig +543 -13
  3. package/build.zig.zon +1 -0
  4. package/native-sdk.d.ts +2 -0
  5. package/package.json +12 -11
  6. package/packages/core/compile-surface/core.ts +365 -2
  7. package/packages/core/package-lock.json +11 -11
  8. package/packages/core/package.json +2 -2
  9. package/packages/core/scripts/compiler_typecheck.mjs +116 -15
  10. package/packages/core/scripts/gen_service_surface.mjs +268 -0
  11. package/packages/core/scripts/npm_static_spike.mjs +64 -0
  12. package/packages/core/scripts/run_external_core_compiler.mjs +77 -6
  13. package/packages/core/scripts/run_external_service_compiler.mjs +240 -0
  14. package/packages/core/scripts/stage_external_core.mjs +9 -1
  15. package/packages/core/scripts/stage_external_services.mjs +172 -0
  16. package/packages/core/scripts/surface_manifest_diff.mjs +253 -0
  17. package/packages/core/scripts/vendor_service_packages.mjs +189 -0
  18. package/packages/core/sdk/core.d.ts +149 -0
  19. package/packages/core/sdk/core.ts +529 -12
  20. package/packages/core/sdk/events.d.ts +36 -0
  21. package/packages/core/sdk/events.ts +57 -0
  22. package/packages/core/src/checker.ts +468 -15
  23. package/packages/core/src/cli.ts +143 -3
  24. package/packages/core/src/contract.ts +26 -5
  25. package/packages/core/src/devhost.ts +1847 -16
  26. package/packages/core/src/devhost_journal.mjs +181 -0
  27. package/packages/core/src/devhost_resolver.mjs +17 -1
  28. package/packages/core/src/devhost_service_worker.mjs +90 -0
  29. package/packages/core/src/diagnostics.ts +82 -16
  30. package/packages/core/src/frontend.ts +204 -34
  31. package/packages/core/src/modules.ts +129 -80
  32. package/packages/core/src/service_contract.ts +597 -0
  33. package/packages/core/src/sqlite_cli.ts +93 -0
  34. package/packages/core/src/sqlite_codegen.ts +806 -0
  35. package/packages/core/src/sqlite_runtime_policy.ts +364 -0
  36. package/packages/core/src/typed_ast.ts +36 -8
  37. package/skill-data/core/references/project-anatomy.md +1 -1
  38. package/skill-data/native-ui/SKILL.md +47 -0
  39. package/skill-data/ts-core/SKILL.md +80 -31
  40. package/skill-data/ts-services/SKILL.md +126 -0
  41. package/skill-data/ts-services/references/service-surface.md +603 -0
  42. package/skill-data/zig/SKILL.md +1 -1
  43. package/skills/native-sdk/SKILL.md +1 -1
  44. package/src/app_runner/no_migrations.zig +3 -0
  45. package/src/app_runner/no_services.zig +20 -0
  46. package/src/app_runner/root.zig +104 -4
  47. package/src/app_runner/ts_core_main.zig +249 -8
  48. package/src/automation/snapshot.zig +23 -5
  49. package/src/embed/app_exports.zig +11 -1
  50. package/src/embed/c_api.zig +48 -2
  51. package/src/embed/conversions.zig +4 -5
  52. package/src/embed/host.zig +109 -1
  53. package/src/embed/root.zig +7 -0
  54. package/src/embed/tests.zig +213 -0
  55. package/src/embed/types.zig +51 -0
  56. package/src/embed/ui_host.zig +119 -5
  57. package/src/platform/android/NativeSdkActivity.java +131 -0
  58. package/src/platform/android/android_host.c +182 -1
  59. package/src/platform/android/native_sdk_app.h +17 -0
  60. package/src/platform/ios/native_sdk_app.h +17 -0
  61. package/src/platform/ios/uikit_host.m +115 -0
  62. package/src/platform/linux/cef_host.cpp +1 -1
  63. package/src/platform/linux/gtk_host.c +89 -17
  64. package/src/platform/linux/gtk_host.h +3 -0
  65. package/src/platform/linux/root.zig +40 -18
  66. package/src/platform/macos/appkit_host.h +16 -3
  67. package/src/platform/macos/appkit_host.m +536 -36
  68. package/src/platform/macos/cef_host.mm +248 -36
  69. package/src/platform/macos/root.zig +244 -34
  70. package/src/platform/null_platform.zig +223 -19
  71. package/src/platform/null_platform_tests.zig +74 -0
  72. package/src/platform/root.zig +9 -0
  73. package/src/platform/types.zig +179 -15
  74. package/src/platform/windows/root.zig +187 -21
  75. package/src/platform/windows/webview2_host.cpp +293 -46
  76. package/src/primitives/app_manifest/comptime_scene.zig +2 -0
  77. package/src/primitives/app_manifest/root.zig +4 -0
  78. package/src/primitives/app_manifest/tests.zig +3 -0
  79. package/src/primitives/app_manifest/types.zig +32 -0
  80. package/src/primitives/app_manifest/validation.zig +19 -1
  81. package/src/root.zig +46 -0
  82. package/src/runtime/api.zig +11 -0
  83. package/src/runtime/automation_snapshot.zig +4 -0
  84. package/src/runtime/bridge_permission_tests.zig +23 -2
  85. package/src/runtime/bridge_responses.zig +3 -1
  86. package/src/runtime/canvas_frame.zig +18 -11
  87. package/src/runtime/canvas_frame_animation_tests.zig +4 -0
  88. package/src/runtime/clock.zig +13 -1
  89. package/src/runtime/core.zig +133 -1
  90. package/src/runtime/credentials_store.zig +115 -0
  91. package/src/runtime/effects.zig +2295 -113
  92. package/src/runtime/effects_credentials_tests.zig +332 -0
  93. package/src/runtime/effects_host_tests.zig +208 -1
  94. package/src/runtime/effects_relational_tests.zig +314 -0
  95. package/src/runtime/effects_store_tests.zig +211 -0
  96. package/src/runtime/flow.zig +14 -1
  97. package/src/runtime/gpu_surface_events.zig +6 -1
  98. package/src/runtime/native_command_event_tests.zig +42 -0
  99. package/src/runtime/persist_store.zig +666 -0
  100. package/src/runtime/record_store.zig +788 -0
  101. package/src/runtime/relational_store.zig +854 -0
  102. package/src/runtime/root.zig +49 -0
  103. package/src/runtime/runtime_event_tests.zig +70 -0
  104. package/src/runtime/service_host.zig +711 -0
  105. package/src/runtime/service_pool.zig +1314 -0
  106. package/src/runtime/session_blobs.zig +1 -1
  107. package/src/runtime/session_journal.zig +102 -0
  108. package/src/runtime/session_record.zig +177 -0
  109. package/src/runtime/session_replay.zig +109 -4
  110. package/src/runtime/shell_layout.zig +1 -0
  111. package/src/runtime/shell_layout_tests.zig +120 -0
  112. package/src/runtime/sqlite_engine.zig +474 -0
  113. package/src/runtime/state.zig +6 -0
  114. package/src/runtime/system_services.zig +49 -10
  115. package/src/runtime/tests.zig +4 -0
  116. package/src/runtime/ts_core_host.zig +788 -86
  117. package/src/runtime/ts_core_host_tests.zig +231 -11
  118. package/src/runtime/ts_ui_app.zig +499 -1
  119. package/src/runtime/ui_app.zig +142 -16
  120. package/src/runtime/ui_app_tests.zig +155 -5
  121. package/src/runtime/validation.zig +22 -0
  122. package/src/runtime/view.zig +9 -0
  123. package/src/runtime/window_storage.zig +1 -0
  124. package/src/runtime/window_view_runtime.zig +2 -3
  125. package/src/runtime/window_views.zig +19 -0
  126. package/src/tooling/android.zig +21 -16
  127. package/src/tooling/db.zig +160 -0
  128. package/src/tooling/ios.zig +7 -1
  129. package/src/tooling/manifest.zig +214 -2
  130. package/src/tooling/package.zig +116 -0
  131. package/src/tooling/raw_manifest.zig +30 -0
  132. package/src/tooling/root.zig +1 -0
  133. package/src/tooling/templates.zig +161 -4
  134. package/src/tooling/ts_core.zig +283 -17
  135. package/src/tooling/verbs.zig +7 -0
  136. package/third_party/sqlite/README.md +13 -0
  137. package/third_party/sqlite/sqlite3.c +269649 -0
  138. package/third_party/sqlite/sqlite3.h +14349 -0
  139. package/tools/corewire/core_abi.zig +14 -2
  140. package/tools/corewire/emit.zig +98 -29
  141. package/tools/corewire/emit_facade.zig +378 -23
  142. package/tools/corewire/emit_profile.zig +6 -2
  143. package/tools/corewire/emit_service.zig +924 -0
  144. package/tools/corewire/main.zig +122 -0
  145. package/tools/corewire/service_contract.zig +250 -0
  146. package/tools/corewire/sidecar.zig +26 -15
@@ -11,7 +11,9 @@ import { resolveModuleGraph } from "./modules.ts";
11
11
  import { TypeTable } from "./types.ts";
12
12
  import { IntInference } from "./infer.ts";
13
13
  import { SubsetChecker } from "./checker.ts";
14
+ import type { PersistRoutes } from "./checker.ts";
14
15
  import { emitContractSidecar, ContractError } from "./contract.ts";
16
+ import { emitServiceContract, type ServicePackage } from "./service_contract.ts";
15
17
  import { makeDiagnostic, formatDiagnostic, type SubsetDiagnostic } from "./diagnostics.ts";
16
18
  import path from "node:path";
17
19
  import fs from "node:fs";
@@ -21,6 +23,32 @@ export interface FrontendOptions {
21
23
  /// schema format 1) from the checked program — the entry spelling the
22
24
  /// document states (never a filesystem-absolute leak).
23
25
  readonly contractEntry?: string;
26
+ /// Ask the CLI/API caller to consume services.contract.json. The service
27
+ /// surface is analyzed whenever src/services exists because core request
28
+ /// names validate against it; this flag records emission intent.
29
+ readonly servicesContract?: boolean;
30
+ /// Exact checked-in npm package facts from app.zon. Bare imports in the
31
+ /// service class are accepted only when named here; the sidecar carries
32
+ /// the same name/version/hash facts into the offline staging gate.
33
+ readonly servicePackages?: readonly ServicePackage[];
34
+ /// app.zon capabilities supplied by the build/check launcher. The core
35
+ /// frontend stays manifest-format agnostic; it needs only declared names
36
+ /// for capability-backed effect diagnostics.
37
+ readonly capabilities?: readonly string[];
38
+ /// app.zon permissions supplied beside capabilities. Core credential
39
+ /// effects are refused unless the explicit runtime grant is present.
40
+ readonly permissions?: readonly string[];
41
+ /// Manifest schema version for engine-owned model persistence. When a
42
+ /// state path is also supplied, the frontend remembers the last accepted
43
+ /// version/fingerprint pair and warns if a shape moves without a bump.
44
+ readonly persistVersion?: number;
45
+ readonly persistStatePath?: string;
46
+ /// app.zon's persistence restore routes, projected without manifest syntax
47
+ /// so the frontend can validate them against the core's Msg union.
48
+ readonly persistRoutes?: PersistRoutes;
49
+ /// Generated @native-sdk/core surface carrying declared SQLite query
50
+ /// constructors. Omitted for non-relational apps and direct checker tests.
51
+ readonly sdkCorePath?: string;
24
52
  }
25
53
 
26
54
  export interface FrontendResult {
@@ -28,9 +56,14 @@ export interface FrontendResult {
28
56
  /// The contract sidecar JSON, when options.contractEntry asked for it
29
57
  /// (null otherwise, and on any failed check).
30
58
  readonly contract: string | null;
59
+ /// The non-deterministic service registry, or null when the app has no
60
+ /// src/services modules (and on any failed check).
61
+ readonly servicesContract: string | null;
62
+ /// The generated typed-client module projected from the service sidecar.
63
+ readonly servicesClient: string | null;
31
64
  readonly diagnostics: SubsetDiagnostic[];
32
- /// Non-fatal teaching notices (NS1028 today): surfaced as warnings,
33
- /// never failing the check.
65
+ /// Non-fatal capability and persistence-contract teaching notices:
66
+ /// surfaced as warnings, never failing the check.
34
67
  readonly warnings: SubsetDiagnostic[];
35
68
  /// Provider (tsc-semantics) diagnostics, already formatted.
36
69
  readonly typeErrors: string[];
@@ -43,30 +76,98 @@ export function checkFile(entry: string, options: FrontendOptions = {}): Fronten
43
76
  // Module-boundary mistakes (NS1034-NS1037) teach BEFORE the type-checked
44
77
  // program is built: a missing file or an escaped src/ boundary would
45
78
  // otherwise surface as a raw resolution error.
46
- const graph = resolveModuleGraph(entry);
79
+ const graph = resolveModuleGraph(
80
+ entry,
81
+ (options.servicePackages ?? []).map((packageEntry) => packageEntry.name),
82
+ options.sdkCorePath,
83
+ );
47
84
  if (graph.diagnostics.length > 0) {
48
- return { ok: false, contract: null, diagnostics: graph.diagnostics, warnings: [], typeErrors: [], inputs: [...graph.files] };
85
+ return { ok: false, contract: null, servicesContract: null, servicesClient: null, diagnostics: graph.diagnostics, warnings: [], typeErrors: [], inputs: [...graph.files] };
49
86
  }
50
87
 
51
- const program = createSubsetProgram(entry);
52
- const tast = new TypedAst(program);
53
- const byPath = new Map(program.getSourceFiles().map((f) => [path.resolve(f.fileName), f]));
54
- const files: ts.SourceFile[] = [];
55
- for (const p of graph.files) {
56
- const file = byPath.get(path.resolve(p));
57
- if (!file) {
58
- return { ok: false, contract: null, diagnostics: [], warnings: [], typeErrors: [`cannot read ${p}`], inputs: [...graph.files] };
59
- }
60
- files.push(file);
88
+ const loadProgramFiles = (program: ts.Program): {
89
+ readonly files: ts.SourceFile[];
90
+ readonly coreFiles: ts.SourceFile[];
91
+ readonly serviceFiles: ts.SourceFile[];
92
+ readonly serviceHostFiles: ts.SourceFile[];
93
+ } | null => {
94
+ const byPath = new Map(program.getSourceFiles().map((file) => [path.resolve(file.fileName), file]));
95
+ const files = graph.files.map((file) => byPath.get(path.resolve(file))).filter((file): file is ts.SourceFile => file !== undefined);
96
+ if (files.length !== graph.files.length) return null;
97
+ const fileByPath = new Map(files.map((file) => [path.resolve(file.fileName), file]));
98
+ return {
99
+ files,
100
+ coreFiles: graph.coreFiles.map((file) => fileByPath.get(path.resolve(file))!).filter(Boolean),
101
+ serviceFiles: graph.serviceFiles.map((file) => fileByPath.get(path.resolve(file))!).filter(Boolean),
102
+ serviceHostFiles: graph.serviceHostFiles.map((file) => fileByPath.get(path.resolve(file))!).filter(Boolean),
103
+ };
104
+ };
105
+
106
+ let program = createSubsetProgram(entry, graph.files, new Map(), options.sdkCorePath);
107
+ let loaded = loadProgramFiles(program);
108
+ if (loaded === null || loaded.files.length === 0) {
109
+ return { ok: false, contract: null, servicesContract: null, servicesClient: null, diagnostics: [], warnings: [], typeErrors: [`cannot read ${entry}`], inputs: [...graph.files] };
61
110
  }
62
- if (files.length === 0) {
63
- return { ok: false, contract: null, diagnostics: [], warnings: [], typeErrors: [`cannot read ${entry}`], inputs: [] };
111
+ let tast = new TypedAst(program);
112
+ let coreFiles = loaded.coreFiles;
113
+ let serviceFiles = loaded.serviceFiles;
114
+ let serviceHostFiles = loaded.serviceHostFiles;
115
+ let table = new TypeTable(tast, coreFiles);
116
+ let infer = new IntInference(tast, table, coreFiles);
117
+ let serviceSurface = emitServiceContract(
118
+ tast,
119
+ table,
120
+ infer,
121
+ serviceFiles,
122
+ serviceHostFiles,
123
+ path.dirname(path.resolve(entry)),
124
+ options.servicePackages ?? [],
125
+ );
126
+ if (serviceSurface.diagnostics.length > 0) {
127
+ return { ok: false, contract: null, servicesContract: null, servicesClient: null, diagnostics: [...serviceSurface.diagnostics], warnings: [], typeErrors: [], inputs: [...graph.files] };
128
+ }
129
+
130
+ // The typed client is virtual during checking: authors import the stable
131
+ // `@native-sdk/services` name, while builds stage this projection as
132
+ // src/services.gen.ts. Rebuild the one provider program with that module
133
+ // mapped at its logical src-root location; generated code is typechecked
134
+ // but excluded from the authored core's NS walk.
135
+ if (serviceSurface.client !== null) {
136
+ const generatedPath = path.join(path.dirname(path.resolve(entry)), "services.gen.ts");
137
+ program = createSubsetProgram(entry, graph.files, new Map([[generatedPath, serviceSurface.client]]), options.sdkCorePath);
138
+ loaded = loadProgramFiles(program);
139
+ if (loaded === null) {
140
+ return { ok: false, contract: null, servicesContract: null, servicesClient: null, diagnostics: [], warnings: [], typeErrors: ["cannot materialize the generated service client"], inputs: [...graph.files] };
141
+ }
142
+ tast = new TypedAst(program);
143
+ coreFiles = loaded.coreFiles;
144
+ serviceFiles = loaded.serviceFiles;
145
+ serviceHostFiles = loaded.serviceHostFiles;
146
+ table = new TypeTable(tast, coreFiles);
147
+ infer = new IntInference(tast, table, coreFiles);
148
+ serviceSurface = emitServiceContract(
149
+ tast,
150
+ table,
151
+ infer,
152
+ serviceFiles,
153
+ serviceHostFiles,
154
+ path.dirname(path.resolve(entry)),
155
+ options.servicePackages ?? [],
156
+ );
157
+ if (serviceSurface.diagnostics.length > 0) {
158
+ return { ok: false, contract: null, servicesContract: null, servicesClient: null, diagnostics: [...serviceSurface.diagnostics], warnings: [], typeErrors: [], inputs: [...graph.files] };
159
+ }
64
160
  }
65
161
 
66
162
  const typeErrors: string[] = [];
67
- for (const file of files) {
163
+ // The provider catches ordinary shape/type errors in both classes before
164
+ // either compile lane starts. Its declaration universe intentionally has
165
+ // no Node/npm packages, so unresolved ambient service imports are deferred
166
+ // to the pinned scriptc verdict and its static-tier coverage report.
167
+ for (const file of [...coreFiles, ...serviceFiles]) {
68
168
  for (const d of tast.fileDiagnostics(file)) {
69
169
  if (d.category !== ts.DiagnosticCategory.Error) continue;
170
+ if (serviceFiles.includes(file) && new Set([2304, 2307, 2503, 2580, 2591, 7016]).has(d.code)) continue;
70
171
  const where = d.file && d.start !== undefined ? lineColumn(d.file, d.start) : null;
71
172
  const msg = ts.flattenDiagnosticMessageText(d.messageText, "\n");
72
173
  const name = d.file?.fileName ?? file.fileName;
@@ -74,20 +175,10 @@ export function checkFile(entry: string, options: FrontendOptions = {}): Fronten
74
175
  }
75
176
  }
76
177
  if (typeErrors.length > 0) {
77
- return { ok: false, contract: null, diagnostics: [], warnings: [], typeErrors: [...new Set(typeErrors)], inputs: [...graph.files] };
78
- }
79
-
80
- const table = new TypeTable(tast, files);
81
- const checker = new SubsetChecker(tast, table, files);
82
- const checkResult = checker.check();
83
- if (checkResult.diagnostics.length > 0) {
84
- return { ok: false, contract: null, diagnostics: checkResult.diagnostics, warnings: checkResult.warnings, typeErrors: [], inputs: [...graph.files] };
178
+ return { ok: false, contract: null, servicesContract: null, servicesClient: null, diagnostics: [], warnings: [], typeErrors: [...new Set(typeErrors)], inputs: [...graph.files] };
85
179
  }
86
180
 
87
- const infer = new IntInference(tast, table, files);
88
181
  if (infer.conflicts.length > 0) {
89
- // R2 consistency: an edge the inference fixed point could not make
90
- // same-typed is the author's to resolve, taught at check time.
91
182
  const diagnostics = infer.conflicts.map((c) => {
92
183
  const file = c.node.getSourceFile();
93
184
  const { line, column } = lineColumn(file, c.node.getStart());
@@ -99,27 +190,106 @@ export function checkFile(entry: string, options: FrontendOptions = {}): Fronten
99
190
  column,
100
191
  );
101
192
  });
102
- return { ok: false, contract: null, diagnostics, warnings: checkResult.warnings, typeErrors: [], inputs: [...graph.files] };
193
+ return { ok: false, contract: null, servicesContract: null, servicesClient: null, diagnostics, warnings: [], typeErrors: [], inputs: [...graph.files] };
194
+ }
195
+ const serviceOps = serviceSurface.contract === null
196
+ ? null
197
+ : new Set(serviceSurface.operations.map((op) => op.name));
198
+ const checker = new SubsetChecker(
199
+ tast,
200
+ table,
201
+ coreFiles,
202
+ serviceOps,
203
+ options.capabilities ?? [],
204
+ options.permissions ?? [],
205
+ options.persistRoutes,
206
+ options.sdkCorePath,
207
+ );
208
+ const checkResult = checker.check();
209
+ if (checkResult.diagnostics.length > 0) {
210
+ return { ok: false, contract: null, servicesContract: null, servicesClient: null, diagnostics: checkResult.diagnostics, warnings: checkResult.warnings, typeErrors: [], inputs: [...graph.files] };
103
211
  }
104
212
  try {
105
213
  // The contract sidecar emits from the SAME checked analysis, so a
106
214
  // contract-bearing run keeps every check-time teaching.
107
- const contract =
108
- options.contractEntry !== undefined
109
- ? emitContractSidecar({ tast, table, infer, checkResult, files, entry: options.contractEntry })
215
+ const emittedContract =
216
+ options.contractEntry !== undefined || options.persistVersion !== undefined
217
+ ? emitContractSidecar({ tast, table, infer, checkResult, files: coreFiles, entry: options.contractEntry ?? "src/core.ts" })
110
218
  : null;
111
- return { ok: true, contract, diagnostics: [], warnings: checkResult.warnings, typeErrors: [], inputs: [...graph.files] };
219
+ const warnings = [...checkResult.warnings];
220
+ if (emittedContract !== null && options.persistVersion !== undefined && options.persistStatePath !== undefined) {
221
+ const fingerprint = (JSON.parse(emittedContract) as { model_fingerprint: string }).model_fingerprint;
222
+ warnings.push(...checkPersistSchemaState(coreFiles[0], options.persistStatePath, options.persistVersion, fingerprint));
223
+ }
224
+ const contract = options.contractEntry !== undefined ? emittedContract : null;
225
+ return { ok: true, contract, servicesContract: serviceSurface.contract, servicesClient: serviceSurface.client, diagnostics: [], warnings, typeErrors: [], inputs: [...graph.files] };
112
226
  } catch (e) {
113
227
  if (e instanceof ContractError) {
114
228
  const file = e.node.getSourceFile();
115
229
  const { line, column } = lineColumn(file, e.node.getStart());
116
230
  const d = makeDiagnostic("NS1063", `${e.message[0].toUpperCase()}${e.message.slice(1)}.`, file.fileName, line, column);
117
- return { ok: false, contract: null, diagnostics: [d], warnings: checkResult.warnings, typeErrors: [], inputs: [...graph.files] };
231
+ return { ok: false, contract: null, servicesContract: null, servicesClient: null, diagnostics: [d], warnings: checkResult.warnings, typeErrors: [], inputs: [...graph.files] };
118
232
  }
119
233
  throw e;
120
234
  }
121
235
  }
122
236
 
237
+ interface PersistSchemaState {
238
+ readonly version: number;
239
+ readonly model_fingerprint: string;
240
+ }
241
+
242
+ /// Cache the last accepted schema pair outside authored source. A same-version
243
+ /// shape edit deliberately does not replace the baseline, so every subsequent
244
+ /// check keeps teaching until the manifest version advances.
245
+ function checkPersistSchemaState(
246
+ entry: ts.SourceFile,
247
+ statePath: string,
248
+ version: number,
249
+ fingerprint: string,
250
+ ): SubsetDiagnostic[] {
251
+ let previous: PersistSchemaState | null = null;
252
+ try {
253
+ const parsed = JSON.parse(fs.readFileSync(statePath, "utf8")) as Partial<PersistSchemaState>;
254
+ if (Number.isSafeInteger(parsed.version) && typeof parsed.model_fingerprint === "string") {
255
+ previous = { version: parsed.version!, model_fingerprint: parsed.model_fingerprint };
256
+ }
257
+ } catch {
258
+ // Missing or damaged generated state is a cold check, never a build gate.
259
+ }
260
+
261
+ const { line, column } = lineColumn(entry, entry.getStart());
262
+ if (previous !== null && version < previous.version) {
263
+ return [makeDiagnostic(
264
+ "NS1068",
265
+ `app.zon's persistence version moved backward from ${previous.version} to ${version}.`,
266
+ entry.fileName,
267
+ line,
268
+ column,
269
+ )];
270
+ }
271
+ if (previous !== null && version === previous.version && fingerprint !== previous.model_fingerprint) {
272
+ return [makeDiagnostic(
273
+ "NS1068",
274
+ `The checked Model shape changed while app.zon's persistence version stayed at ${version}.`,
275
+ entry.fileName,
276
+ line,
277
+ column,
278
+ )];
279
+ }
280
+
281
+ try {
282
+ fs.mkdirSync(path.dirname(statePath), { recursive: true });
283
+ const tmp = `${statePath}.${process.pid}.tmp`;
284
+ fs.writeFileSync(tmp, `${JSON.stringify({ version, model_fingerprint: fingerprint }, null, 2)}\n`);
285
+ fs.renameSync(tmp, statePath);
286
+ } catch {
287
+ // This cache improves teaching only; runtime fingerprint validation stays
288
+ // the hard safety gate when a filesystem is read-only.
289
+ }
290
+ return [];
291
+ }
292
+
123
293
  export function checkSource(source: string, name = "core.ts", options: FrontendOptions = {}): FrontendResult {
124
294
  // Test seam: materialize an in-memory file through a temp path-less host.
125
295
  const tmp = path.join(process.env.TMPDIR ?? "/tmp", `native-core-${process.pid}-${Math.random().toString(36).slice(2)}.ts`);
@@ -1,38 +1,35 @@
1
- // The core's import graph: which .ts files make up one app core, resolved
2
- // from src/core.ts BEFORE the type-checked program is built, so every
3
- // module-boundary mistake is a teaching diagnostic (NS1034-NS1037) instead
4
- // of a raw tsc resolution error.
5
- //
6
- // The boundary rules (spec: "src/ is the boundary"):
7
- // - "@native-sdk/core" is the intrinsic SDK surface — typed, never emitted.
8
- // - "@native-sdk/core/<lib>" names a shipped SDK library module (subset
9
- // TypeScript, transpiled into the core when imported — module-granular
10
- // tree-shaking falls out of walking the graph from the entry).
11
- // - "./x.ts" (and "./sub/x.ts") resolve inside the ENTRY MODULE'S
12
- // directory subtree — its src/. Escaping it (../, absolute paths) is
13
- // NS1034; bare npm specifiers are NS1035; a specifier that names no
14
- // file is NS1037.
15
- // - Runtime import cycles are NS1036. Type-only edges (`import type`,
16
- // `export type`) are exempt — they erase under node and constrain no
17
- // emission order — but still pull their target into the graph, because
18
- // its type declarations must exist in the emitted module.
19
- //
20
- // The returned file list is the canonical module order everywhere
21
- // downstream (type table, checker, inference, emission): the entry first,
22
- // then its imports depth-first in source order — deterministic, so emitted
23
- // output is stable across runs.
1
+ // The two-class TypeScript module graph. The app core remains rooted at
2
+ // src/core.ts; every .ts file under src/services/ is an independent service
3
+ // root because a valid core never imports a service. Both classes share one
4
+ // checked TypeScript program, but only `coreFiles` enter the NS subset checker
5
+ // and integer inference.
24
6
 
25
7
  import path from "node:path";
26
8
  import fs from "node:fs";
27
9
  import { ts, sdkCoreModulePath, sdkLibraryModules } from "./typed_ast.ts";
28
- import { makeDiagnostic, type SubsetDiagnostic } from "./diagnostics.ts";
10
+ import { makeDiagnostic, type RuleId, type SubsetDiagnostic } from "./diagnostics.ts";
11
+
12
+ const serviceBuiltins = new Set([
13
+ "fs", "node:fs", "path", "node:path", "process", "node:process", "os", "node:os",
14
+ "child_process", "node:child_process",
15
+ ]);
16
+
17
+ export type ModuleClass = "core" | "service";
29
18
 
30
19
  export interface ModuleGraph {
31
- /// Absolute paths in module order: the entry first, then imports
32
- /// depth-first. Includes imported SDK library modules; never sdk/core.ts.
20
+ /// All program roots/modules in deterministic order: the entry graph first,
21
+ /// followed by the lexically sorted service roots and their dependencies.
33
22
  readonly files: readonly string[];
34
- /// The subset of `files` that are SDK library modules (checker
35
- /// diagnostics inside these are SDK bugs, not app bugs).
23
+ /// Files that retain the complete NS1001-NS1064 core posture. SDK library
24
+ /// modules are included here, as they were before the service seam.
25
+ readonly coreFiles: readonly string[];
26
+ /// Author files under src/services/. The SubsetChecker never visits these.
27
+ readonly serviceFiles: readonly string[];
28
+ /// Author files that can enter the service executable: every service root
29
+ /// plus its runtime-relative dependencies, including shared core-class
30
+ /// modules. Throw validation and the service source fingerprint use this
31
+ /// set rather than only the files physically under src/services/.
32
+ readonly serviceHostFiles: readonly string[];
36
33
  readonly sdkFiles: ReadonlySet<string>;
37
34
  readonly diagnostics: SubsetDiagnostic[];
38
35
  }
@@ -43,16 +40,11 @@ interface Edge {
43
40
  readonly node: ts.Node;
44
41
  }
45
42
 
46
- /// Import/re-export edges of one parsed file, in source order.
47
43
  function edgesOf(file: ts.SourceFile): Edge[] {
48
44
  const out: Edge[] = [];
49
45
  for (const stmt of file.statements) {
50
46
  if (ts.isImportDeclaration(stmt) && ts.isStringLiteral(stmt.moduleSpecifier)) {
51
- out.push({
52
- specifier: stmt.moduleSpecifier.text,
53
- typeOnly: stmt.importClause?.isTypeOnly ?? false,
54
- node: stmt,
55
- });
47
+ out.push({ specifier: stmt.moduleSpecifier.text, typeOnly: stmt.importClause?.isTypeOnly ?? false, node: stmt });
56
48
  } else if (ts.isExportDeclaration(stmt) && stmt.moduleSpecifier && ts.isStringLiteral(stmt.moduleSpecifier)) {
57
49
  out.push({ specifier: stmt.moduleSpecifier.text, typeOnly: stmt.isTypeOnly, node: stmt });
58
50
  }
@@ -60,39 +52,83 @@ function edgesOf(file: ts.SourceFile): Edge[] {
60
52
  return out;
61
53
  }
62
54
 
63
- function diag(
64
- id: "NS1034" | "NS1035" | "NS1036" | "NS1037",
65
- site: string,
66
- file: ts.SourceFile,
67
- node: ts.Node,
68
- ): SubsetDiagnostic {
55
+ function tsFilesUnder(dir: string, excludedRoot?: string): string[] {
56
+ if (!fs.existsSync(dir)) return [];
57
+ const out: string[] = [];
58
+ const walk = (current: string): void => {
59
+ for (const entry of fs.readdirSync(current, { withFileTypes: true })) {
60
+ const child = path.join(current, entry.name);
61
+ if (entry.isDirectory() && path.resolve(child) !== excludedRoot) walk(child);
62
+ else if (entry.isFile() && entry.name.endsWith(".ts") && !entry.name.endsWith(".d.ts")) out.push(path.resolve(child));
63
+ }
64
+ };
65
+ walk(dir);
66
+ return out.sort((a, b) => a.localeCompare(b));
67
+ }
68
+
69
+ function diag(id: RuleId, site: string, file: ts.SourceFile, node: ts.Node): SubsetDiagnostic {
69
70
  const lc = file.getLineAndCharacterOfPosition(node.getStart(file));
70
71
  return makeDiagnostic(id, site, file.fileName, lc.line + 1, lc.character + 1);
71
72
  }
72
73
 
73
- /// Walk the import graph from `entry` (absolute or cwd-relative path).
74
- /// Reads and parses each file once — no type checking here; the caller
75
- /// builds the checked program only when the graph is clean.
76
- export function resolveModuleGraph(entry: string): ModuleGraph {
74
+ /// Resolve the core graph plus every src/services/**/*.ts root. Class is a
75
+ /// path property, never inferred from which root happened to reach a file:
76
+ /// this is what makes a service->core shared-shape edge legal while a
77
+ /// core->service edge is NS1065.
78
+ export function resolveModuleGraph(
79
+ entry: string,
80
+ servicePackages: readonly string[] = [],
81
+ coreModulePath: string = sdkCoreModulePath,
82
+ ): ModuleGraph {
77
83
  const entryPath = path.resolve(entry);
78
84
  const boundary = path.dirname(entryPath);
79
- const sdkBoundary = path.dirname(sdkCoreModulePath);
85
+ const servicesBoundary = path.join(boundary, "services");
86
+ const sdkBoundary = path.dirname(coreModulePath);
80
87
  const diagnostics: SubsetDiagnostic[] = [];
81
88
  const files: string[] = [];
89
+ const coreFiles: string[] = [];
90
+ const serviceFiles: string[] = [];
82
91
  const sdkFiles = new Set<string>();
83
- const visiting = new Set<string>(); // DFS stack for runtime-cycle detection
92
+ const runtimeEdges = new Map<string, string[]>();
84
93
  const done = new Set<string>();
94
+ const visiting = new Set<string>();
95
+ const allowedServicePackages = new Set(servicePackages);
85
96
 
86
- const insideBoundary = (p: string, root: string): boolean => {
97
+ const insideBoundary = (p: string, root: string, includeRoot = false): boolean => {
87
98
  const rel = path.relative(root, p);
88
- return rel !== "" && !rel.startsWith("..") && !path.isAbsolute(rel);
99
+ return (includeRoot ? rel === "" : false) || (rel !== "" && !rel.startsWith("..") && !path.isAbsolute(rel));
100
+ };
101
+ const classOf = (p: string): ModuleClass => insideBoundary(p, servicesBoundary, true) ? "service" : "core";
102
+
103
+ const follow = (
104
+ target: string,
105
+ edge: Edge,
106
+ parsed: ts.SourceFile,
107
+ from: string,
108
+ trail: string[],
109
+ ): void => {
110
+ if (!edge.typeOnly) {
111
+ const targets = runtimeEdges.get(from) ?? [];
112
+ targets.push(target);
113
+ runtimeEdges.set(from, targets);
114
+ }
115
+ if (visiting.has(target)) {
116
+ if (!edge.typeOnly) {
117
+ const names = [...trail, from, target].map((p) => path.basename(p));
118
+ diagnostics.push(diag("NS1036", `\`import ... from "${edge.specifier}"\` closes a ${classOf(from)} import cycle (${names.join(" -> ")}).`, parsed, edge.node));
119
+ }
120
+ return;
121
+ }
122
+ visit(target, [...trail, from]);
89
123
  };
90
124
 
91
- const visit = (filePath: string, fromCycleTrail: string[]): void => {
92
- if (done.has(filePath)) return;
93
- if (visiting.has(filePath)) return; // a cycle is reported at its back-edge
125
+ const visit = (filePath: string, trail: string[]): void => {
126
+ if (done.has(filePath) || visiting.has(filePath)) return;
94
127
  visiting.add(filePath);
95
128
  files.push(filePath);
129
+ const fileClass = classOf(filePath);
130
+ if (fileClass === "service") serviceFiles.push(filePath);
131
+ else coreFiles.push(filePath);
96
132
 
97
133
  const text = fs.readFileSync(filePath, "utf8");
98
134
  const parsed = ts.createSourceFile(filePath, text, ts.ScriptTarget.ESNext, true);
@@ -101,7 +137,20 @@ export function resolveModuleGraph(entry: string): ModuleGraph {
101
137
 
102
138
  for (const edge of edgesOf(parsed)) {
103
139
  const spec = edge.specifier;
104
- if (spec === "@native-sdk/core") continue; // the intrinsic surface — typed, never emitted
140
+
141
+ // Services are ordinary static-tier TypeScript. A bare package import
142
+ // is legal only when app.zon supplied its exact vendored package fact;
143
+ // every undeclared bare specifier gets the NS1066 teaching.
144
+ const generatedServiceTypes = fileClass === "service" && edge.typeOnly && spec === "@native-sdk/core";
145
+ if (fileClass === "service" && !spec.startsWith(".") && !serviceBuiltins.has(spec) && !allowedServicePackages.has(spec) && !generatedServiceTypes) {
146
+ diagnostics.push(diag("NS1066", `\`import ... from "${spec}"\` is a bare service import.`, parsed, edge.node));
147
+ continue;
148
+ }
149
+ if (fileClass === "service" && serviceBuiltins.has(spec)) continue;
150
+ if (fileClass === "service" && allowedServicePackages.has(spec)) continue;
151
+
152
+ if (spec === "@native-sdk/core") continue;
153
+ if (fileClass === "core" && spec === "@native-sdk/services") continue;
105
154
  if (sdkLibraryModules.has(spec)) {
106
155
  const target = path.resolve(sdkLibraryModules.get(spec)!);
107
156
  if (!fs.existsSync(target)) {
@@ -109,28 +158,23 @@ export function resolveModuleGraph(entry: string): ModuleGraph {
109
158
  continue;
110
159
  }
111
160
  sdkFiles.add(target);
112
- follow(target, edge, parsed, filePath, fromCycleTrail);
161
+ follow(target, edge, parsed, filePath, trail);
113
162
  continue;
114
163
  }
115
164
  if (spec.startsWith("@native-sdk/")) {
116
165
  if (edge.typeOnly) continue;
117
- diagnostics.push(diag(
118
- "NS1037",
119
- `\`${spec}\` names no SDK module (this SDK ships ${["@native-sdk/core", ...sdkLibraryModules.keys()].join(", ")}).`,
120
- parsed,
121
- edge.node,
122
- ));
166
+ diagnostics.push(diag("NS1037", `\`${spec}\` names no SDK module (this SDK ships ${["@native-sdk/core", ...sdkLibraryModules.keys()].join(", ")}).`, parsed, edge.node));
123
167
  continue;
124
168
  }
125
169
  if (!spec.startsWith(".")) {
126
- if (edge.typeOnly) continue; // type-only npm imports erase — free
170
+ if (edge.typeOnly) continue;
127
171
  diagnostics.push(diag("NS1035", `\`import ... from "${spec}"\` brings a runtime npm dependency into the core.`, parsed, edge.node));
128
172
  continue;
129
173
  }
130
- // A relative specifier: resolve against the importing file.
174
+
131
175
  const resolved = path.resolve(path.dirname(filePath), spec);
132
176
  if (!insideBoundary(resolved, root) || path.isAbsolute(spec)) {
133
- diagnostics.push(diag("NS1034", `\`import ... from "${spec}"\` resolves outside ${isSdk ? "the SDK's module directory" : "the core's src/ directory"}.`, parsed, edge.node));
177
+ diagnostics.push(diag("NS1034", `\`import ... from "${spec}"\` resolves outside ${isSdk ? "the SDK's module directory" : "the app's src/ directory"}.`, parsed, edge.node));
134
178
  continue;
135
179
  }
136
180
  if (!spec.endsWith(".ts")) {
@@ -145,29 +189,34 @@ export function resolveModuleGraph(entry: string): ModuleGraph {
145
189
  diagnostics.push(diag("NS1037", `\`import ... from "${spec}"\` names no file (looked for ${resolved}).`, parsed, edge.node));
146
190
  continue;
147
191
  }
148
- follow(resolved, edge, parsed, filePath, fromCycleTrail);
192
+ if (fileClass === "core" && classOf(resolved) === "service") {
193
+ diagnostics.push(diag("NS1065", `\`import ... from "${spec}"\` crosses from the core into src/services/.`, parsed, edge.node));
194
+ continue;
195
+ }
196
+ follow(resolved, edge, parsed, filePath, trail);
149
197
  }
150
198
 
151
199
  visiting.delete(filePath);
152
200
  done.add(filePath);
153
201
  };
154
202
 
155
- const follow = (target: string, edge: Edge, parsed: ts.SourceFile, from: string, trail: string[]): void => {
156
- if (visiting.has(target)) {
157
- // A back-edge. Runtime cycles are taught; type-only ones erase.
158
- if (!edge.typeOnly) {
159
- const names = [...trail, from, target].map((p) => path.basename(p));
160
- diagnostics.push(diag("NS1036", `\`import ... from "${edge.specifier}"\` closes an import cycle (${names.join(" -> ")}).`, parsed, edge.node));
161
- }
162
- return;
163
- }
164
- visit(target, [...trail, from]);
165
- };
166
-
167
- if (!fs.existsSync(entryPath)) {
168
- // The caller reports the unreadable entry itself.
169
- return { files: [], sdkFiles, diagnostics };
170
- }
203
+ if (!fs.existsSync(entryPath)) return { files: [], coreFiles, serviceFiles, serviceHostFiles: [], sdkFiles, diagnostics };
171
204
  visit(entryPath, []);
172
- return { files, sdkFiles, diagnostics };
205
+ // Vendored package sources are package-manager inputs, not service
206
+ // operation roots. They enter the staged node_modules tree only after the
207
+ // contract's hash gate accepts them.
208
+ const serviceRoots = tsFilesUnder(servicesBoundary, path.resolve(servicesBoundary, "vendor"));
209
+ for (const serviceRoot of serviceRoots) visit(serviceRoot, []);
210
+
211
+ const serviceReachable = new Set<string>();
212
+ const markServiceReachable = (filePath: string): void => {
213
+ if (serviceReachable.has(filePath)) return;
214
+ serviceReachable.add(filePath);
215
+ for (const target of runtimeEdges.get(filePath) ?? []) markServiceReachable(target);
216
+ };
217
+ for (const serviceRoot of serviceRoots) markServiceReachable(serviceRoot);
218
+ const serviceHostFiles = files.filter((filePath) =>
219
+ serviceReachable.has(filePath) && insideBoundary(filePath, boundary, true)
220
+ );
221
+ return { files, coreFiles, serviceFiles, serviceHostFiles, sdkFiles, diagnostics };
173
222
  }