@nimiplatform/app-tools 0.1.2 → 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 (120) hide show
  1. package/LICENSE +198 -6
  2. package/README.md +83 -27
  3. package/bin/nimi-app.mjs +328 -45
  4. package/lib/app-access-declaration.mjs +49 -0
  5. package/lib/app-doctor-update.mjs +411 -149
  6. package/lib/app-pack.mjs +401 -0
  7. package/lib/app-project-lifecycle.mjs +1141 -0
  8. package/lib/app-scaffold-capabilities.mjs +769 -0
  9. package/lib/app-scaffold-default-source.mjs +21 -0
  10. package/lib/app-scaffold-profiles.mjs +1093 -0
  11. package/lib/app-scaffold.mjs +1266 -813
  12. package/lib/index.mjs +194 -42
  13. package/lib/simulator-conformance-ast.mjs +498 -0
  14. package/lib/simulator-conformance-css.mjs +116 -0
  15. package/lib/simulator-conformance-graph.mjs +757 -0
  16. package/lib/simulator-conformance.d.mts +14 -0
  17. package/lib/simulator-conformance.mjs +203 -0
  18. package/lib/simulator-css-profile.d.mts +27 -0
  19. package/lib/simulator-css-profile.mjs +531 -0
  20. package/lib/simulator-kit-export-resolution.mjs +70 -0
  21. package/lib/simulator-manifest.mjs +334 -0
  22. package/package.json +66 -3
  23. package/scripts/dev-shell.mjs +465 -0
  24. package/scripts/sync-app-source.mjs +300 -0
  25. package/scripts/sync-scaffold-versions.mjs +91 -0
  26. package/templates/app-source/LICENSE +21 -0
  27. package/templates/app-source/src/ai-studio-core/ai-config.ts +100 -0
  28. package/templates/app-source/src/ai-studio-core/ai-studio-core.css +338 -0
  29. package/templates/app-source/src/ai-studio-core/contexts.tsx +61 -0
  30. package/templates/app-source/src/ai-studio-core/history-policy.ts +447 -0
  31. package/templates/app-source/src/ai-studio-core/history.ts +824 -0
  32. package/templates/app-source/src/ai-studio-core/host-context.tsx +79 -0
  33. package/templates/app-source/src/ai-studio-core/index.ts +214 -0
  34. package/templates/app-source/src/ai-studio-core/messages/en.json +310 -0
  35. package/templates/app-source/src/ai-studio-core/messages/index.ts +47 -0
  36. package/templates/app-source/src/ai-studio-core/messages/zh.json +310 -0
  37. package/templates/app-source/src/ai-studio-core/module-registration.ts +109 -0
  38. package/templates/app-source/src/ai-studio-core/non-success-presentation.ts +65 -0
  39. package/templates/app-source/src/ai-studio-core/parameter-fields.tsx +247 -0
  40. package/templates/app-source/src/ai-studio-core/parameters.ts +110 -0
  41. package/templates/app-source/src/ai-studio-core/prompt-drafts.ts +69 -0
  42. package/templates/app-source/src/ai-studio-core/run-target.ts +123 -0
  43. package/templates/app-source/src/ai-studio-core/runtime-dispatcher.ts +35 -0
  44. package/templates/app-source/src/ai-studio-core/runtime-types.ts +86 -0
  45. package/templates/app-source/src/ai-studio-core/runtime.ts +306 -0
  46. package/templates/app-source/src/ai-studio-core/section-ai-testing-admission.ts +38 -0
  47. package/templates/app-source/src/ai-studio-core/section-ai-testing-ai-config.tsx +30 -0
  48. package/templates/app-source/src/ai-studio-core/section-ai-testing-artifact-preview.ts +40 -0
  49. package/templates/app-source/src/ai-studio-core/section-ai-testing-composer.tsx +257 -0
  50. package/templates/app-source/src/ai-studio-core/section-ai-testing-history.tsx +676 -0
  51. package/templates/app-source/src/ai-studio-core/section-ai-testing-input.ts +19 -0
  52. package/templates/app-source/src/ai-studio-core/section-ai-testing-output.tsx +291 -0
  53. package/templates/app-source/src/ai-studio-core/section-ai-testing-result.tsx +413 -0
  54. package/templates/app-source/src/ai-studio-core/section-ai-testing-run.ts +174 -0
  55. package/templates/app-source/src/ai-studio-core/section-ai-testing-studio-result.tsx +449 -0
  56. package/templates/app-source/src/ai-studio-core/section-ai-testing-surface.tsx +45 -0
  57. package/templates/app-source/src/ai-studio-core/section-ai-testing.tsx +494 -0
  58. package/templates/app-source/src/ai-studio-core/studio-directives.ts +33 -0
  59. package/templates/app-source/src/ai-studio-core/workspace.tsx +381 -0
  60. package/templates/app-source/src/product-modules/agent-center/index.tsx +27 -0
  61. package/templates/app-source/src/product-modules/agent-conversation/index.tsx +19 -0
  62. package/templates/app-source/src/product-modules/agent-realtime/index.tsx +29 -0
  63. package/templates/app-source/src/product-modules/kit-recipes/gallery.tsx +142 -0
  64. package/templates/app-source/src/product-modules/kit-recipes/index.tsx +19 -0
  65. package/templates/app-source/src/product-modules/kit-recipes/kit-component-gallery-data-recipes.tsx +336 -0
  66. package/templates/app-source/src/product-modules/kit-recipes/kit-component-gallery-demos.tsx +165 -0
  67. package/templates/app-source/src/product-modules/kit-recipes/kit-component-gallery-recipes.tsx +682 -0
  68. package/templates/app-source/src/product-modules/kit-recipes/kit-component-gallery-surface.tsx +341 -0
  69. package/templates/app-source/src/studio-modules/studio-create/descriptors.ts +26 -0
  70. package/templates/app-source/src/studio-modules/studio-create/index.ts +14 -0
  71. package/templates/app-source/src/studio-modules/studio-create/messages/en.json +67 -0
  72. package/templates/app-source/src/studio-modules/studio-create/messages/index.ts +5 -0
  73. package/templates/app-source/src/studio-modules/studio-create/messages/zh.json +67 -0
  74. package/templates/app-source/src/studio-modules/studio-create/parameter-panel.tsx +153 -0
  75. package/templates/app-source/src/studio-modules/studio-create/parameters.ts +70 -0
  76. package/templates/app-source/src/studio-modules/studio-create/registration.ts +46 -0
  77. package/templates/app-source/src/studio-modules/studio-create/runtime.ts +339 -0
  78. package/templates/app-source/src/studio-modules/studio-media/descriptors.ts +22 -0
  79. package/templates/app-source/src/studio-modules/studio-media/index.ts +12 -0
  80. package/templates/app-source/src/studio-modules/studio-media/messages/en.json +82 -0
  81. package/templates/app-source/src/studio-modules/studio-media/messages/index.ts +5 -0
  82. package/templates/app-source/src/studio-modules/studio-media/messages/zh.json +82 -0
  83. package/templates/app-source/src/studio-modules/studio-media/parameter-panel.tsx +283 -0
  84. package/templates/app-source/src/studio-modules/studio-media/parameters.ts +94 -0
  85. package/templates/app-source/src/studio-modules/studio-media/registration.ts +44 -0
  86. package/templates/app-source/src/studio-modules/studio-media/runtime.ts +113 -0
  87. package/templates/app-source/src/studio-modules/studio-voice/descriptors.ts +28 -0
  88. package/templates/app-source/src/studio-modules/studio-voice/index.ts +16 -0
  89. package/templates/app-source/src/studio-modules/studio-voice/messages/en.json +99 -0
  90. package/templates/app-source/src/studio-modules/studio-voice/messages/index.ts +5 -0
  91. package/templates/app-source/src/studio-modules/studio-voice/messages/zh.json +99 -0
  92. package/templates/app-source/src/studio-modules/studio-voice/parameter-panel.tsx +284 -0
  93. package/templates/app-source/src/studio-modules/studio-voice/parameters.ts +116 -0
  94. package/templates/app-source/src/studio-modules/studio-voice/registration.ts +59 -0
  95. package/templates/app-source/src/studio-modules/studio-voice/runtime.ts +347 -0
  96. package/templates/app-source/src/workbench-core/empty-state.tsx +31 -0
  97. package/templates/app-source/src/workbench-core/index.ts +17 -0
  98. package/templates/app-source/src/workbench-core/runtime-gate.tsx +131 -0
  99. package/templates/app-source/src/workbench-core/workbench-core.css +255 -0
  100. package/templates/app-source/src/workbench-core/workbench-core.tsx +140 -0
  101. package/templates/app-source.manifest.json +333 -0
  102. package/templates/default-starter/AGENTS.md +33 -0
  103. package/templates/default-starter/LICENSE +21 -0
  104. package/templates/default-starter/README.md +41 -0
  105. package/templates/default-starter/SECURITY.md +5 -0
  106. package/templates/default-starter/index.html +12 -0
  107. package/templates/default-starter/scripts/validate.mjs +26 -0
  108. package/templates/default-starter/src/shell/App.tsx +27 -0
  109. package/templates/default-starter/src/shell/auth/app-identity.ts +3 -0
  110. package/templates/default-starter/src/shell/auth/local-app-client.ts +18 -0
  111. package/templates/default-starter/src/shell/auth/runtime-platform.ts +110 -0
  112. package/templates/default-starter/src/shell/authenticated-shell.tsx +20 -0
  113. package/templates/default-starter/src/shell/workbench-target-adapter.ts +40 -0
  114. package/templates/default-starter/src/styles.css +26 -0
  115. package/templates/default-starter/src-tauri/Cargo.toml +17 -0
  116. package/templates/default-starter/src-tauri/build.rs +5 -0
  117. package/templates/default-starter/src-tauri/capabilities/default.json +7 -0
  118. package/templates/default-starter/src-tauri/tauri.conf.json +26 -0
  119. package/templates/default-starter/tsconfig.json +18 -0
  120. package/templates/default-starter.manifest.json +99 -0
@@ -1,22 +1,311 @@
1
1
  import path from 'node:path';
2
2
  import { createHash } from 'node:crypto';
3
-
4
- const DEFAULT_APP_ID = 'my-nimi-app';
3
+ import YAML from 'yaml';
4
+ import {
5
+ WORKBENCH_CORE_SOURCE_ROOT,
6
+ readAppSourceFile,
7
+ resolveAppSource,
8
+ } from '../scripts/sync-app-source.mjs';
9
+ import { loadDefaultStarterSource, readDefaultStarterSourceFile } from './app-scaffold-default-source.mjs';
10
+ import { normalizeAppAccessItems } from './app-access-declaration.mjs';
11
+ import {
12
+ resolveAppScaffoldCandidateFeatures,
13
+ resolveAppScaffoldFeatures,
14
+ resolveAppScaffoldIntentFeatures,
15
+ validateAppScaffoldCargoDependencyValue,
16
+ validateAppScaffoldNpmRegistryVersion,
17
+ } from './app-scaffold-capabilities.mjs';
18
+ import {
19
+ SUPPORTED_APP_SCAFFOLD_PROFILES,
20
+ buildDefaultStarterFiles,
21
+ } from './app-scaffold-profiles.mjs';
22
+ export { SUPPORTED_APP_SCAFFOLD_PROFILES };
23
+ const DEFAULT_APP_ID = 'my.nimi-app';
5
24
  const DEFAULT_APP_TITLE = 'My Nimi App';
6
- export const SCAFFOLD_VERSION = '2026-05-24.wave-4-remediation-b';
7
- export const SCAFFOLD_LOCK_PATH = '.nimi/scaffold.lock.json';
8
- export const SUPPORTED_APP_SCAFFOLD_PROFILES = ['standalone', 'workspace-app'];
9
- const SCAFFOLD_LICENSE_YEAR = '2026';
25
+ const DEFAULT_APP_VERSION = '0.1.0';
26
+ const SEMVER_PATTERN = /^(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)(?:-[0-9A-Za-z]+(?:[.-][0-9A-Za-z]+)*)?(?:\+[0-9A-Za-z]+(?:[.-][0-9A-Za-z]+)*)?$/u;
27
+ export const SCAFFOLD_INTENT_VERSION = 4;
28
+ export const SCAFFOLD_LOCK_VERSION = 4;
29
+ export const SCAFFOLD_VERSION = '2026-08-31.app-lifecycle-v1';
30
+ export const SCAFFOLD_STATE_DIR = '.nimi/app-scaffold';
31
+ export const SCAFFOLD_INTENT_PATH = `${SCAFFOLD_STATE_DIR}/intent.json`;
32
+ export const SCAFFOLD_LOCK_PATH = `${SCAFFOLD_STATE_DIR}/lock.json`;
10
33
  const LOCKFILE_POLICY = 'author-install-generates-lockfile';
11
- const MINIMAL_TAURI_ICON_PNG = Buffer.from(
12
- 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR4nGNgAAIAAAUAAXpeqz8AAAAASUVORK5CYII=',
13
- 'base64',
14
- );
34
+ const GENERATED_GITIGNORE = [
35
+ 'node_modules/',
36
+ 'dist/',
37
+ 'dist-electron/',
38
+ 'src-tauri/target/',
39
+ '.env.local',
40
+ '.env.*.local',
41
+ '.nimi/local/',
42
+ '.turbo/',
43
+ '.vite/',
44
+ '.DS_Store',
45
+ '',
46
+ ].join('\n');
47
+ const MINIMAL_TAURI_ICON_PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR4nGNgAAIAAAUAAXpeqz8AAAAASUVORK5CYII=', 'base64');
48
+ const MINIMAL_TAURI_ICON_ICO = Buffer.from('AAABAAEAAQEAAAEAIABEAAAAFgAAAIlQTkcNChoKAAAADUlIRFIAAAABAAAAAQgGAAAAHxXEiQAAAAtJREFUeJxjYAACAAAFAAF6Xqs/AAAAAElFTkSuQmCC', 'base64');
49
+
50
+ const APP_RELEASE_WORKFLOW = [
51
+ 'name: nimi-app-release',
52
+ 'on:',
53
+ ' pull_request:',
54
+ ' push:',
55
+ ' tags:',
56
+ " - 'v*'",
57
+ ' workflow_dispatch: {}',
58
+ 'permissions:',
59
+ ' contents: read',
60
+ 'jobs:',
61
+ ' prepare:',
62
+ ' runs-on: ubuntu-latest',
63
+ ' outputs:',
64
+ ' matrix: ${{ steps.matrix.outputs.matrix }}',
65
+ ' steps:',
66
+ ' - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2',
67
+ ' with:',
68
+ ' fetch-depth: 0',
69
+ ' persist-credentials: false',
70
+ ' - uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0',
71
+ ' with:',
72
+ ' node-version: 24',
73
+ ' package-manager-cache: false',
74
+ ' - run: corepack enable',
75
+ ' - run: pnpm install --frozen-lockfile',
76
+ ' - run: pnpm exec nimi-app sync',
77
+ ' - run: test -z "$(git status --porcelain)"',
78
+ ' - run: pnpm exec nimi-app check --json > .nimi-targets.json',
79
+ ' - run: pnpm exec nimi-app test',
80
+ ' - name: Require tag/version lockstep',
81
+ " if: github.event_name == 'push' && github.ref_type == 'tag'",
82
+ ' run: node -e "const p=require(\'./package.json\'); if (process.env.GITHUB_REF_NAME !== `v${p.version}`) throw new Error(\'tag_version_mismatch\')"',
83
+ ' - name: Require annotated tag bound to this commit',
84
+ " if: github.event_name == 'push' && github.ref_type == 'tag'",
85
+ ' shell: bash',
86
+ ' run: |',
87
+ ' test "$(git cat-file -t "refs/tags/$GITHUB_REF_NAME")" = tag',
88
+ ' test "$(git rev-parse "refs/tags/$GITHUB_REF_NAME^{}")" = "$GITHUB_SHA"',
89
+ ' - name: Require tagged commit on canonical default branch',
90
+ " if: github.event_name == 'push' && github.ref_type == 'tag'",
91
+ ' env:',
92
+ ' NIMI_APP_CANONICAL_BRANCH: ${{ github.event.repository.default_branch }}',
93
+ ' shell: bash',
94
+ ' run: |',
95
+ ' test -n "$NIMI_APP_CANONICAL_BRANCH"',
96
+ ' git fetch --no-tags origin "refs/heads/$NIMI_APP_CANONICAL_BRANCH:refs/remotes/origin/$NIMI_APP_CANONICAL_BRANCH"',
97
+ ' git merge-base --is-ancestor "$GITHUB_SHA" "refs/remotes/origin/$NIMI_APP_CANONICAL_BRANCH"',
98
+ ' - name: Run production release preflight',
99
+ " if: github.event_name == 'push' && github.ref_type == 'tag'",
100
+ ' run: pnpm exec nimi-app check --production',
101
+ ' - name: Require protected tags and immutable releases',
102
+ " if: github.event_name == 'push' && github.ref_type == 'tag'",
103
+ ' env:',
104
+ ' GH_TOKEN: ${{ secrets.GITHUB_REPOSITORY_ADMIN_TOKEN }}',
105
+ ' shell: bash',
106
+ ' run: |',
107
+ ' test -n "$GH_TOKEN"',
108
+ ' test "$(gh api "repos/$GITHUB_REPOSITORY/immutable-releases" --jq .enabled)" = true',
109
+ ' protected=false',
110
+ ' while read -r ruleset_id; do',
111
+ ' ruleset=$(gh api "repos/$GITHUB_REPOSITORY/rulesets/$ruleset_id")',
112
+ ' excluded=false',
113
+ ' while read -r pattern; do',
114
+ ' if [[ "refs/tags/$GITHUB_REF_NAME" == $pattern ]]; then excluded=true; break; fi',
115
+ ' done < <(jq -r \'.conditions.ref_name.exclude[]?\' <<<"$ruleset")',
116
+ ' if test "$excluded" = true; then continue; fi',
117
+ " if jq -e '(.conditions.ref_name.include | index(\"refs/tags/v*\")) != null and ([.rules[].type] | index(\"update\") != null and index(\"deletion\") != null)' <<<\"$ruleset\" >/dev/null; then",
118
+ ' protected=true',
119
+ ' break',
120
+ ' fi',
121
+ ' done < <(gh api "repos/$GITHUB_REPOSITORY/rulesets" --jq \'.[] | select(.target == "tag" and .enforcement == "active") | .id\')',
122
+ ' test "$protected" = true',
123
+ ' - name: Resolve declared target matrix',
124
+ ' id: matrix',
125
+ ' shell: bash',
126
+ ' run: |',
127
+ " matrix=$(jq -c '{include: [.targets[] | {target: ., runner: (if . == \"windows-x86_64\" then \"windows-latest\" else error(\"unsupported target\") end)}]}' .nimi-targets.json)",
128
+ ' test "$(jq \'.include | length\' <<<"$matrix")" -gt 0',
129
+ ' echo "matrix=$matrix" >> "$GITHUB_OUTPUT"',
130
+ ' build-target:',
131
+ ' needs: prepare',
132
+ ' runs-on: ${{ matrix.runner }}',
133
+ ' permissions:',
134
+ ' contents: read',
135
+ ' strategy:',
136
+ ' fail-fast: false',
137
+ ' matrix: ${{ fromJSON(needs.prepare.outputs.matrix) }}',
138
+ ' steps:',
139
+ ' - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2',
140
+ ' with:',
141
+ ' persist-credentials: false',
142
+ ' - uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0',
143
+ ' with:',
144
+ ' node-version: 24',
145
+ ' package-manager-cache: false',
146
+ ' - run: corepack enable',
147
+ ' - run: pnpm install --frozen-lockfile',
148
+ ' - name: Build development target',
149
+ " if: github.event_name != 'push' || github.ref_type != 'tag'",
150
+ ' env:',
151
+ ' NIMI_APP_TARGET: ${{ matrix.target }}',
152
+ ' shell: pwsh',
153
+ ' run: pnpm exec nimi-app build --target $env:NIMI_APP_TARGET',
154
+ ' - name: Build and sign production target',
155
+ " if: github.event_name == 'push' && github.ref_type == 'tag'",
156
+ ' env:',
157
+ ' NIMI_APP_TARGET: ${{ matrix.target }}',
158
+ ' NIMI_APP_PRODUCTION: true',
159
+ ' WINDOWS_CERTIFICATE_BASE64: ${{ secrets.WINDOWS_CERTIFICATE_BASE64 }}',
160
+ ' WINDOWS_CERTIFICATE_PASSWORD: ${{ secrets.WINDOWS_CERTIFICATE_PASSWORD }}',
161
+ ' shell: pwsh',
162
+ ' run: pnpm exec nimi-app build --target $env:NIMI_APP_TARGET --production',
163
+ ' - name: Require build to preserve the tracked source tree',
164
+ ' shell: bash',
165
+ ' run: test -z "$(git status --porcelain)"',
166
+ ' - name: Pack development target',
167
+ " if: github.event_name != 'push' || github.ref_type != 'tag'",
168
+ ' env:',
169
+ ' NIMI_APP_TARGET: ${{ matrix.target }}',
170
+ ' shell: pwsh',
171
+ ' run: pnpm exec nimi-app pack --target $env:NIMI_APP_TARGET',
172
+ ' - name: Verify native trust and pack production target',
173
+ " if: github.event_name == 'push' && github.ref_type == 'tag'",
174
+ ' env:',
175
+ ' NIMI_APP_TARGET: ${{ matrix.target }}',
176
+ ' shell: pwsh',
177
+ ' run: pnpm exec nimi-app pack --target $env:NIMI_APP_TARGET --production',
178
+ ' - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1',
179
+ ' with:',
180
+ ' name: nimi-app-${{ matrix.target }}',
181
+ ' path: |',
182
+ ' dist/nimi-app/*.nimiapp',
183
+ ' dist/nimi-app/*.target.json',
184
+ ' if-no-files-found: error',
185
+ ' attest-target:',
186
+ " if: github.event_name == 'push' && github.ref_type == 'tag'",
187
+ ' needs: [prepare, build-target]',
188
+ ' runs-on: ubuntu-latest',
189
+ ' permissions:',
190
+ ' contents: read',
191
+ ' id-token: write',
192
+ ' attestations: write',
193
+ ' artifact-metadata: write',
194
+ ' strategy:',
195
+ ' fail-fast: false',
196
+ ' matrix: ${{ fromJSON(needs.prepare.outputs.matrix) }}',
197
+ ' steps:',
198
+ ' - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1',
199
+ ' with:',
200
+ ' name: nimi-app-${{ matrix.target }}',
201
+ ' path: attest-assets',
202
+ ' - uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2',
203
+ ' with:',
204
+ ' subject-path: attest-assets/*.nimiapp',
205
+ ' aggregate:',
206
+ ' needs: build-target',
207
+ ' runs-on: ubuntu-latest',
208
+ ' steps:',
209
+ ' - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2',
210
+ ' with:',
211
+ ' persist-credentials: false',
212
+ ' - uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0',
213
+ ' with:',
214
+ ' node-version: 24',
215
+ ' package-manager-cache: false',
216
+ ' - run: corepack enable',
217
+ ' - run: pnpm install --frozen-lockfile',
218
+ ' - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1',
219
+ ' with:',
220
+ ' pattern: nimi-app-*',
221
+ ' path: dist/nimi-app',
222
+ ' merge-multiple: true',
223
+ ' - run: pnpm exec nimi-app pack --aggregate',
224
+ ' - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1',
225
+ ' with:',
226
+ ' name: nimi-app-release-candidate',
227
+ ' path: |',
228
+ ' dist/nimi-app/*.nimiapp',
229
+ ' dist/nimi-app/*.target.json',
230
+ ' dist/nimi-app/*.candidate.json',
231
+ ' if-no-files-found: error',
232
+ ' release:',
233
+ " if: github.event_name == 'push' && github.ref_type == 'tag'",
234
+ ' needs: [aggregate, attest-target]',
235
+ ' runs-on: ubuntu-latest',
236
+ ' permissions:',
237
+ ' contents: write',
238
+ ' steps:',
239
+ ' - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1',
240
+ ' with:',
241
+ ' name: nimi-app-release-candidate',
242
+ ' path: release-assets',
243
+ ' - name: Publish the immutable GitHub Release set',
244
+ ' env:',
245
+ ' GH_TOKEN: ${{ github.token }}',
246
+ ' shell: bash',
247
+ ' run: |',
248
+ ' set -euo pipefail',
249
+ ' shopt -s nullglob',
250
+ ' assets=(release-assets/*.nimiapp release-assets/*.candidate.json)',
251
+ ' test "${#assets[@]}" -gt 0',
252
+ " expected=$(printf '%s\\n' \"${assets[@]##*/}\" | jq -R -s -c 'split(\"\\n\")[:-1] | sort')",
253
+ ' if release_json=$(gh api "repos/$GITHUB_REPOSITORY/releases/tags/$GITHUB_REF_NAME" 2>/dev/null); then',
254
+ ' existing=$(jq -c \'.assets | map(.name) | sort\' <<<"$release_json")',
255
+ " unexpected=$(jq -n --argjson existing \"$existing\" --argjson expected \"$expected\" '$existing - $expected | length')",
256
+ ' test "$unexpected" -eq 0',
257
+ ' if test "$(jq -r .draft <<<"$release_json")" = false; then',
258
+ ' test "$existing" = "$expected"',
259
+ ' gh release verify "$GITHUB_REF_NAME" --repo "$GITHUB_REPOSITORY"',
260
+ ' for asset in "${assets[@]}"; do gh release verify-asset "$GITHUB_REF_NAME" "$asset" --repo "$GITHUB_REPOSITORY"; done',
261
+ ' exit 0',
262
+ ' fi',
263
+ ' else',
264
+ ' gh release create "$GITHUB_REF_NAME" --repo "$GITHUB_REPOSITORY" --draft --verify-tag --title "$GITHUB_REF_NAME" --notes-from-tag',
265
+ ' release_json=$(gh api "repos/$GITHUB_REPOSITORY/releases/tags/$GITHUB_REF_NAME")',
266
+ ' fi',
267
+ ' verify_dir=$(mktemp -d)',
268
+ ' for asset in "${assets[@]}"; do',
269
+ ' name=$(basename "$asset")',
270
+ ' if jq -e --arg name "$name" \'.assets[] | select(.name == $name)\' <<<"$release_json" >/dev/null; then',
271
+ ' gh release download "$GITHUB_REF_NAME" --repo "$GITHUB_REPOSITORY" --pattern "$name" --dir "$verify_dir"',
272
+ ' cmp "$asset" "$verify_dir/$name"',
273
+ ' else',
274
+ ' gh release upload "$GITHUB_REF_NAME" "$asset" --repo "$GITHUB_REPOSITORY"',
275
+ ' fi',
276
+ ' done',
277
+ ' gh release edit "$GITHUB_REF_NAME" --repo "$GITHUB_REPOSITORY" --draft=false',
278
+ ' gh release verify "$GITHUB_REF_NAME" --repo "$GITHUB_REPOSITORY"',
279
+ ' for asset in "${assets[@]}"; do gh release verify-asset "$GITHUB_REF_NAME" "$asset" --repo "$GITHUB_REPOSITORY"; done',
280
+ '',
281
+ ].join('\n');
282
+
283
+ const appSourceCache = new Map();
284
+
285
+ function loadAppSource(resolvedModuleIds = []) {
286
+ const cacheKey = resolvedModuleIds.join('\0');
287
+ if (!appSourceCache.has(cacheKey)) {
288
+ appSourceCache.set(cacheKey, resolveAppSource({ resolvedModuleIds }));
289
+ }
290
+ return appSourceCache.get(cacheKey);
291
+ }
15
292
 
16
293
  function jsonFile(value) {
17
294
  return `${JSON.stringify(value, null, 2)}\n`;
18
295
  }
19
296
 
297
+ function sortedJsonValue(value) {
298
+ if (Array.isArray(value)) return value.map(sortedJsonValue);
299
+ if (!value || typeof value !== 'object') return value;
300
+ return Object.fromEntries(
301
+ Object.keys(value).sort().map((key) => [key, sortedJsonValue(value[key])]),
302
+ );
303
+ }
304
+
305
+ function canonicalJson(value) {
306
+ return JSON.stringify(sortedJsonValue(value));
307
+ }
308
+
20
309
  function slugify(input) {
21
310
  const normalized = String(input || DEFAULT_APP_ID)
22
311
  .trim()
@@ -27,20 +316,29 @@ function slugify(input) {
27
316
  }
28
317
 
29
318
  function normalizeExplicitAppId(input) {
30
- const normalized = String(input || '')
31
- .trim()
32
- .toLowerCase();
33
- if (!/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/.test(normalized)) {
319
+ const raw = String(input || '');
320
+ if (raw !== raw.trim() || raw !== raw.toLowerCase()) {
34
321
  throw new Error(`Invalid app id: ${input}`);
35
322
  }
36
- return normalized;
323
+ if (!/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/.test(raw)) {
324
+ throw new Error(`Invalid app id: ${input}`);
325
+ }
326
+ return raw;
327
+ }
328
+
329
+ function normalizeAppVersion(input) {
330
+ const value = String(input || DEFAULT_APP_VERSION);
331
+ if (value !== value.trim() || !SEMVER_PATTERN.test(value)) {
332
+ throw new Error(`Invalid initial App version: ${input}`);
333
+ }
334
+ return value;
37
335
  }
38
336
 
39
337
  function resolveAppId(options) {
40
338
  if (String(options.appId || '').trim()) {
41
339
  return normalizeExplicitAppId(options.appId);
42
340
  }
43
- return slugify(options.name || DEFAULT_APP_ID);
341
+ return DEFAULT_APP_ID;
44
342
  }
45
343
 
46
344
  function packageSafeName(input) {
@@ -57,7 +355,11 @@ function validateNpmPackageSegment(segment) {
57
355
  }
58
356
 
59
357
  function normalizeExplicitPackageName(input) {
60
- const normalized = String(input || '').trim();
358
+ const raw = String(input || '');
359
+ const normalized = raw.trim();
360
+ if (raw !== normalized) {
361
+ throw new Error(`Invalid npm package name: ${input}`);
362
+ }
61
363
  if (!normalized || normalized.length > 214 || /\s/.test(normalized)) {
62
364
  throw new Error(`Invalid npm package name: ${input}`);
63
365
  }
@@ -92,26 +394,93 @@ function cargoSafeNameFromPackageName(input) {
92
394
  return normalized || DEFAULT_APP_ID;
93
395
  }
94
396
 
397
+ function appSlugFromAppId(appId) {
398
+ return packageSafeName(appId);
399
+ }
400
+
95
401
  function tauriIdentifierFromAppId(appId) {
96
402
  const suffix = String(appId || DEFAULT_APP_ID)
97
403
  .toLowerCase()
98
- .replace(/[^a-z0-9]+/g, '.')
404
+ .replace(/[^a-z0-9.-]+/g, '.')
99
405
  .replace(/^\.+|\.+$/g, '')
100
406
  .replace(/\.+/g, '.');
101
- return `ai.nimi.apps.${suffix || DEFAULT_APP_ID.replace(/-/g, '.')}`;
407
+ return `ai.nimi.apps.${suffix || DEFAULT_APP_ID}`;
408
+ }
409
+
410
+ function normalizeDisplayName(input) {
411
+ const value = String(input ?? '');
412
+ if (!value.trim() || value.length > 160 || /[\0\r\n]/.test(value)) {
413
+ throw new Error('Display Name must be non-empty, at most 160 characters, and one line');
414
+ }
415
+ return value;
102
416
  }
103
417
 
104
- function buildAppIdentity(profile, appId, appTitle, packageName, author = '') {
418
+ function normalizeAuthor(input) {
419
+ const value = String(input ?? '');
420
+ if (!value) return '';
421
+ if (!value.trim() || value.length > 214 || /[\0\r\n]/.test(value)) {
422
+ throw new Error('Author must be at most 214 characters and one line');
423
+ }
424
+ return value;
425
+ }
426
+
427
+ function assertNonLabIdentity(identity) {
428
+ const normalizedTitle = identity.appTitle.trim().toLowerCase();
429
+ const reserved = [
430
+ identity.appId === 'nimi.lab',
431
+ normalizedTitle === 'nimi lab',
432
+ identity.packageName === '@nimiplatform/lab',
433
+ identity.tauriIdentifier === 'ai.nimi.apps.nimi.lab',
434
+ identity.cargoPackageName === 'nimiapp-lab-shell',
435
+ identity.appSlug === 'nimi-lab',
436
+ ];
437
+ if (reserved.some(Boolean)) {
438
+ throw new Error('Nimi Lab canonical identity is reserved and cannot be scaffolded');
439
+ }
440
+ }
441
+
442
+ function deriveScaffoldDevPort(appId) {
443
+ let hash = 0;
444
+ for (const char of String(appId || DEFAULT_APP_ID)) {
445
+ hash = (hash * 31 + char.charCodeAt(0)) % 100;
446
+ }
447
+ return 1430 + hash;
448
+ }
449
+
450
+ function buildAppIdentity(
451
+ profile,
452
+ appId,
453
+ appTitle,
454
+ version,
455
+ packageName,
456
+ author = '',
457
+ accentPack = 'nimi-accent',
458
+ features = undefined,
459
+ featureResolver = resolveAppScaffoldFeatures,
460
+ ) {
105
461
  const resolvedPackageName = packageName || packageSafeName(appId);
106
- return {
462
+ const capabilityResolution = featureResolver(features);
463
+ const identity = {
107
464
  appId,
108
465
  appTitle,
466
+ version: normalizeAppVersion(version),
109
467
  profile,
110
468
  packageName: resolvedPackageName,
111
469
  cargoPackageName: `${cargoSafeNameFromPackageName(resolvedPackageName)}-shell`,
112
470
  tauriIdentifier: tauriIdentifierFromAppId(appId),
113
- author: String(author || '').trim(),
471
+ nativeBundleIdentifier: tauriIdentifierFromAppId(appId),
472
+ appSlug: appSlugFromAppId(appId),
473
+ rendererEntryId: `${appSlugFromAppId(appId)}-app`,
474
+ accentPack: String(accentPack || '').trim() || 'nimi-accent',
475
+ features: capabilityResolution.resolvedFeatureIds,
476
+ appAccessItems: normalizeAppAccessItems(capabilityResolution.appAccessItems),
477
+ capabilityResolution,
478
+ devPort: deriveScaffoldDevPort(appId),
479
+ appOwnedNamespace: appId,
480
+ author: normalizeAuthor(author),
114
481
  };
482
+ assertNonLabIdentity(identity);
483
+ return identity;
115
484
  }
116
485
 
117
486
  function resolveProfile(options) {
@@ -122,46 +491,102 @@ function resolveProfile(options) {
122
491
  return profile;
123
492
  }
124
493
 
494
+ function resolveAppScaffoldCreateInputWithResolver(
495
+ { cwd, options = {} },
496
+ featureResolver,
497
+ ) {
498
+ const profile = resolveProfile(options);
499
+ const appId = resolveAppId(options);
500
+ const appTitle = normalizeDisplayName(options.title || options.name || DEFAULT_APP_TITLE);
501
+ const version = normalizeAppVersion(options.version);
502
+ const packageName = resolvePackageName(options, appId);
503
+ const author = normalizeAuthor(options.author || '');
504
+ const targetDir = path.resolve(cwd, String(options.dir || '').trim() || appId);
505
+ const identity = buildAppIdentity(
506
+ profile,
507
+ appId,
508
+ appTitle,
509
+ version,
510
+ packageName,
511
+ author,
512
+ options.accentPack,
513
+ options.features,
514
+ featureResolver,
515
+ );
516
+ return Object.freeze({
517
+ profile,
518
+ appId,
519
+ appTitle,
520
+ version,
521
+ packageName,
522
+ author,
523
+ accentPack: identity.accentPack,
524
+ directFeatures: identity.capabilityResolution.directFeatureIds,
525
+ resolvedModules: identity.capabilityResolution.resolvedModuleIds,
526
+ features: identity.features,
527
+ targetDir,
528
+ });
529
+ }
530
+
531
+ export function resolveAppScaffoldCreateInput(input) {
532
+ return resolveAppScaffoldCreateInputWithResolver(input, resolveAppScaffoldFeatures);
533
+ }
534
+
535
+ export function resolveAppScaffoldCandidateCreateInput(input) {
536
+ return resolveAppScaffoldCreateInputWithResolver(input, resolveAppScaffoldCandidateFeatures);
537
+ }
538
+
125
539
  function buildPackageJson(profile, versions, identity) {
540
+ const dependencies = buildRuntimeDependencies(profile, versions, identity.capabilityResolution);
541
+ const devDependencies = {
542
+ '@nimiplatform/app-tools': versions.appToolsVersion,
543
+ '@nimiplatform/nimi-coding': versions.nimicodingVersion,
544
+ '@tailwindcss/vite': versions.tailwindcssViteVersion,
545
+ '@tauri-apps/cli': versions.tauriCliVersion,
546
+ '@types/node': versions.nodeTypesVersion,
547
+ '@types/react': versions.reactTypesVersion,
548
+ '@types/react-dom': versions.reactDomTypesVersion,
549
+ '@vitejs/plugin-react': versions.viteReactPluginVersion,
550
+ electron: versions.electronVersion,
551
+ esbuild: versions.esbuildVersion,
552
+ tailwindcss: versions.tailwindcssVersion,
553
+ typescript: versions.typescriptVersion,
554
+ vite: versions.viteVersion,
555
+ yaml: versions.yamlVersion,
556
+ };
557
+ for (const [name, version] of Object.entries(devDependencies)) {
558
+ validateAppScaffoldNpmRegistryVersion(version, name);
559
+ }
126
560
  const packageJson = {
127
561
  name: identity.packageName,
128
- private: false,
562
+ version: identity.version,
563
+ private: true,
129
564
  type: 'module',
130
- publishConfig: {
131
- access: 'public',
565
+ packageManager: versions.packageManager,
566
+ pnpm: {
567
+ onlyBuiltDependencies: ['electron', 'esbuild', 'protobufjs'],
132
568
  },
133
569
  scripts: {
134
- dev: 'pnpm run dev:renderer',
135
- 'dev:renderer': 'vite --host 127.0.0.1 --port 1420 --strictPort',
136
- 'dev:shell': 'tauri dev',
570
+ dev: 'nimi-app dev --shell electron',
571
+ 'dev:renderer': `vite --host 127.0.0.1 --port ${identity.devPort} --strictPort`,
572
+ 'dev:shell': 'nimi-app dev',
573
+ 'dev:electron': 'nimi-app dev --shell electron',
574
+ init: 'nimi-app init',
575
+ sync: 'nimi-app sync',
576
+ check: 'nimi-app check',
577
+ test: 'nimi-app test',
578
+ 'test:app': 'node --test test/*.test.mjs',
579
+ 'app:build': 'nimi-app build',
580
+ pack: 'nimi-app pack',
137
581
  typecheck: 'tsc --noEmit',
138
582
  build: 'tsc --noEmit && vite build',
583
+ 'build:electron': 'tsc -p tsconfig.electron.json && node scripts/bundle-electron-preload.mjs',
139
584
  'build:shell': 'tauri build',
140
- test: 'node --test test/*.test.mjs',
141
- check: 'pnpm run doctor && pnpm run test && pnpm run validate',
142
- pack: 'pnpm run build && node scripts/pack.mjs',
585
+ postinstall: 'install-electron --no',
143
586
  validate: 'node scripts/validate.mjs',
144
- 'local-audit': 'node scripts/local-audit.mjs',
145
- doctor: 'nimi-app doctor',
146
- update: 'nimi-app update',
147
- },
148
- dependencies: {
149
- '@nimiplatform/sdk': profile === 'workspace-app' ? 'workspace:*' : versions.sdkVersion,
150
- '@nimiplatform/kit': profile === 'workspace-app' ? 'workspace:*' : versions.kitVersion,
151
- '@tauri-apps/api': versions.tauriApiVersion,
152
- react: versions.reactVersion,
153
- 'react-dom': versions.reactDomVersion,
154
- },
155
- devDependencies: {
156
- '@nimiplatform/app-tools': profile === 'workspace-app' ? 'workspace:*' : versions.appToolsVersion,
157
- '@tauri-apps/cli': versions.tauriCliVersion,
158
- '@types/node': versions.nodeTypesVersion,
159
- '@types/react': versions.reactTypesVersion,
160
- '@types/react-dom': versions.reactDomTypesVersion,
161
- '@vitejs/plugin-react': versions.viteReactPluginVersion,
162
- typescript: versions.typescriptVersion,
163
- vite: versions.viteVersion,
164
587
  },
588
+ dependencies,
589
+ devDependencies,
165
590
  };
166
591
  if (identity.author) {
167
592
  packageJson.author = identity.author;
@@ -169,797 +594,682 @@ function buildPackageJson(profile, versions, identity) {
169
594
  return packageJson;
170
595
  }
171
596
 
172
- function buildRendererFiles(identity) {
173
- return [
174
- {
175
- path: 'src/main.tsx',
176
- content: [
177
- "import React from 'react';",
178
- "import { createRoot } from 'react-dom/client';",
179
- "import { NimiThemeProvider } from '@nimiplatform/kit/ui';",
180
- "import '@nimiplatform/kit/ui/styles.css';",
181
- "import './styles.css';",
182
- "import { App } from './shell/App.js';",
183
- '',
184
- "createRoot(document.getElementById('root') as HTMLElement).render(",
185
- ' <React.StrictMode>',
186
- ' <NimiThemeProvider accentPack="nimi-accent">',
187
- ' <App />',
188
- ' </NimiThemeProvider>',
189
- ' </React.StrictMode>,',
190
- ');',
191
- '',
192
- ].join('\n'),
193
- },
194
- {
195
- path: 'src/shell/App.tsx',
196
- content: [
197
- "import { RuntimeGate } from './auth/runtime-gate.js';",
198
- "import { AuthGate } from './auth/auth-gate.js';",
199
- "import { ProductArea } from './routes/product-area.js';",
200
- "import { SettingsRoute } from './routes/settings.js';",
201
- "import { DemoSurfaces } from './routes/demo-surfaces.js';",
202
- '',
203
- 'export function App() {',
204
- ' return (',
205
- ' <RuntimeGate>',
206
- ' <AuthGate>',
207
- ' <main className="app-shell">',
208
- ' <ProductArea />',
209
- ' <aside className="side-panel">',
210
- ' <SettingsRoute />',
211
- ' <DemoSurfaces />',
212
- ' </aside>',
213
- ' </main>',
214
- ' </AuthGate>',
215
- ' </RuntimeGate>',
216
- ' );',
217
- '}',
218
- '',
219
- ].join('\n'),
220
- },
221
- {
222
- path: 'src/shell/auth/runtime-platform.ts',
223
- content: [
224
- "import { createNimiAppRuntimePlatformClient, type NimiAppAuthProjection } from '@nimiplatform/sdk';",
225
- '',
226
- `export const appId = '${identity.appId}';`,
227
- `export const scaffoldProfile = '${identity.profile}' as const;`,
228
- '',
229
- 'let runtimeProjection: Promise<NimiAppAuthProjection> | null = null;',
230
- '',
231
- 'export function getRuntimePlatformProjection() {',
232
- ' runtimeProjection ??= createNimiAppRuntimePlatformClient({',
233
- " mode: 'third-party-nimi-app',",
234
- ' appId,',
235
- ' });',
236
- ' return runtimeProjection;',
237
- '}',
238
- '',
239
- ].join('\n'),
240
- },
241
- {
242
- path: 'src/shell/auth/auth-gate.tsx',
243
- content: [
244
- "import { useEffect, useState, type ReactNode } from 'react';",
245
- "import type { NimiAppAuthProjection } from '@nimiplatform/sdk';",
246
- "import { InlineAlert, StatusBadge } from '@nimiplatform/kit/ui';",
247
- "import { getRuntimePlatformProjection } from './runtime-platform.js';",
248
- '',
249
- 'export function AuthGate({ children }: { children: ReactNode }) {',
250
- " const [projection, setProjection] = useState<NimiAppAuthProjection | null>(null);",
251
- ' useEffect(() => {',
252
- ' let active = true;',
253
- ' void getRuntimePlatformProjection().then((nextProjection) => {',
254
- ' if (active) setProjection(nextProjection);',
255
- ' });',
256
- ' return () => {',
257
- ' active = false;',
258
- ' };',
259
- ' }, []);',
260
- '',
261
- ' if (!projection) {',
262
- " return <div className=\"gate-panel\"><StatusBadge tone=\"neutral\">Runtime check</StatusBadge></div>;",
263
- ' }',
264
- '',
265
- " if (projection.status !== 'ready') {",
266
- ' return (',
267
- ' <div className="gate-panel">',
268
- ' <InlineAlert tone="warning">',
269
- ' <strong>Runtime action required</strong>',
270
- ' <span>{projection.message}</span>',
271
- ' </InlineAlert>',
272
- ' </div>',
273
- ' );',
274
- ' }',
275
- '',
276
- ' return <>{children}</>;',
277
- '}',
278
- '',
279
- ].join('\n'),
280
- },
281
- {
282
- path: 'src/shell/auth/runtime-gate.tsx',
283
- content: [
284
- "import type { ReactNode } from 'react';",
285
- "import { StatusBadge } from '@nimiplatform/kit/ui';",
286
- '',
287
- 'export function RuntimeGate({ children }: { children: ReactNode }) {',
288
- ' return (',
289
- ' <section className="runtime-frame" aria-label="Runtime readiness gate">',
290
- ' <header className="runtime-frame__header">',
291
- ` <strong>${identity.appTitle}</strong>`,
292
- ' <StatusBadge tone="neutral">pre-submission self-check</StatusBadge>',
293
- ' </header>',
294
- ' {children}',
295
- ' </section>',
296
- ' );',
297
- '}',
298
- '',
299
- ].join('\n'),
300
- },
301
- {
302
- path: 'src/shell/routes/product-area.tsx',
303
- content: [
304
- "import { Button, Surface } from '@nimiplatform/kit/ui';",
305
- '',
306
- 'export function ProductArea() {',
307
- ' return (',
308
- ' <Surface className="product-area">',
309
- ' <p className="eyebrow">app-owned product route</p>',
310
- ` <h1>${identity.appTitle}</h1>`,
311
- ' <p>Replace this route with app product behavior while keeping auth, Runtime, and permission boundaries in scaffold-managed glue.</p>',
312
- ' <Button type="button">Open product action</Button>',
313
- ' </Surface>',
314
- ' );',
315
- '}',
316
- '',
317
- ].join('\n'),
318
- },
319
- {
320
- path: 'src/shell/routes/settings.tsx',
321
- content: [
322
- "import { Surface, Toggle } from '@nimiplatform/kit/ui';",
323
- '',
324
- 'export function SettingsRoute() {',
325
- ' return (',
326
- ' <Surface className="panel-section">',
327
- ' <h2>Settings</h2>',
328
- ' <label className="setting-row">',
329
- ' <span>Use local draft data</span>',
330
- ' <Toggle checked={false} onChange={() => {}} />',
331
- ' </label>',
332
- ' </Surface>',
333
- ' );',
334
- '}',
335
- '',
336
- ].join('\n'),
337
- },
338
- {
339
- path: 'src/shell/routes/demo-surfaces.tsx',
340
- content: [
341
- "import { EmptyState, Surface } from '@nimiplatform/kit/ui';",
342
- '',
343
- 'export function DemoSurfaces() {',
344
- ' return (',
345
- ' <Surface className="panel-section">',
346
- ' <h2>Demo</h2>',
347
- ' <EmptyState title="Add app-owned surfaces" description="Use reviewed SDK and kit imports only." />',
348
- ' </Surface>',
349
- ' );',
350
- '}',
351
- '',
352
- ].join('\n'),
353
- },
354
- {
355
- path: 'src/styles.css',
356
- content: [
357
- ':root {',
358
- ' color-scheme: light;',
359
- ' font-family: Inter, ui-sans-serif, system-ui, sans-serif;',
360
- '}',
361
- '',
362
- 'body {',
363
- ' margin: 0;',
364
- ' background: #f6f7f9;',
365
- ' color: #20242c;',
366
- '}',
367
- '',
368
- '.runtime-frame {',
369
- ' min-height: 100vh;',
370
- ' padding: 24px;',
371
- '}',
372
- '',
373
- '.runtime-frame__header, .app-shell {',
374
- ' display: grid;',
375
- ' gap: 16px;',
376
- '}',
377
- '',
378
- '.runtime-frame__header {',
379
- ' grid: auto / 1fr auto;',
380
- ' align-items: center;',
381
- ' margin-bottom: 16px;',
382
- '}',
383
- '',
384
- '.app-shell {',
385
- ' grid: auto / minmax(0, 1fr) minmax(280px, 360px);',
386
- '}',
387
- '',
388
- '.product-area, .panel-section, .gate-panel {',
389
- ' padding: 20px;',
390
- '}',
391
- '',
392
- '.side-panel {',
393
- ' display: grid;',
394
- ' align-content: start;',
395
- ' gap: 16px;',
396
- '}',
397
- '',
398
- '.eyebrow {',
399
- ' margin: 0 0 8px;',
400
- ' color: #5b6472;',
401
- ' font-size: 12px;',
402
- ' text-transform: uppercase;',
403
- '}',
404
- '',
405
- '.setting-row {',
406
- ' display: flex;',
407
- ' align-items: center;',
408
- ' justify-content: space-between;',
409
- ' gap: 12px;',
410
- '}',
411
- '',
412
- '@media (max-width: 820px) {',
413
- ' .app-shell, .runtime-frame__header {',
414
- ' grid: auto / 1fr;',
415
- ' }',
416
- '}',
417
- '',
418
- ].join('\n'),
419
- },
597
+ function buildRuntimeDependencies(profile, versions, capabilityResolution) {
598
+ const dependencies = {
599
+ '@nimiplatform/sdk': versions.sdkVersion,
600
+ '@nimiplatform/kit': versions.kitVersion,
601
+ react: versions.reactVersion,
602
+ 'react-dom': versions.reactDomVersion,
603
+ };
604
+ for (const [name, version] of Object.entries(dependencies)) {
605
+ validateAppScaffoldNpmRegistryVersion(version, name);
606
+ }
607
+ for (const [name, version] of Object.entries(capabilityResolution.npmDependencies)) {
608
+ const resolvedVersion = resolveScaffoldVersionReference(version, versions, name);
609
+ if (Object.hasOwn(dependencies, name) && dependencies[name] !== resolvedVersion) {
610
+ throw new Error(`App scaffold base/module dependency version collision for ${name}`);
611
+ }
612
+ dependencies[name] = resolvedVersion;
613
+ }
614
+ return dependencies;
615
+ }
616
+
617
+ function resolveScaffoldVersionReference(value, versions, dependencyName) {
618
+ if (typeof value !== 'string') throw new Error(`Invalid npm dependency version for ${dependencyName}`);
619
+ const match = value.match(/^\$versions\.([A-Za-z][A-Za-z0-9]*)$/u);
620
+ const resolved = match ? versions[match[1]] : value;
621
+ if (typeof resolved !== 'string' || !resolved.trim()) {
622
+ throw new Error(`Missing scaffold version source for ${dependencyName}: ${match?.[1] ?? 'inline'}`);
623
+ }
624
+ validateAppScaffoldNpmRegistryVersion(resolved, dependencyName);
625
+ return resolved;
626
+ }
627
+
628
+ function buildCargoDependencies(profile, versions, capabilityResolution) {
629
+ const dependencies = {
630
+ 'nimi-shell-tauri': versions.nimiShellTauriVersion,
631
+ tauri: { version: '2', features: [] },
632
+ serde: { version: '1', features: ['derive'] },
633
+ serde_json: '1',
634
+ url: '2',
635
+ base64: '0.22',
636
+ dirs: '6',
637
+ time: '=0.3.47',
638
+ 'tauri-build': { version: '2', features: [] },
639
+ };
640
+ for (const [name, value] of Object.entries(capabilityResolution.cargoDependencies || {})) {
641
+ if (Object.hasOwn(dependencies, name) && canonicalJson(dependencies[name]) !== canonicalJson(value)) {
642
+ throw new Error(`App scaffold base/module Cargo dependency collision for ${name}`);
643
+ }
644
+ dependencies[name] = value;
645
+ }
646
+ for (const [name, value] of Object.entries(dependencies)) {
647
+ validateAppScaffoldCargoDependencyValue(value, name);
648
+ }
649
+ return dependencies;
650
+ }
651
+
652
+ function cargoShellDependencyLine(profile, versions) {
653
+ return `nimi-shell-tauri = ${renderCargoDependencyValue(versions.nimiShellTauriVersion, 'nimi-shell-tauri')}`;
654
+ }
655
+
656
+ export function renderCargoDependencyValue(value, label) {
657
+ validateAppScaffoldCargoDependencyValue(value, label);
658
+ if (typeof value === 'string' && value.trim() === value && value) {
659
+ return JSON.stringify(value);
660
+ }
661
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
662
+ throw new Error(`Invalid Cargo dependency descriptor: ${label}`);
663
+ }
664
+ const fields = [];
665
+ for (const key of Object.keys(value).sort()) {
666
+ const field = value[key];
667
+ if (typeof field === 'string' && field.trim() === field && field) {
668
+ fields.push(`${key} = ${JSON.stringify(field)}`);
669
+ continue;
670
+ }
671
+ if (typeof field === 'boolean') {
672
+ fields.push(`${key} = ${field ? 'true' : 'false'}`);
673
+ continue;
674
+ }
675
+ if (Array.isArray(field) && field.every((item) => typeof item === 'string' && item.trim() === item && item)) {
676
+ fields.push(`${key} = [${field.map((item) => JSON.stringify(item)).join(', ')}]`);
677
+ continue;
678
+ }
679
+ throw new Error(`Invalid Cargo dependency value: ${label}.${key}`);
680
+ }
681
+ if (fields.length === 0) throw new Error(`Invalid empty Cargo dependency descriptor: ${label}`);
682
+ return `{ ${fields.join(', ')} }`;
683
+ }
684
+
685
+ function renderCargoManifest(content, profile, versions, identity) {
686
+ let rendered = content.replace(
687
+ /^nimi-shell-tauri\s*=.*$/m,
688
+ cargoShellDependencyLine(profile, versions),
689
+ );
690
+ rendered = rendered.replace(
691
+ /^(\[package\][\s\S]*?^version\s*=\s*)"[^"]+"/m,
692
+ `$1${JSON.stringify(identity.version)}`,
693
+ );
694
+ const baseNames = new Set([
695
+ 'tauri',
696
+ 'nimi-shell-tauri',
697
+ 'serde',
698
+ 'serde_json',
699
+ 'url',
700
+ 'base64',
701
+ 'dirs',
702
+ 'time',
703
+ 'tauri-build',
704
+ ]);
705
+ const additions = [];
706
+ for (const [name, value] of Object.entries(identity.capabilityResolution.cargoDependencies || {})) {
707
+ if (!/^[A-Za-z0-9_-]+$/u.test(name)) throw new Error(`Invalid Cargo dependency name: ${name}`);
708
+ if (baseNames.has(name)) continue;
709
+ additions.push(`${name} = ${renderCargoDependencyValue(value, name)}`);
710
+ }
711
+ if (additions.length === 0) return rendered;
712
+ const marker = '\n[build-dependencies]';
713
+ if (!rendered.includes(marker)) throw new Error('Generated Cargo manifest is missing [build-dependencies]');
714
+ rendered = rendered.replace(marker, `\n${additions.join('\n')}\n${marker}`);
715
+ return rendered;
716
+ }
717
+
718
+ function targetIdentityMap(identity) {
719
+ return {
720
+ tauriIdentifier: identity.tauriIdentifier,
721
+ packageName: identity.packageName,
722
+ cargoPackageName: identity.cargoPackageName,
723
+ appId: identity.appId,
724
+ appTitle: identity.appTitle,
725
+ appVersion: identity.version,
726
+ appSlug: identity.appSlug,
727
+ rendererEntryId: identity.rendererEntryId,
728
+ accentPack: identity.accentPack,
729
+ devPort: String(identity.devPort),
730
+ };
731
+ }
732
+
733
+ function applyIdentityReplacement(content, manifest, target) {
734
+ const replacements = new Map();
735
+ for (const field of manifest.identityReplacementOrder) {
736
+ if (field === 'rendererEntryId') {
737
+ continue;
738
+ }
739
+ const from = manifest.sourceIdentity[field];
740
+ const to = target[field];
741
+ if (from === undefined || to === undefined) {
742
+ throw new Error(`Identity replacement field missing: ${field}`);
743
+ }
744
+ // The starter intentionally shares some literals (for example packageName
745
+ // and appSlug). The manifest order owns that ambiguity; replacement stays
746
+ // single-pass so the selected target value is never processed again.
747
+ if (replacements.has(from)) continue;
748
+ replacements.set(from, to);
749
+ }
750
+ const sourceEntryId = manifest.sourceIdentity.rendererEntryId;
751
+ const targetEntryId = target.rendererEntryId;
752
+ if (sourceEntryId && targetEntryId) {
753
+ replacements.set(`entry:${sourceEntryId}`, `entry:${targetEntryId}`);
754
+ }
755
+ const pattern = [...replacements.keys()]
756
+ .sort((left, right) => right.length - left.length || left.localeCompare(right))
757
+ .map((value) => value.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&'))
758
+ .join('|');
759
+ if (!pattern) return content;
760
+ return content.replace(new RegExp(pattern, 'gu'), (value) => replacements.get(value));
761
+ }
762
+
763
+ export function assertIdentityNeutralProductSource(relativePath, content, manifest) {
764
+ const forbidden = [
765
+ 'tauriIdentifier',
766
+ 'packageName',
767
+ 'cargoPackageName',
768
+ 'appId',
769
+ 'appTitle',
770
+ 'appSlug',
771
+ 'rendererEntryId',
420
772
  ];
773
+ for (const field of forbidden) {
774
+ const value = manifest.sourceIdentity?.[field];
775
+ if (typeof value === 'string' && value && content.includes(value)) {
776
+ throw new Error(`Scaffold product source contains reserved Lab identity: ${relativePath}: ${field}`);
777
+ }
778
+ }
779
+ if (/\bLab-only\b/u.test(content)) {
780
+ throw new Error(`Scaffold product source contains a Lab-only marker: ${relativePath}`);
781
+ }
421
782
  }
422
783
 
423
- function buildCommonFiles(identity, versions) {
784
+ function relativeModuleSpecifier(fromFile, toFile) {
785
+ const relative = path.posix.relative(path.posix.dirname(fromFile), toFile);
786
+ return relative.startsWith('.') ? relative : `./${relative}`;
787
+ }
788
+
789
+ export function rewriteMappedModuleSpecifiers(content, sourcePath, outputPath, mappings) {
790
+ if (!/\.[cm]?[jt]sx?$/u.test(sourcePath)) return content;
791
+ const pattern = /(\b(?:from|import)\s*(?:\(\s*)?)(['"])(\.\.?\/[^'"]+)\2(\s*\)?)/gu;
792
+ return content.replace(pattern, (whole, prefix, quote, specifier, suffix) => {
793
+ const resolvedSource = path.posix.normalize(path.posix.join(path.posix.dirname(sourcePath), specifier));
794
+ const owner = mappings.find((mapping) => (
795
+ resolvedSource === mapping.sourceRoot
796
+ || resolvedSource.startsWith(`${mapping.sourceRoot}/`)
797
+ ));
798
+ if (!owner) {
799
+ throw new Error(`Scaffold product import escapes resolved source ownership: ${sourcePath}: ${specifier}`);
800
+ }
801
+ const sourceSuffix = resolvedSource === owner.sourceRoot
802
+ ? ''
803
+ : resolvedSource.slice(owner.sourceRoot.length + 1);
804
+ const resolvedTarget = sourceSuffix
805
+ ? `${owner.targetRoot}/${sourceSuffix}`
806
+ : owner.targetRoot;
807
+ const rewritten = relativeModuleSpecifier(outputPath, resolvedTarget);
808
+ return `${prefix}${quote}${rewritten}${quote}${suffix}`;
809
+ });
810
+ }
811
+
812
+ function buildNimiAppManifest(identity) {
813
+ return YAML.stringify({
814
+ app_id: identity.appId,
815
+ display_name: identity.appTitle,
816
+ version: identity.version,
817
+ profile: identity.profile,
818
+ manifest_role: 'submitted-input',
819
+ app_access: identity.appAccessItems,
820
+ local_development: {
821
+ electron: {
822
+ renderer_origin: `http://127.0.0.1:${identity.devPort}`,
823
+ },
824
+ },
825
+ }, { lineWidth: 0 });
826
+ }
827
+
828
+ function renderTauriConfig(raw, identity) {
829
+ const config = JSON.parse(raw);
830
+ config.productName = identity.appTitle;
831
+ config.version = identity.version;
832
+ config.identifier = identity.nativeBundleIdentifier;
833
+ config.build = { ...config.build, devUrl: `http://127.0.0.1:${identity.devPort}` };
834
+ config.app = {
835
+ ...config.app,
836
+ windows: Array.isArray(config.app?.windows)
837
+ ? config.app.windows.map((window) => ({ ...window, title: identity.appTitle }))
838
+ : [],
839
+ };
840
+ return jsonFile(config);
841
+ }
842
+
843
+ function renderAppIdentityModule(identity) {
424
844
  return [
425
- {
426
- path: 'package.json',
427
- content: jsonFile(buildPackageJson(identity.profile, versions, identity)),
845
+ `export const appId = ${JSON.stringify(identity.appId)};`,
846
+ `export const appTitle = ${JSON.stringify(identity.appTitle)};`,
847
+ `export const scaffoldProfile = ${JSON.stringify(identity.profile)} as const;`,
848
+ `export const nativeBundleIdentifier = ${JSON.stringify(identity.nativeBundleIdentifier)};`,
849
+ '',
850
+ ].join('\n');
851
+ }
852
+
853
+ function escapeHtmlText(input) {
854
+ return String(input)
855
+ .replaceAll('&', '&amp;')
856
+ .replaceAll('<', '&lt;')
857
+ .replaceAll('>', '&gt;')
858
+ .replaceAll('"', '&quot;')
859
+ .replaceAll("'", '&#39;');
860
+ }
861
+
862
+ function renderIdentitySensitiveStarterFile(relativePath, raw, manifest, identity) {
863
+ if (relativePath === 'src-tauri/tauri.conf.json') {
864
+ return renderTauriConfig(raw, identity);
865
+ }
866
+ if (relativePath === 'src/shell/auth/app-identity.ts') {
867
+ return renderAppIdentityModule(identity);
868
+ }
869
+ if (relativePath === 'index.html') {
870
+ return raw.split(manifest.sourceIdentity.appTitle).join(escapeHtmlText(identity.appTitle));
871
+ }
872
+ return applyIdentityReplacement(raw, manifest, targetIdentityMap(identity));
873
+ }
874
+
875
+ function applyProfileSeam(relativePath, content, profile, versions, manifest, identity) {
876
+ if (relativePath === 'nimi.app.yaml') {
877
+ return buildNimiAppManifest(identity);
878
+ }
879
+ if (relativePath === 'src-tauri/Cargo.toml') {
880
+ return renderCargoManifest(content, profile, versions, identity);
881
+ }
882
+ if (relativePath === 'README.md') {
883
+ return content.replace(/Profile: `standalone`/, `Profile: \`${profile}\``);
884
+ }
885
+ return content;
886
+ }
887
+
888
+ function buildDefaultStarterTemplateFiles(identity, profile, versions) {
889
+ const { baseDir, manifest } = loadDefaultStarterSource();
890
+ const target = targetIdentityMap(identity);
891
+ return manifest.files.map((entry) => {
892
+ const raw = readDefaultStarterSourceFile(baseDir, entry.path);
893
+ const identityApplied = renderIdentitySensitiveStarterFile(entry.path, raw, manifest, identity);
894
+ return {
895
+ path: entry.path,
896
+ content: applyProfileSeam(entry.path, identityApplied, profile, versions, manifest, identity),
897
+ mutationClass: entry.class,
898
+ };
899
+ });
900
+ }
901
+
902
+ function buildCapabilitySliceFiles(identity, profile, versions) {
903
+ if (identity.capabilityResolution.modules.length === 0) return [];
904
+ const { baseDir, manifest } = loadAppSource(identity.capabilityResolution.resolvedModuleIds);
905
+ const mappings = identity.capabilityResolution.modules.flatMap((module) => (
906
+ module.sourceMappings.map((mapping) => ({ ...mapping, ownerId: module.id }))
907
+ ));
908
+ const outputPaths = new Set();
909
+ const files = [];
910
+ for (const module of identity.capabilityResolution.modules) {
911
+ for (const mapping of module.sourceMappings) {
912
+ const sourcePrefix = `${mapping.sourceRoot}/`;
913
+ const selected = manifest.files.filter((entry) => entry.path.startsWith(sourcePrefix));
914
+ if (selected.length === 0) {
915
+ throw new Error(`App scaffold module source is empty: ${module.id}: ${mapping.sourceRoot}`);
916
+ }
917
+ for (const entry of selected) {
918
+ const suffix = entry.path.slice(sourcePrefix.length);
919
+ const outputPath = `${mapping.targetRoot}/${suffix}`;
920
+ if (outputPaths.has(outputPath)) {
921
+ throw new Error(`App scaffold module output collision: ${outputPath}`);
922
+ }
923
+ outputPaths.add(outputPath);
924
+ const raw = readAppSourceFile(baseDir, entry.path);
925
+ assertIdentityNeutralProductSource(entry.path, raw, manifest);
926
+ const rendered = rewriteMappedModuleSpecifiers(raw, entry.path, outputPath, mappings);
927
+ files.push({
928
+ path: outputPath,
929
+ content: applyProfileSeam(outputPath, rendered, profile, versions, manifest, identity),
930
+ mutationClass: 'app-owned product code',
931
+ ownerKind: 'module',
932
+ ownerId: module.id,
933
+ });
934
+ }
935
+ }
936
+ }
937
+ return files.sort((left, right) => left.path.localeCompare(right.path));
938
+ }
939
+
940
+ function buildWorkbenchCoreFiles(identity, profile, versions) {
941
+ const { baseDir, manifest } = loadAppSource(identity.capabilityResolution.resolvedModuleIds);
942
+ const sourcePrefix = `${WORKBENCH_CORE_SOURCE_ROOT}/`;
943
+ const selected = manifest.files.filter((entry) => entry.path.startsWith(sourcePrefix));
944
+ if (selected.length === 0) {
945
+ throw new Error('Workbench core source is empty');
946
+ }
947
+ return selected.map((entry) => {
948
+ const raw = readAppSourceFile(baseDir, entry.path);
949
+ assertIdentityNeutralProductSource(entry.path, raw, manifest);
950
+ return {
951
+ path: entry.path,
952
+ content: applyProfileSeam(entry.path, raw, profile, versions, manifest, identity),
953
+ mutationClass: 'app-owned product code',
954
+ ownerKind: 'skeleton',
955
+ ownerId: 'workbench-core',
956
+ };
957
+ }).sort((left, right) => left.path.localeCompare(right.path));
958
+ }
959
+
960
+ export function renderAppIdentityInput(identity) {
961
+ return YAML.stringify({
962
+ app_id: identity.appId,
963
+ display_name: identity.appTitle,
964
+ version: identity.version,
965
+ npm_package_name: identity.packageName,
966
+ cargo_package_name: identity.cargoPackageName,
967
+ tauri_identifier: identity.tauriIdentifier,
968
+ package_author: identity.author || null,
969
+ identity_role: 'scaffold-generated-authoring-input',
970
+ }, { lineWidth: 0 });
971
+ }
972
+
973
+ export function renderAppBuildProfile(options = {}) {
974
+ const identity = options.identity || null;
975
+ const targets = options.targets || (identity ? {
976
+ 'windows-x86_64': {
977
+ os: 'windows',
978
+ arch: 'x86_64',
979
+ build_command: 'pnpm run build:shell',
980
+ payload_path: `src-tauri/target/release/${identity.cargoPackageName}.exe`,
981
+ runtime_entry: `payload/${identity.cargoPackageName}.exe`,
428
982
  },
429
- {
430
- path: 'tsconfig.json',
431
- content: jsonFile({
432
- compilerOptions: {
433
- target: 'ES2022',
434
- module: 'ESNext',
435
- moduleResolution: 'Bundler',
436
- jsx: 'react-jsx',
437
- strict: true,
438
- skipLibCheck: true,
439
- noEmit: true,
440
- types: ['node'],
441
- },
442
- include: ['src/**/*.ts', 'src/**/*.tsx', 'test/**/*.mjs'],
443
- }),
983
+ } : undefined);
984
+ return YAML.stringify({
985
+ build_profile_ref: 'tauri-pnpm-vite',
986
+ test_command: options.testCommand || 'pnpm run test:app',
987
+ build_command: options.buildCommand || 'pnpm run build:shell',
988
+ output_path: 'src-tauri/target/release',
989
+ lockfile_path: 'pnpm-lock.yaml',
990
+ lockfile_policy: LOCKFILE_POLICY,
991
+ ci_install_command: 'pnpm install --frozen-lockfile',
992
+ ...(targets ? { targets } : {}),
993
+ profile_role: 'developer-workflow-input',
994
+ }, { lineWidth: 0 });
995
+ }
996
+
997
+ export function managedAppReleaseWorkflowSource() {
998
+ return APP_RELEASE_WORKFLOW;
999
+ }
1000
+
1001
+ export function renderAppSubmissionInput(identity, options = {}) {
1002
+ const supportManifest = options.supportManifest || {
1003
+ diagnostics_bundle_fields: ['app_version', 'runtime_status'],
1004
+ redaction_rules: ['credentials'],
1005
+ user_visible_issue_categories: ['startup', 'runtime'],
1006
+ escalation_path: 'README.md#support',
1007
+ kill_switch_visibility: 'visible',
1008
+ recovery_instructions: 'Restart the App from Nimi. If the problem persists, reinstall the current admitted release.',
1009
+ };
1010
+ return YAML.stringify({
1011
+ app_id: identity.appId,
1012
+ display_name: identity.appTitle,
1013
+ version: identity.version,
1014
+ profile: identity.profile,
1015
+ npm_package_name: identity.packageName,
1016
+ cargo_package_name: identity.cargoPackageName,
1017
+ tauri_identifier: identity.tauriIdentifier,
1018
+ package_author: identity.author || null,
1019
+ submission_role: 'developer-submitted-input',
1020
+ capability_contract_refs: options.capabilityContractRefs || [],
1021
+ required_standardized_feature_refs: options.requiredStandardizedFeatureRefs || [],
1022
+ ...(options.aiProfileRecommendationRef ? { ai_profile_recommendation_ref: options.aiProfileRecommendationRef } : {}),
1023
+ storage_policy: options.storagePolicy || { kind: 'nimi-mediated-default' },
1024
+ support_manifest: supportManifest,
1025
+ review_inputs: {
1026
+ manifest: 'nimi.app.yaml',
1027
+ build_profile: '.nimi/config/build-profile.yaml',
1028
+ scaffold_boundary: '.nimi/contracts/scaffold-boundary.yaml',
444
1029
  },
1030
+ admission_truth: 'platform-owned-after-review',
1031
+ }, { lineWidth: 0 });
1032
+ }
1033
+
1034
+ function buildScaffoldBoundary() {
1035
+ return YAML.stringify({
1036
+ scaffold_contract: 'P-SCAF',
1037
+ profile: 'standalone',
1038
+ public_admission_truth: 'not-generated',
1039
+ developer_release_input: 'candidate-only',
1040
+ }, { lineWidth: 0 });
1041
+ }
1042
+
1043
+ function buildStructuredFiles(identity, profile, versions) {
1044
+ const files = [
445
1045
  {
446
- path: 'index.html',
447
- content: [
448
- '<!doctype html>',
449
- '<html lang="en">',
450
- ' <head>',
451
- ' <meta charset="UTF-8" />',
452
- ' <meta name="viewport" content="width=device-width, initial-scale=1.0" />',
453
- ` <title>${identity.appTitle}</title>`,
454
- ' </head>',
455
- ' <body>',
456
- ' <div id="root"></div>',
457
- ' <script type="module" src="/src/main.tsx"></script>',
458
- ' </body>',
459
- '</html>',
460
- '',
461
- ].join('\n'),
1046
+ path: '.gitignore',
1047
+ content: GENERATED_GITIGNORE,
1048
+ mutationClass: 'scaffold-managed glue',
462
1049
  },
463
1050
  {
464
- path: 'vite.config.ts',
465
- content: [
466
- "import { defineConfig } from 'vite';",
467
- "import react from '@vitejs/plugin-react';",
468
- '',
469
- 'export default defineConfig({',
470
- ' plugins: [react()],',
471
- '});',
472
- '',
473
- ].join('\n'),
1051
+ path: 'package.json',
1052
+ content: jsonFile(buildPackageJson(profile, versions, identity)),
1053
+ mutationClass: 'app-owned product code',
474
1054
  },
475
1055
  {
476
- path: 'nimi.app.yaml',
477
- content: [
478
- `app_id: ${identity.appId}`,
479
- `display_name: ${identity.appTitle}`,
480
- `profile: ${identity.profile}`,
481
- 'manifest_role: submitted-input',
482
- 'permissions:',
483
- ' declared_nimi_api_scopes:',
484
- ' - scope: app.local.drafts',
485
- ' qualifier: app-local-drafts',
486
- ' purpose: Store drafts owned by this app during author testing.',
487
- '',
488
- ].join('\n'),
1056
+ path: '.github/workflows/nimi-app-release.yml',
1057
+ content: APP_RELEASE_WORKFLOW,
1058
+ mutationClass: 'scaffold-managed glue',
489
1059
  },
490
1060
  {
491
- path: '.nimi/admission/submission.yaml',
492
- content: [
493
- `app_id: ${identity.appId}`,
494
- `display_name: ${identity.appTitle}`,
495
- `profile: ${identity.profile}`,
496
- `npm_package_name: ${identity.packageName}`,
497
- `cargo_package_name: ${identity.cargoPackageName}`,
498
- `tauri_identifier: ${identity.tauriIdentifier}`,
499
- ...(identity.author ? [`package_author: ${identity.author}`] : []),
500
- 'submission_role: developer-submitted-input',
501
- 'publish_readiness:',
502
- ' install_command: pnpm install',
503
- ' dev_shell_command: pnpm dev:shell',
504
- ' build_command: pnpm run build',
505
- ' pack_command: pnpm run pack',
506
- 'review_inputs:',
507
- ' manifest: nimi.app.yaml',
508
- ' build_profile: .nimi/config/build-profile.yaml',
509
- ' scaffold_boundary: .nimi/contracts/scaffold-boundary.yaml',
510
- ' local_audit: pnpm run local-audit',
511
- 'admission_truth: platform-owned-after-review',
512
- '',
513
- ].join('\n'),
1061
+ path: 'nimi.app.yaml',
1062
+ content: buildNimiAppManifest(identity),
1063
+ mutationClass: 'scaffold-managed glue',
514
1064
  },
515
1065
  {
516
1066
  path: '.nimi/config/app-identity.yaml',
517
- content: [
518
- `app_id: ${identity.appId}`,
519
- `display_name: ${identity.appTitle}`,
520
- `npm_package_name: ${identity.packageName}`,
521
- `cargo_package_name: ${identity.cargoPackageName}`,
522
- `tauri_identifier: ${identity.tauriIdentifier}`,
523
- ...(identity.author ? [`package_author: ${identity.author}`] : []),
524
- 'identity_role: scaffold-generated-authoring-input',
525
- '',
526
- ].join('\n'),
1067
+ content: renderAppIdentityInput(identity),
1068
+ mutationClass: 'scaffold-managed glue',
527
1069
  },
528
1070
  {
529
1071
  path: '.nimi/config/build-profile.yaml',
530
- content: [
531
- 'build_profile_ref: tauri-pnpm-vite',
532
- 'toolchain_version: node>=20;pnpm>=9;rust>=1.80;tauri=2',
533
- 'build_command: pnpm run build',
534
- 'output_path: src-tauri/target/release',
535
- 'lockfile_path: pnpm-lock.yaml',
536
- `lockfile_policy: ${LOCKFILE_POLICY}`,
537
- 'ci_install_command: pnpm install --no-frozen-lockfile',
538
- 'profile_role: developer-workflow-input',
539
- '',
540
- ].join('\n'),
1072
+ content: renderAppBuildProfile({ identity }),
1073
+ mutationClass: 'app-owned product code',
541
1074
  },
542
1075
  {
543
- path: '.nimi/contracts/scaffold-boundary.yaml',
544
- content: [
545
- 'scaffold_contract: P-SCAF',
546
- `profile: ${identity.profile}`,
547
- 'public_admission_truth: not-generated',
548
- 'local_audit_role: pre-submission-self-check',
549
- 'permission_declarations: transparency-input-only',
550
- '',
551
- ].join('\n'),
552
- },
553
- {
554
- path: '.nimi/methodology/scaffold-managed-files.yaml',
555
- content: [
556
- 'mutation_classes:',
557
- ' package_owned_projection:',
558
- ' - .nimi/config/**',
559
- ' - .nimi/contracts/**',
560
- ' - .nimi/methodology/**',
561
- ' - .nimi/admission/**',
562
- ' scaffold_managed_glue:',
563
- ' - .github/**',
564
- ' - .gitignore',
565
- ' - package.json',
566
- ' - ADMISSION.md',
567
- ' - README.md',
568
- ' - SECURITY.md',
569
- ' - nimi.app.yaml',
570
- ' - src/shell/auth/**',
571
- ' - src-tauri/**',
572
- ' - scripts/**',
573
- ' app_owned_product_code:',
574
- ' - src/shell/routes/product-area.tsx',
575
- '',
576
- ].join('\n'),
577
- },
578
- {
579
- path: 'AGENTS.md',
580
- content: [
581
- '# AGENTS.md',
582
- '- Treat `.nimi/**` as host-local scaffold truth for this generated app.',
583
- '- Keep auth, Runtime, permission, manifest, and Tauri shell glue in scaffold-managed files.',
584
- '- The app-owned area is `src/shell/routes/product-area.tsx` unless a later scaffold update expands it.',
585
- '- `.nimi/admission/**` and `ADMISSION.md` are developer-submitted review inputs, not platform admission truth.',
586
- '- Local checks are pre-submission self-checks only.',
587
- '',
588
- ].join('\n'),
589
- },
590
- {
591
- path: '.gitignore',
592
- content: [
593
- 'node_modules/',
594
- 'dist/',
595
- 'src-tauri/target/',
596
- '.turbo/',
597
- '.vite/',
598
- '.DS_Store',
599
- '',
600
- ].join('\n'),
601
- },
602
- {
603
- path: 'README.md',
604
- content: [
605
- `# ${identity.appTitle}`,
606
- '',
607
- `Profile: \`${identity.profile}\``,
608
- '',
609
- 'This repository is a Nimi App authoring scaffold. `nimi.app.yaml`, the build profile, permission declarations, pack output, validate output, and local audit output are submitted inputs and pre-submission self-checks only.',
610
- '',
611
- '## Development',
612
- '',
613
- '```bash',
614
- 'pnpm install',
615
- 'pnpm dev:shell',
616
- 'pnpm run validate',
617
- 'pnpm run local-audit',
618
- 'pnpm run pack',
619
- 'pnpm run doctor',
620
- 'pnpm run update',
621
- '```',
622
- '',
623
- '`doctor` and `update` are developer scaffold checks for this source repository. They do not update an installed app, publish admission truth, create release descriptors, or grant permissions.',
624
- '',
625
- 'For Nimi listing review, keep `nimi.app.yaml`, `.nimi/admission/submission.yaml`, `.nimi/config/build-profile.yaml`, and `ADMISSION.md` in sync with the product behavior under `src/shell/routes/product-area.tsx`.',
626
- '',
627
- 'Upstream Platform/Runtime review produces release descriptors, ordinary visibility, install truth, and scope authorization. This scaffold does not mint those outcomes.',
628
- '',
629
- ].join('\n'),
630
- },
631
- {
632
- path: 'ADMISSION.md',
633
- content: [
634
- `# ${identity.appTitle} Nimi Listing Request`,
635
- '',
636
- 'This document is a developer-submitted listing request. It is not an approval, release descriptor, permission grant, or install truth.',
637
- '',
638
- '## Developer Runbook',
639
- '',
640
- '```bash',
641
- 'pnpm install',
642
- 'pnpm dev:shell',
643
- 'pnpm run check',
644
- 'pnpm run pack',
645
- '```',
646
- '',
647
- '## Submission Inputs',
648
- '',
649
- '- `nimi.app.yaml` declares app identity and requested API scopes.',
650
- '- `.nimi/admission/submission.yaml` records publish-readiness commands and review inputs.',
651
- '- `.nimi/config/build-profile.yaml` records install, build, and lockfile policy.',
652
- '- `dist/nimi-app-submission.json` is produced by `pnpm run pack` after a successful renderer build.',
653
- '',
654
- '## Reviewer Boundary',
655
- '',
656
- 'Nimi Platform review owns final admission, release descriptors, ordinary-user visibility, install availability, and permission grants.',
657
- '',
658
- ].join('\n'),
659
- },
660
- {
661
- path: 'LICENSE',
662
- content: [
663
- 'MIT License',
664
- '',
665
- `Copyright (c) ${SCAFFOLD_LICENSE_YEAR} ${identity.appTitle}`,
666
- '',
667
- 'Permission is hereby granted, free of charge, to any person obtaining a copy',
668
- 'of this software and associated documentation files to deal in the Software',
669
- 'without restriction, including without limitation the rights to use, copy,',
670
- 'modify, merge, publish, distribute, sublicense, and/or sell copies of the',
671
- 'Software, and to permit persons to whom the Software is furnished to do so.',
672
- '',
673
- ].join('\n'),
674
- },
675
- {
676
- path: 'SECURITY.md',
677
- content: [
678
- '# Security',
679
- '',
680
- '- Do not store Realm credentials or app-owned bearer credentials in this repository.',
681
- '- Use `createNimiAppRuntimePlatformClient` for Runtime platform projection.',
682
- '- Treat permission declarations as review transparency, not grants.',
683
- '',
684
- ].join('\n'),
685
- },
686
- {
687
- path: 'scripts/validate.mjs',
688
- content: [
689
- "import { readFileSync } from 'node:fs';",
690
- '',
691
- "const manifest = readFileSync(new URL('../nimi.app.yaml', import.meta.url), 'utf8');",
692
- "const submission = readFileSync(new URL('../.nimi/admission/submission.yaml', import.meta.url), 'utf8');",
693
- "if (!manifest.includes('manifest_role: submitted-input')) {",
694
- " throw new Error('submitted manifest role marker missing');",
695
- '}',
696
- "if (!submission.includes('submission_role: developer-submitted-input')) {",
697
- " throw new Error('developer submission role marker missing');",
698
- '}',
699
- "if (!submission.includes('dev_shell_command: pnpm dev:shell')) {",
700
- " throw new Error('dev shell command marker missing');",
701
- '}',
702
- "console.log('[nimi-app] validate pre-submission self-check passed');",
703
- '',
704
- ].join('\n'),
705
- },
706
- {
707
- path: 'scripts/local-audit.mjs',
708
- content: [
709
- "import { readFileSync } from 'node:fs';",
710
- '',
711
- "const boundary = readFileSync(new URL('../.nimi/contracts/scaffold-boundary.yaml', import.meta.url), 'utf8');",
712
- "if (!boundary.includes('local_audit_role: pre-submission-self-check')) {",
713
- " throw new Error('local audit role marker missing');",
714
- '}',
715
- "console.log('[nimi-app] local-audit pre-submission self-check passed');",
716
- '',
717
- ].join('\n'),
718
- },
719
- {
720
- path: 'scripts/pack.mjs',
721
- content: [
722
- "import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';",
723
- "import { join } from 'node:path';",
724
- '',
725
- "if (!existsSync(join('dist', 'index.html'))) {",
726
- " throw new Error('renderer build output missing: run pnpm run build before packing');",
727
- '}',
728
- "const packageJson = JSON.parse(readFileSync('package.json', 'utf8'));",
729
- "const tauriConfig = JSON.parse(readFileSync(join('src-tauri', 'tauri.conf.json'), 'utf8'));",
730
- "const manifest = readFileSync('nimi.app.yaml', 'utf8');",
731
- "const submission = readFileSync(join('.nimi', 'admission', 'submission.yaml'), 'utf8');",
732
- "if (!manifest.includes('manifest_role: submitted-input')) {",
733
- " throw new Error('submitted manifest role marker missing');",
734
- '}',
735
- "if (!submission.includes('submission_role: developer-submitted-input')) {",
736
- " throw new Error('developer submission role marker missing');",
737
- '}',
738
- "mkdirSync('dist', { recursive: true });",
739
- 'const packet = {',
740
- " packetRole: 'developer-submitted-input',",
741
- ' packageName: packageJson.name,',
742
- ' appVersion: tauriConfig.version,',
743
- ' tauriIdentifier: tauriConfig.identifier,',
744
- " rendererEntry: 'dist/index.html',",
745
- " manifestPath: 'nimi.app.yaml',",
746
- " admissionRequestPath: '.nimi/admission/submission.yaml',",
747
- " generatedBy: '@nimiplatform/app-tools',",
748
- '};',
749
- "writeFileSync(join('dist', 'nimi-app-submission.json'), `${JSON.stringify(packet, null, 2)}\\n`);",
750
- "console.log('[nimi-app] pack wrote dist/nimi-app-submission.json');",
751
- '',
752
- ].join('\n'),
753
- },
754
- {
755
- path: 'test/scaffold-boundary.test.mjs',
756
- content: [
757
- "import assert from 'node:assert/strict';",
758
- "import { readFileSync } from 'node:fs';",
759
- "import test from 'node:test';",
760
- '',
761
- "const authSource = readFileSync(new URL('../src/shell/auth/runtime-platform.ts', import.meta.url), 'utf8');",
762
- "const manifest = readFileSync(new URL('../nimi.app.yaml', import.meta.url), 'utf8');",
763
- "const submission = readFileSync(new URL('../.nimi/admission/submission.yaml', import.meta.url), 'utf8');",
764
- '',
765
- "test('auth glue uses Nimi App runtime platform helper', () => {",
766
- " assert.match(authSource, /createNimiAppRuntimePlatformClient/);",
767
- " assert.doesNotMatch(authSource, /createPlatformClient\\s*\\(/);",
768
- "});",
769
- '',
770
- "test('manifest remains submitted input', () => {",
771
- " assert.match(manifest, /manifest_role: submitted-input/);",
772
- " assert.match(manifest, /declared_nimi_api_scopes/);",
773
- "});",
774
- '',
775
- "test('admission request remains submitted input', () => {",
776
- " assert.match(submission, /submission_role: developer-submitted-input/);",
777
- " assert.match(submission, /dev_shell_command: pnpm dev:shell/);",
778
- " assert.match(submission, /admission_truth: platform-owned-after-review/);",
779
- "});",
780
- '',
781
- ].join('\n'),
782
- },
783
- {
784
- path: '.github/workflows/ci.yml',
785
- content: [
786
- 'name: pre-submission-self-check',
787
- 'on:',
788
- ' pull_request:',
789
- ' push:',
790
- 'jobs:',
791
- ' check:',
792
- ' runs-on: ubuntu-latest',
793
- ' steps:',
794
- ' - uses: actions/checkout@v4',
795
- ' - uses: pnpm/action-setup@v4',
796
- ' with:',
797
- ' version: 9',
798
- ' - uses: actions/setup-node@v4',
799
- ' with:',
800
- ' node-version: 22',
801
- ' - run: pnpm install --no-frozen-lockfile',
802
- ' - run: pnpm run check',
803
- '',
804
- ].join('\n'),
805
- },
806
- ];
807
- }
808
-
809
- function buildTauriFiles(identity, versions) {
810
- const shellDependency = identity.profile === 'workspace-app'
811
- ? '{ path = "../../../kit/shell/tauri" }'
812
- : `"${versions.nimiShellTauriVersion}"`;
813
- return [
814
- {
815
- path: 'src-tauri/Cargo.toml',
816
- content: [
817
- '[package]',
818
- `name = "${identity.cargoPackageName}"`,
819
- 'version = "0.1.0"',
820
- 'edition = "2021"',
821
- '',
822
- '[dependencies]',
823
- 'tauri = "2"',
824
- `nimi-shell-tauri = ${shellDependency}`,
825
- '',
826
- '[build-dependencies]',
827
- 'tauri-build = { version = "2", features = [] }',
828
- '',
829
- ].join('\n'),
830
- },
831
- {
832
- path: 'src-tauri/build.rs',
833
- content: [
834
- 'fn main() {',
835
- ' tauri_build::build();',
836
- '}',
837
- '',
838
- ].join('\n'),
1076
+ path: '.nimi/admission/submission.yaml',
1077
+ content: renderAppSubmissionInput(identity, {
1078
+ capabilityContractRefs: identity.capabilityResolution.capabilityContractRefs,
1079
+ requiredStandardizedFeatureRefs: identity.capabilityResolution.requiredStandardizedFeatureRefs,
1080
+ }),
1081
+ mutationClass: 'app-owned product code',
839
1082
  },
840
1083
  {
841
- path: 'src-tauri/tauri.conf.json',
842
- content: jsonFile({
843
- productName: identity.appTitle,
844
- version: '0.1.0',
845
- identifier: identity.tauriIdentifier,
846
- build: {
847
- beforeDevCommand: 'pnpm run dev:renderer',
848
- beforeBuildCommand: 'pnpm run build',
849
- devUrl: 'http://localhost:1420',
850
- frontendDist: '../dist',
851
- },
852
- app: {
853
- windows: [
854
- {
855
- title: identity.appTitle,
856
- width: 1120,
857
- height: 760,
858
- },
859
- ],
860
- },
861
- bundle: {
862
- icon: ['icons/icon.png'],
863
- },
864
- }),
1084
+ path: '.nimi/contracts/scaffold-boundary.yaml',
1085
+ content: buildScaffoldBoundary(),
1086
+ mutationClass: 'scaffold-managed glue',
865
1087
  },
866
1088
  {
867
1089
  path: 'src-tauri/icons/icon.png',
868
1090
  content: MINIMAL_TAURI_ICON_PNG,
1091
+ mutationClass: 'scaffold-managed glue',
869
1092
  },
870
1093
  {
871
- path: 'src-tauri/src/main.rs',
872
- content: [
873
- 'fn main() {',
874
- ' tauri::Builder::default()',
875
- ' .invoke_handler(nimi_shell_tauri::nimi_shell_tauri_runtime_bridge_handler![])',
876
- ' .run(tauri::generate_context!())',
877
- ' .expect("failed to run Nimi App shell");',
878
- '}',
879
- '',
880
- ].join('\n'),
1094
+ path: 'src-tauri/icons/icon.ico',
1095
+ content: MINIMAL_TAURI_ICON_ICO,
1096
+ mutationClass: 'scaffold-managed glue',
881
1097
  },
882
1098
  ];
1099
+ return files;
883
1100
  }
884
1101
 
885
- function buildWorkspaceAppFiles(identity) {
886
- return [
887
- {
888
- path: `apps/${identity.packageName}/spec/app-slice.md`,
889
- content: [
890
- `# ${identity.appId} App Slice`,
891
- '',
892
- 'Workspace-app profile input under P-APP authority. This app-slice file is not public Nimi App admission and does not create ordinary-user visibility.',
893
- '',
894
- ].join('\n'),
1102
+ function buildIdentityMapping(identity, targetDir = '') {
1103
+ return {
1104
+ appId: identity.appId,
1105
+ displayName: identity.appTitle,
1106
+ version: identity.version,
1107
+ npmPackageName: identity.packageName,
1108
+ author: identity.author || null,
1109
+ cargoPackageName: identity.cargoPackageName,
1110
+ nativeBundleIdentifier: identity.nativeBundleIdentifier,
1111
+ tauriIdentifier: identity.tauriIdentifier,
1112
+ appSlug: identity.appSlug,
1113
+ rendererEntryId: identity.rendererEntryId,
1114
+ devPort: identity.devPort,
1115
+ devRendererOrigin: `http://127.0.0.1:${identity.devPort}`,
1116
+ appOwnedNamespace: identity.appOwnedNamespace,
1117
+ targetDir: targetDir || null,
1118
+ };
1119
+ }
1120
+
1121
+ function buildScaffoldIntent(identity, versions, targetDir = '') {
1122
+ return {
1123
+ intentVersion: SCAFFOLD_INTENT_VERSION,
1124
+ scaffoldVersion: SCAFFOLD_VERSION,
1125
+ initRequired: true,
1126
+ initCommand: 'pnpm exec nimi-app init',
1127
+ initOrder: ['nimi-app create', 'pnpm install', 'pnpm exec nimi-app init'],
1128
+ profile: identity.profile,
1129
+ appId: identity.appId,
1130
+ appTitle: identity.appTitle,
1131
+ version: identity.version,
1132
+ packageName: identity.packageName,
1133
+ packageAuthor: identity.author || null,
1134
+ cargoPackageName: identity.cargoPackageName,
1135
+ tauriIdentifier: identity.tauriIdentifier,
1136
+ accentPack: identity.accentPack,
1137
+ features: identity.features,
1138
+ directFeatures: identity.capabilityResolution.directFeatureIds,
1139
+ resolvedModules: identity.capabilityResolution.resolvedModuleIds,
1140
+ resolvedViews: identity.capabilityResolution.views,
1141
+ resolvedNavigation: identity.capabilityResolution.navigation,
1142
+ resolvedStyles: identity.capabilityResolution.styles,
1143
+ resolvedAssets: identity.capabilityResolution.assets,
1144
+ hostAdapterContracts: identity.capabilityResolution.hostAdapterContracts,
1145
+ appAccessItems: identity.appAccessItems,
1146
+ capabilityContractRefs: identity.capabilityResolution.capabilityContractRefs,
1147
+ requiredStandardizedFeatureRefs: identity.capabilityResolution.requiredStandardizedFeatureRefs,
1148
+ devPort: identity.devPort,
1149
+ appIdentity: buildIdentityMapping(identity, targetDir),
1150
+ dependencyMatrix: buildDependencyMatrix(identity.profile, versions, identity.capabilityResolution),
1151
+ semantics: {
1152
+ role: 'app-scaffold-init-input',
1153
+ authority: 'app-tools-orchestration-input-not-platform-admission',
1154
+ nimicodingProjectionOwner: '@nimiplatform/nimi-coding',
895
1155
  },
896
- ];
1156
+ };
1157
+ }
1158
+
1159
+ function buildScaffoldIntentFile(identity, versions, targetDir = '') {
1160
+ return {
1161
+ path: SCAFFOLD_INTENT_PATH,
1162
+ content: jsonFile(buildScaffoldIntent(identity, versions, targetDir)),
1163
+ mutationClass: 'scaffold-managed glue',
1164
+ ownerKind: 'scaffold-state',
1165
+ ownerId: 'intent',
1166
+ };
1167
+ }
1168
+
1169
+ function withFileOwner(files, ownerKind, ownerId) {
1170
+ return files.map((file) => ({
1171
+ ...file,
1172
+ ownerKind: file.ownerKind ?? ownerKind,
1173
+ ownerId: file.ownerId ?? ownerId,
1174
+ }));
897
1175
  }
898
1176
 
899
1177
  function buildScaffoldFiles(identity, versions) {
900
1178
  return [
901
- ...buildCommonFiles(identity, versions),
902
- ...buildRendererFiles(identity),
903
- ...buildTauriFiles(identity, versions),
904
- ...(identity.profile === 'workspace-app' ? buildWorkspaceAppFiles(identity) : []),
1179
+ ...withFileOwner(
1180
+ buildStructuredFiles(identity, identity.profile, versions),
1181
+ 'carrier',
1182
+ 'structured',
1183
+ ),
1184
+ ...withFileOwner(
1185
+ buildDefaultStarterTemplateFiles(identity, identity.profile, versions),
1186
+ 'carrier',
1187
+ 'default-starter',
1188
+ ),
1189
+ ...withFileOwner(buildDefaultStarterFiles(identity), 'generated-glue', 'composition'),
1190
+ ...buildWorkbenchCoreFiles(identity, identity.profile, versions),
1191
+ ...buildCapabilitySliceFiles(identity, identity.profile, versions),
905
1192
  ];
906
1193
  }
907
1194
 
908
- function normalizePathList(paths) {
909
- return [...paths].sort((left, right) => left.localeCompare(right));
910
- }
911
-
912
- function classifyScaffoldFile(filePath) {
913
- if (filePath === 'src/shell/routes/product-area.tsx') {
914
- return 'app-owned product code';
1195
+ export function validateScaffoldFileOwnership(files) {
1196
+ const filesByPath = new Map();
1197
+ const filesByCollisionKey = new Map();
1198
+ for (const file of files) {
1199
+ const relativePath = String(file?.path || '');
1200
+ if (
1201
+ !relativePath
1202
+ || relativePath.startsWith('/')
1203
+ || relativePath.endsWith('/')
1204
+ || relativePath.includes('\\')
1205
+ || relativePath.split('/').some((segment) => !segment || segment === '.' || segment === '..')
1206
+ || path.posix.normalize(relativePath) !== relativePath
1207
+ ) {
1208
+ throw new Error(`Scaffold file path is invalid: ${relativePath || 'missing'}`);
1209
+ }
1210
+ if (!file.ownerKind || !file.ownerId) {
1211
+ throw new Error(`Scaffold file ownership is missing: ${relativePath}`);
1212
+ }
1213
+ const collisionKey = relativePath.toLowerCase();
1214
+ const existing = filesByCollisionKey.get(collisionKey);
1215
+ if (existing) {
1216
+ throw new Error(
1217
+ `Scaffold file ownership collision: ${existing.path} and ${relativePath}: ${existing.ownerKind}/${existing.ownerId} and ${file.ownerKind}/${file.ownerId}`,
1218
+ );
1219
+ }
1220
+ filesByCollisionKey.set(collisionKey, file);
1221
+ filesByPath.set(relativePath, file);
915
1222
  }
916
- if (
917
- filePath.startsWith('.nimi/config/')
918
- || filePath.startsWith('.nimi/contracts/')
919
- || filePath.startsWith('.nimi/methodology/')
920
- || filePath.startsWith('.nimi/admission/')
921
- || /^apps\/[^/]+\/spec\//.test(filePath)
922
- ) {
923
- return 'package-owned projection';
1223
+ for (const [relativePath, file] of filesByPath) {
1224
+ const segments = relativePath.split('/');
1225
+ for (let index = 1; index < segments.length; index += 1) {
1226
+ const prefix = segments.slice(0, index).join('/');
1227
+ const prefixFile = filesByCollisionKey.get(prefix.toLowerCase());
1228
+ if (prefixFile) {
1229
+ throw new Error(
1230
+ `Scaffold file/directory prefix collision: ${prefix}: ${prefixFile.ownerKind}/${prefixFile.ownerId} and ${file.ownerKind}/${file.ownerId}`,
1231
+ );
1232
+ }
1233
+ }
924
1234
  }
925
- return 'scaffold-managed glue';
1235
+ return filesByPath;
1236
+ }
1237
+
1238
+ function normalizePathList(paths) {
1239
+ return [...paths].sort((left, right) => left.localeCompare(right));
926
1240
  }
927
1241
 
928
1242
  export function hashScaffoldContent(content) {
929
1243
  return createHash('sha256').update(content).digest('hex');
930
1244
  }
931
1245
 
932
- function buildDependencyMatrix(profile, versions) {
1246
+ function buildDependencyMatrix(profile, versions, capabilityResolution) {
933
1247
  return {
934
1248
  npm: {
935
- '@nimiplatform/app-tools': profile === 'workspace-app' ? 'workspace:*' : versions.appToolsVersion,
936
- '@nimiplatform/sdk': profile === 'workspace-app' ? 'workspace:*' : versions.sdkVersion,
937
- '@nimiplatform/kit': profile === 'workspace-app' ? 'workspace:*' : versions.kitVersion,
938
- '@tauri-apps/api': versions.tauriApiVersion,
939
- react: versions.reactVersion,
940
- 'react-dom': versions.reactDomVersion,
1249
+ '@nimiplatform/app-tools': versions.appToolsVersion,
1250
+ '@nimiplatform/nimi-coding': versions.nimicodingVersion,
1251
+ ...buildRuntimeDependencies(profile, versions, capabilityResolution),
941
1252
  typescript: versions.typescriptVersion,
942
1253
  vite: versions.viteVersion,
1254
+ tailwindcss: versions.tailwindcssVersion,
943
1255
  '@tauri-apps/cli': versions.tauriCliVersion,
1256
+ '@tailwindcss/vite': versions.tailwindcssViteVersion,
944
1257
  '@vitejs/plugin-react': versions.viteReactPluginVersion,
1258
+ electron: versions.electronVersion,
1259
+ esbuild: versions.esbuildVersion,
1260
+ yaml: versions.yamlVersion,
945
1261
  },
946
- cargo: {
947
- 'nimi-shell-tauri': profile === 'workspace-app'
948
- ? { path: '../../../kit/shell/tauri' }
949
- : versions.nimiShellTauriVersion,
950
- tauri: '2',
951
- 'tauri-build': '2',
952
- },
1262
+ cargo: buildCargoDependencies(profile, versions, capabilityResolution),
953
1263
  toolchain: {
954
- node: '>=20',
955
- pnpm: '>=9',
1264
+ node: '>=24',
1265
+ pnpm: versions.packageManager.replace(/^pnpm@/u, ''),
956
1266
  rust: '>=1.80',
957
1267
  tauri: '2',
958
1268
  },
959
1269
  };
960
1270
  }
961
1271
 
962
- function buildScaffoldLock(identity, versions, files) {
1272
+ function buildScaffoldLock(identity, versions, files, targetDir = '') {
963
1273
  const taxonomy = {
964
1274
  'package-owned projection': [],
965
1275
  'scaffold-managed glue': [],
@@ -969,7 +1279,7 @@ function buildScaffoldLock(identity, versions, files) {
969
1279
  const appOwnedInitialHashes = {};
970
1280
 
971
1281
  for (const file of files) {
972
- const mutationClass = classifyScaffoldFile(file.path);
1282
+ const mutationClass = file.mutationClass;
973
1283
  taxonomy[mutationClass].push(file.path);
974
1284
  const digest = hashScaffoldContent(file.content);
975
1285
  if (mutationClass === 'app-owned product code') {
@@ -986,24 +1296,29 @@ function buildScaffoldLock(identity, versions, files) {
986
1296
  }
987
1297
 
988
1298
  return {
989
- lockVersion: 1,
1299
+ lockVersion: SCAFFOLD_LOCK_VERSION,
990
1300
  scaffoldVersion: SCAFFOLD_VERSION,
991
1301
  profile: identity.profile,
992
1302
  appId: identity.appId,
993
1303
  appTitle: identity.appTitle,
1304
+ version: identity.version,
994
1305
  packageName: identity.packageName,
995
1306
  packageAuthor: identity.author || null,
996
1307
  cargoPackageName: identity.cargoPackageName,
997
1308
  tauriIdentifier: identity.tauriIdentifier,
998
- appIdentity: {
999
- appId: identity.appId,
1000
- appTitle: identity.appTitle,
1001
- npmPackageName: identity.packageName,
1002
- packageAuthor: identity.author || null,
1003
- cargoPackageName: identity.cargoPackageName,
1004
- tauriIdentifier: identity.tauriIdentifier,
1005
- identityRole: 'scaffold-generated-authoring-input',
1006
- },
1309
+ accentPack: identity.accentPack,
1310
+ appAccessItems: identity.appAccessItems,
1311
+ capabilityContractRefs: identity.capabilityResolution.capabilityContractRefs,
1312
+ requiredStandardizedFeatureRefs: identity.capabilityResolution.requiredStandardizedFeatureRefs,
1313
+ features: identity.features,
1314
+ directFeatures: identity.capabilityResolution.directFeatureIds,
1315
+ resolvedModules: identity.capabilityResolution.resolvedModuleIds,
1316
+ resolvedViews: identity.capabilityResolution.views,
1317
+ resolvedNavigation: identity.capabilityResolution.navigation,
1318
+ resolvedStyles: identity.capabilityResolution.styles,
1319
+ resolvedAssets: identity.capabilityResolution.assets,
1320
+ hostAdapterContracts: identity.capabilityResolution.hostAdapterContracts,
1321
+ appIdentity: buildIdentityMapping(identity, targetDir),
1007
1322
  managedFileTaxonomy: {
1008
1323
  packageOwnedProjection: normalizePathList(taxonomy['package-owned projection']),
1009
1324
  scaffoldManagedGlue: normalizePathList(taxonomy['scaffold-managed glue']),
@@ -1011,55 +1326,193 @@ function buildScaffoldLock(identity, versions, files) {
1011
1326
  },
1012
1327
  managedFileHashes,
1013
1328
  appOwnedInitialHashes,
1014
- dependencyMatrix: buildDependencyMatrix(identity.profile, versions),
1329
+ dependencyMatrix: buildDependencyMatrix(identity.profile, versions, identity.capabilityResolution),
1015
1330
  semantics: {
1016
- doctorAndUpdateRole: 'developer-scaffold-check-only',
1017
- publicAdmissionTruth: 'not-generated',
1018
- installedAppUpdateTruth: 'not-generated',
1019
- permissionGrantTruth: 'not-generated',
1331
+ initRole: 'developer-scaffold-initialization-after-install',
1332
+ nimicodingProjectionOwner: '@nimiplatform/nimi-coding',
1333
+ nimicodingApplyCommand: 'pnpm exec nimicoding sync --apply --json',
1334
+ nimicodingCheckCommand: 'pnpm exec nimicoding sync --check --json',
1335
+ syncAndCheckRole: 'developer-scaffold-maintenance-only',
1020
1336
  lockfilePolicy: LOCKFILE_POLICY,
1021
1337
  ignoredVerificationArtifacts: ['dist/'],
1338
+ capabilityComposition: 'base-plus-selected-dependency-closure',
1022
1339
  },
1023
1340
  };
1024
1341
  }
1025
1342
 
1026
- export function buildAppScaffoldSnapshot({ profile, versions, appId, appTitle, packageName, author }) {
1027
- const identity = buildAppIdentity(profile, appId, appTitle, packageName, author);
1028
- const files = buildScaffoldFiles(identity, versions);
1029
- const lock = buildScaffoldLock(identity, versions, files);
1030
- const allFiles = [
1031
- ...files,
1343
+ function buildAppScaffoldSnapshotWithResolver(
1344
+ { profile, versions, appId, appTitle, version = DEFAULT_APP_VERSION, packageName, author, accentPack, features, targetDir = '' },
1345
+ featureResolver,
1346
+ ) {
1347
+ const identity = buildAppIdentity(
1348
+ profile,
1349
+ appId,
1350
+ appTitle,
1351
+ version,
1352
+ packageName,
1353
+ author,
1354
+ accentPack,
1355
+ features,
1356
+ featureResolver,
1357
+ );
1358
+ const createFiles = [
1359
+ ...buildScaffoldFiles(identity, versions),
1360
+ buildScaffoldIntentFile(identity, versions, targetDir),
1361
+ ];
1362
+ validateScaffoldFileOwnership(createFiles);
1363
+ const filesWithoutLock = [...createFiles];
1364
+ const lock = buildScaffoldLock(identity, versions, filesWithoutLock, targetDir);
1365
+ const initFiles = [
1032
1366
  {
1033
1367
  path: SCAFFOLD_LOCK_PATH,
1034
1368
  content: jsonFile(lock),
1369
+ mutationClass: 'scaffold-managed glue',
1370
+ ownerKind: 'scaffold-state',
1371
+ ownerId: 'lock',
1035
1372
  },
1036
1373
  ];
1374
+ const allFiles = [
1375
+ ...createFiles,
1376
+ ...initFiles,
1377
+ ];
1378
+ const filesByPath = validateScaffoldFileOwnership(allFiles);
1037
1379
  return {
1038
1380
  appId: identity.appId,
1039
1381
  appTitle: identity.appTitle,
1382
+ version: identity.version,
1040
1383
  profile: identity.profile,
1041
1384
  packageName: identity.packageName,
1042
1385
  packageAuthor: identity.author || null,
1043
1386
  cargoPackageName: identity.cargoPackageName,
1044
1387
  tauriIdentifier: identity.tauriIdentifier,
1388
+ features: identity.features,
1045
1389
  files: allFiles,
1046
- filesWithoutLock: files,
1390
+ createFiles,
1391
+ initFiles,
1392
+ filesWithoutLock,
1047
1393
  lock,
1048
- filesByPath: new Map(allFiles.map((file) => [file.path, file])),
1394
+ filesByPath,
1049
1395
  };
1050
1396
  }
1051
1397
 
1398
+ export function buildAppScaffoldSnapshot(input) {
1399
+ return buildAppScaffoldSnapshotWithResolver(input, resolveAppScaffoldFeatures);
1400
+ }
1401
+
1402
+ export function buildAppScaffoldCandidateSnapshot(input) {
1403
+ return buildAppScaffoldSnapshotWithResolver(input, resolveAppScaffoldCandidateFeatures);
1404
+ }
1405
+
1406
+ export function buildAppScaffoldSnapshotFromIntent({ intent, versions, targetDir = '', allowDerivedAppAccessDrift = false }) {
1407
+ if (intent?.intentVersion !== SCAFFOLD_INTENT_VERSION) {
1408
+ throw new Error(`Unsupported scaffold intent version: ${String(intent?.intentVersion || 'missing')}`);
1409
+ }
1410
+ if (intent?.scaffoldVersion !== SCAFFOLD_VERSION) {
1411
+ throw new Error(`Unsupported scaffold intent version source: ${String(intent?.scaffoldVersion || 'missing')}`);
1412
+ }
1413
+ if (!SUPPORTED_APP_SCAFFOLD_PROFILES.includes(intent?.profile)) {
1414
+ throw new Error(`Unsupported scaffold profile: ${String(intent?.profile || 'missing')}`);
1415
+ }
1416
+ const canonicalTargetDir = targetDir || intent?.appIdentity?.targetDir || '';
1417
+ const snapshot = buildAppScaffoldSnapshotWithResolver({
1418
+ profile: intent.profile,
1419
+ versions,
1420
+ appId: intent.appId,
1421
+ appTitle: intent.appTitle,
1422
+ version: intent.version,
1423
+ packageName: intent.packageName,
1424
+ author: intent.packageAuthor || '',
1425
+ accentPack: intent.accentPack || 'nimi-accent',
1426
+ features: intent.directFeatures,
1427
+ targetDir: canonicalTargetDir,
1428
+ }, resolveAppScaffoldIntentFeatures);
1429
+ const expectedIntent = JSON.parse(snapshot.filesByPath.get(SCAFFOLD_INTENT_PATH).content);
1430
+ const comparableIntent = allowDerivedAppAccessDrift
1431
+ ? { ...intent, appAccessItems: expectedIntent.appAccessItems }
1432
+ : intent;
1433
+ if (canonicalJson(comparableIntent) !== canonicalJson(expectedIntent)) {
1434
+ throw new Error('Scaffold intent does not match the current canonical resolved intent');
1435
+ }
1436
+ return snapshot;
1437
+ }
1438
+
1439
+ function buildAppScaffoldCreatePlanWithResolver(
1440
+ { cwd, options = {}, versions, topology = null },
1441
+ featureResolver,
1442
+ ) {
1443
+ const resolvedInput = resolveAppScaffoldCreateInputWithResolver({ cwd, options }, featureResolver);
1444
+ const snapshot = buildAppScaffoldSnapshotWithResolver({
1445
+ profile: resolvedInput.profile,
1446
+ versions,
1447
+ appId: resolvedInput.appId,
1448
+ appTitle: resolvedInput.appTitle,
1449
+ version: resolvedInput.version,
1450
+ packageName: resolvedInput.packageName,
1451
+ author: resolvedInput.author,
1452
+ accentPack: resolvedInput.accentPack,
1453
+ features: resolvedInput.directFeatures,
1454
+ targetDir: resolvedInput.targetDir,
1455
+ }, featureResolver);
1456
+ return Object.freeze({
1457
+ resolvedInput,
1458
+ snapshot,
1459
+ preview: Object.freeze({
1460
+ targetDir: resolvedInput.targetDir,
1461
+ profile: resolvedInput.profile,
1462
+ identity: snapshot.lock.appIdentity,
1463
+ directFeatures: snapshot.lock.directFeatures,
1464
+ resolvedModules: snapshot.lock.resolvedModules,
1465
+ resolvedViews: snapshot.lock.resolvedViews,
1466
+ resolvedNavigation: snapshot.lock.resolvedNavigation,
1467
+ resolvedStyles: snapshot.lock.resolvedStyles,
1468
+ resolvedAssets: snapshot.lock.resolvedAssets,
1469
+ hostAdapterContracts: snapshot.lock.hostAdapterContracts,
1470
+ npmDependencies: snapshot.lock.dependencyMatrix.npm,
1471
+ cargoDependencies: snapshot.lock.dependencyMatrix.cargo,
1472
+ appAccessItems: snapshot.lock.appAccessItems,
1473
+ topology,
1474
+ }),
1475
+ });
1476
+ }
1477
+
1478
+ export function buildAppScaffoldCreatePlan(input) {
1479
+ return buildAppScaffoldCreatePlanWithResolver(input, resolveAppScaffoldFeatures);
1480
+ }
1481
+
1482
+ export function buildAppScaffoldCandidateCreatePlan(input) {
1483
+ return buildAppScaffoldCreatePlanWithResolver(input, resolveAppScaffoldCandidateFeatures);
1484
+ }
1485
+
1052
1486
  export function createAppScaffold(input) {
1053
1487
  const { cwd, options, versions, createFileTree, ensureDirEmptyOrMissing } = input;
1054
- const profile = resolveProfile(options);
1055
- const appId = resolveAppId(options);
1056
- const appTitle = String(options.title || options.name || DEFAULT_APP_TITLE).trim() || DEFAULT_APP_TITLE;
1057
- const packageName = resolvePackageName(options, appId);
1058
- const author = String(options.author || '').trim();
1059
- const targetDir = path.resolve(cwd, String(options.dir || '').trim() || appId);
1488
+ const plan = input.plan || buildAppScaffoldCreatePlan({ cwd, options, versions });
1489
+ const { targetDir, profile } = plan.resolvedInput;
1490
+ const { snapshot } = plan;
1060
1491
  ensureDirEmptyOrMissing(targetDir);
1061
- input.mkdirSync(targetDir, { recursive: true });
1062
- const snapshot = buildAppScaffoldSnapshot({ profile, versions, appId, appTitle, packageName, author });
1063
- createFileTree(targetDir, snapshot.files);
1064
- process.stdout.write(`[nimi-app] created ${profile} app scaffold at ${targetDir}\n`);
1492
+ // Resolution, source collection and every structured serialization complete
1493
+ // before a missing target directory is materialized.
1494
+ try {
1495
+ input.mkdirSync(targetDir, { recursive: true });
1496
+ createFileTree(targetDir, snapshot.createFiles);
1497
+ } catch (error) {
1498
+ const message = error instanceof Error ? error.message : String(error || 'unknown filesystem failure');
1499
+ throw new Error(`Scaffold materialization failed; inspect the exact residual target ${targetDir}: ${message}`);
1500
+ }
1501
+ const payload = {
1502
+ ok: true,
1503
+ command: 'create',
1504
+ dir: targetDir,
1505
+ profile,
1506
+ preview: plan.preview,
1507
+ };
1508
+ if (!options.silent) {
1509
+ process.stdout.write(`[nimi-app] created ${profile} app scaffold at ${targetDir}\n`);
1510
+ process.stdout.write('[nimi-app] next: pnpm install && pnpm run init\n');
1511
+ }
1512
+ return payload;
1513
+ }
1514
+
1515
+ export function createAppScaffoldCandidate(input) {
1516
+ const plan = input.plan || buildAppScaffoldCandidateCreatePlan(input);
1517
+ return createAppScaffold({ ...input, plan });
1065
1518
  }