@nimiplatform/app-tools 0.2.9 → 0.4.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 (44) hide show
  1. package/README.md +89 -4
  2. package/lib/app-doctor-update.mjs +12 -3
  3. package/lib/app-info.mjs +142 -0
  4. package/lib/app-pack.mjs +53 -16
  5. package/lib/app-project-lifecycle.mjs +10 -15
  6. package/lib/app-scaffold-profiles.mjs +28 -13
  7. package/lib/app-scaffold.mjs +31 -3
  8. package/lib/macos-native.mjs +96 -0
  9. package/lib/payload-links.mjs +41 -0
  10. package/package.json +8 -7
  11. package/scripts/sync-scaffold-versions.mjs +3 -16
  12. package/templates/app-source/src/ai-studio-core/ai-studio-core.css +31 -0
  13. package/templates/app-source/src/ai-studio-core/history-policy.ts +23 -1
  14. package/templates/app-source/src/ai-studio-core/history.ts +7 -1
  15. package/templates/app-source/src/ai-studio-core/host-context.tsx +5 -3
  16. package/templates/app-source/src/ai-studio-core/messages/en.json +1 -0
  17. package/templates/app-source/src/ai-studio-core/messages/zh.json +1 -0
  18. package/templates/app-source/src/ai-studio-core/module-registration.ts +2 -2
  19. package/templates/app-source/src/ai-studio-core/non-success-presentation.ts +6 -2
  20. package/templates/app-source/src/ai-studio-core/run-target.ts +1 -1
  21. package/templates/app-source/src/ai-studio-core/runtime-types.ts +4 -0
  22. package/templates/app-source/src/ai-studio-core/runtime.ts +13 -4
  23. package/templates/app-source/src/ai-studio-core/section-ai-testing-admission.ts +3 -3
  24. package/templates/app-source/src/ai-studio-core/section-ai-testing-composer.tsx +41 -13
  25. package/templates/app-source/src/ai-studio-core/section-ai-testing-history.tsx +1 -1
  26. package/templates/app-source/src/ai-studio-core/section-ai-testing-input.ts +1 -0
  27. package/templates/app-source/src/ai-studio-core/section-ai-testing-output.tsx +26 -1
  28. package/templates/app-source/src/ai-studio-core/section-ai-testing-result.tsx +14 -4
  29. package/templates/app-source/src/ai-studio-core/section-ai-testing-run.ts +3 -1
  30. package/templates/app-source/src/ai-studio-core/section-ai-testing-studio-result.tsx +12 -3
  31. package/templates/app-source/src/ai-studio-core/section-ai-testing-vision-input.tsx +56 -0
  32. package/templates/app-source/src/ai-studio-core/section-ai-testing-vision-result.tsx +22 -0
  33. package/templates/app-source/src/ai-studio-core/section-ai-testing.tsx +54 -29
  34. package/templates/app-source/src/product-modules/agent-realtime/index.tsx +2 -2
  35. package/templates/app-source/src/studio-modules/studio-create/runtime.ts +1 -0
  36. package/templates/app-source/src/studio-modules/studio-media/descriptors.ts +6 -1
  37. package/templates/app-source/src/studio-modules/studio-media/messages/en.json +19 -0
  38. package/templates/app-source/src/studio-modules/studio-media/messages/zh.json +19 -0
  39. package/templates/app-source/src/studio-modules/studio-media/registration.ts +10 -1
  40. package/templates/app-source/src/studio-modules/studio-media/runtime.ts +2 -0
  41. package/templates/app-source/src/studio-modules/studio-media/vision-parameters.tsx +18 -0
  42. package/templates/app-source/src/studio-modules/studio-media/vision-runtime.ts +58 -0
  43. package/templates/app-source/src/workbench-core/workbench-core.css +5 -0
  44. package/templates/app-source.manifest.json +16 -0
package/README.md CHANGED
@@ -79,13 +79,31 @@ The list shows the current project's registrations and creation times. Copy the
79
79
 
80
80
  The default `windows-x86_64` build profile runs `build:electron:production`. It rebuilds the renderer and Electron main/preload, then creates a fresh, non-installer `dist-electron-package/<app>-shell-win32-x64/` directory with `asar` disabled and an App-specific `<app>-shell.exe`. The production main bundle has a compile-time production marker and rejects every `--nimi-dev-renderer-url` argument; packaged renderer assets stay relative under `dist/`. The protected native binding is resolved from Kit's optional dependency and is never declared directly by the App.
81
81
 
82
+ App Tools 0.3 also prepares the `macos-aarch64` target on an Apple Silicon Mac.
83
+ The same owner command produces `dist-electron-package/<app>-shell-darwin-arm64/`
84
+ with a native `.app` bundle and a direct `Contents/MacOS` entry. The publisher's
85
+ build applies an ad-hoc integrity seal without a Developer ID identity or Apple
86
+ notarization; production pack observes that absence and rejects invalid seals.
87
+ Relative framework links are preserved inside the immutable payload. The App
88
+ continues to consume the macOS native binding through Kit's optional dependency.
89
+ Nimi installation never signs or repairs the publisher's code.
90
+
91
+ Existing `.nimi/config/build-profile.yaml` target choices are App-owned and are
92
+ preserved by sync. To add macOS, declare `macos-aarch64` with `os: macos`,
93
+ `arch: arm64`, the same production build command, the Darwin output directory
94
+ above as `payload_path`, and
95
+ `payload/<app>-shell.app/Contents/MacOS/<app>-shell` as `runtime_entry`.
96
+ The managed workflow resolves that declared target to `macos-15`; Windows keeps
97
+ its existing runner and profile. These authoring/build capabilities do not by
98
+ themselves establish Registry admission or a completed Desktop lifecycle.
99
+
82
100
  Tauri remains an explicit alternative through `pnpm run build:tauri:production`; selecting it requires an explicit Tauri build profile rather than changing the default Electron carrier.
83
101
 
84
102
  ## Canonical release boundary
85
103
 
86
- The publisher GitHub Release stage is available for configured repositories.
87
- Registry review, Runtime installation, and Desktop launch are separate owner
88
- stages:
104
+ The Registry publication chain uses the stages below. Publisher GitHub Release
105
+ is available for configured pilot repositories; protected Registry admission and
106
+ verified installation, update, launch and uninstall are available on Windows x86_64:
89
107
 
90
108
  ```text
91
109
  public App repository
@@ -101,7 +119,9 @@ public App repository
101
119
 
102
120
  The registry references publisher Release assets and never mirrors bytes. GitHub Release is not catalog admission; catalog admission is not installed; installed is not running; running is not Nimi Access ready.
103
121
 
104
- Repository administration must enable a protected `v*` tag ruleset and GitHub immutable releases before production. The managed tag workflow fetches the repository's canonical default branch and rejects a tag commit outside that history before production preflight, build, attestation, or Release. A fine-grained `NIMI_REPOSITORY_ADMIN_TOKEN` secret with repository Administration read permission lets the workflow verify protected-tag and immutable-release settings; it cannot enable or change them. Manual workflow dispatch runs only the non-production build/package path. On Windows, the tag-only production build invokes the App-declared production build with no certificate-secret mapping or app-tools-owned signing step. Optional native signing remains publisher-owned and must already be reflected in the final exact Runtime entry before production pack observes and records its native-trust posture; a present invalid or unresolved signature still fails closed. A successful tag workflow creates the immutable publisher GitHub Release and no registry, installed, running, or Nimi Access truth. Submit the immutable Release to the Registry review flow, then use a current Nimi Desktop build with verified Windows package support for installation and acceptance.
122
+ Repository administration must enable a protected `v*` tag ruleset and GitHub immutable releases before production. The managed tag workflow fetches the repository's canonical default branch and rejects a tag commit outside that history before production preflight, build, attestation, or Release. A fine-grained `NIMI_REPOSITORY_ADMIN_TOKEN` secret with repository Administration read permission lets the workflow verify protected-tag and immutable-release settings; it cannot enable or change them. Manual workflow dispatch runs only the non-production build/package path. On Windows, the tag-only production build invokes the App-declared production build with no certificate-secret mapping or app-tools-owned signing step. Optional native signing remains publisher-owned and must already be reflected in the final exact Runtime entry before production pack observes and records its native-trust posture; a present invalid or unresolved signature still fails closed. A successful tag workflow creates the immutable publisher GitHub Release and no registry, installed, running, or Nimi Access truth. Protected Registry submission and approved Windows x86_64 and macOS arm64 installation, update, launch/focus/stop, current-session Nimi Access and uninstall are available through their Platform, Runtime and Desktop owners. Other-platform installed lifecycle and ordinary repair remain unavailable. Explicit immutable local-package import has source-qualified Desktop and Runtime implementations on Windows x86_64 and macOS arm64; combined product acceptance and public release readiness remain unverified.
123
+
124
+ Registry projects must be open source with an explicit license and reviewable release source. Consistently observed unsigned packages are eligible; invalid signatures cannot be downgraded to unsigned. These Registry admission requirements do not apply to user-imported packages or Developer Mode projects. Registry approval is not a guarantee that third-party code is harmless.
105
125
 
106
126
  ## Publishing on GitHub
107
127
 
@@ -200,3 +220,68 @@ Published CLI usage is:
200
220
  ```bash
201
221
  pnpm dlx --package @nimiplatform/app-tools nimi-app --help
202
222
  ```
223
+
224
+ ## Portable App information (package v2)
225
+
226
+ A distribution package includes `app-info.json`, containing its actual icon,
227
+ summary, usage guide, version notes, license and portable requirements. Fill in
228
+ `nimi.app.yaml` before running a production check or build:
229
+
230
+ ```yaml
231
+ metadata:
232
+ summary: A short description of what your App helps people do.
233
+ icon: assets/app-icon.png
234
+ readme: README.md
235
+ release_notes: RELEASE_NOTES.md
236
+ author: Your team
237
+ homepage_url: https://example.com
238
+ support_url: https://example.com/support
239
+ capability_contract_refs: []
240
+ required_standardized_feature_refs: []
241
+ storage_policy:
242
+ kind: nimi-mediated-default
243
+ ```
244
+
245
+ Use the canonical requirement references your App needs; an explicitly empty
246
+ list is valid. Apps with their own OS storage must declare
247
+ `kind: app-owned-os-storage` and `os_storage_disclosure` entries containing
248
+ `path_pattern`, `purpose` and `expected_size_band`. These paths are disclosures,
249
+ not instructions for Nimi to delete files. The author, homepage and support
250
+ links are optional claims for local/private imports; Registry admission keeps
251
+ its independent public-source, open-source license and support requirements.
252
+
253
+ The icon must be a complete static PNG, square, 128–1024 pixels, no larger than
254
+ 512 KiB, and not fully transparent. Supply your App's real artwork: the old
255
+ 1×1 scaffold native icon is not distribution artwork. `metadata` paths are
256
+ relative to the App repository. README and version notes are optional for local or
257
+ private packages; omit their metadata paths when not provided. Registry admission
258
+ requires both documents. Supplied README is limited to 96 KiB, version notes to
259
+ 32 KiB, and the root LICENSE to 128 KiB. `package.json.license` supplies the
260
+ explicit license identifier; it does not turn a private license into an
261
+ open-source Registry license. Name and summary allow 120 and 280 characters.
262
+ Scaffold `sync` preserves these author-edited metadata, requirement and storage
263
+ fields while continuing to check the managed identity and carrier fields.
264
+ Incomplete development projects remain usable; production preflight reports
265
+ missing resources before invoking the build.
266
+
267
+ Pack writes `nimi.app-package/v2` and emits the exact embedded information bytes
268
+ as `<app_id>-<version>-<target_id>.app-info.json` next to the `.nimiapp` and
269
+ `.target.json`. Aggregate verifies both files and their equality with the
270
+ embedded document. The managed Release workflow uploads this sidecar; a Registry
271
+ candidate must reference its actual immutable Release asset identity, URL, size
272
+ and digest. No App icon or document is copied into Registry storage.
273
+
274
+ App Tools releases independently of SDK, Kit and Tauri shell. Its `nimiScaffoldVersions`
275
+ declares the tested public SDK, Kit and Tauri shell versions used by new Apps and
276
+ explicit `sync`; workspace development version bumps do not change those ranges.
277
+ The release workflow requires those public versions before publishing App Tools.
278
+
279
+ The v2 Runtime rejects v1 packages. Existing immutable publisher Releases and
280
+ approved descriptors must not be edited to invent the missing asset. Prepare a
281
+ new App version and real target builds, publish new immutable assets, and follow
282
+ normal Registry review. The coordinated pre-release Registry data cutover must
283
+ retire v1 entries/descriptors from the active dataset, retaining their history
284
+ in Git; adding v2 releases alone cannot make old descriptors satisfy the new
285
+ required-field schema. Do not deploy the v2 consumer before that reviewed
286
+ cutover is ready. Installed information is source-qualified and stored offline
287
+ by Runtime; metadata does not grant Registry verification or App Access.
@@ -1,9 +1,9 @@
1
+ import { APP_AUTHOR_DECLARATION_FIELDS, hashScaffoldManagedContent } from './app-scaffold.mjs';
1
2
  import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
2
3
  import path from 'node:path';
3
- import { parse as parseYaml } from 'yaml';
4
+ import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
4
5
  import {
5
6
  buildAppScaffoldSnapshotFromIntent,
6
- hashScaffoldContent,
7
7
  managedAppReleaseWorkflowSource,
8
8
  SCAFFOLD_INTENT_PATH,
9
9
  SCAFFOLD_LOCK_VERSION,
@@ -536,7 +536,7 @@ function assertManagedFilesCurrent(targetDir, lock) {
536
536
  drift.push(`${relativePath}: missing`);
537
537
  continue;
538
538
  }
539
- const currentHash = hashScaffoldContent(readContentForHash(absolutePath));
539
+ const currentHash = hashScaffoldManagedContent(relativePath, readContentForHash(absolutePath));
540
540
  if (currentHash !== entry.sha256) {
541
541
  drift.push(`${relativePath}: sha256 drift`);
542
542
  }
@@ -706,6 +706,15 @@ function assertNoClassificationConflict(lock, snapshot) {
706
706
  function writeScaffoldFile(targetDir, file) {
707
707
  const targetPath = path.join(targetDir, file.path);
708
708
  mkdirSync(path.dirname(targetPath), { recursive: true });
709
+ if (file.path === 'nimi.app.yaml' && existsSync(targetPath)) {
710
+ const current = parseYaml(readFileSync(targetPath, 'utf8'));
711
+ const next = parseYaml(file.content);
712
+ for (const field of APP_AUTHOR_DECLARATION_FIELDS) {
713
+ if (Object.hasOwn(current, field)) next[field] = current[field];
714
+ }
715
+ writeFileSync(targetPath, stringifyYaml(next, { lineWidth: 0 }));
716
+ return;
717
+ }
709
718
  writeFileSync(targetPath, file.content);
710
719
  }
711
720
 
@@ -0,0 +1,142 @@
1
+ // @nimi-authority: rule.nimi.platform.app-ecosystem.p-napp-042a
2
+ import { existsSync, lstatSync, readFileSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { PNG } from 'pngjs';
5
+ import { parse as parseYaml } from 'yaml';
6
+ import { normalizeAppAccessItems } from './app-access-declaration.mjs';
7
+
8
+ export const APP_INFO_MAX_BYTES = 1024 * 1024;
9
+ const PNG_SIGNATURE = Buffer.from('89504e470d0a1a0a', 'hex');
10
+
11
+ function text(value, label, max, multiline = false) {
12
+ if (typeof value !== 'string' || !value.trim() || value.includes('\0')
13
+ || (!multiline && (value !== value.trim() || /[\r\n]/u.test(value)))
14
+ || (multiline ? Buffer.byteLength(value) : [...value].length) > max) {
15
+ throw new Error(`App info ${label} must be nonempty and at most ${max} ${multiline ? 'bytes' : 'characters'}`);
16
+ }
17
+ return value;
18
+ }
19
+
20
+ function refs(value, label) {
21
+ if (!Array.isArray(value) || new Set(value).size !== value.length) {
22
+ throw new Error(`App info ${label} must be an explicit unique list (empty is allowed)`);
23
+ }
24
+ return value.map((item) => text(item, label, 200));
25
+ }
26
+
27
+ export function validateAppIcon(bytes) {
28
+ if (!Buffer.isBuffer(bytes) || bytes.length > 512 * 1024 || !bytes.subarray(0, 8).equals(PNG_SIGNATURE)) {
29
+ throw new Error('App icon must be a PNG of at most 512 KiB');
30
+ }
31
+ let offset = 8;
32
+ let ended = false;
33
+ while (offset + 12 <= bytes.length) {
34
+ const length = bytes.readUInt32BE(offset);
35
+ const type = bytes.toString('ascii', offset + 4, offset + 8);
36
+ if (offset + length + 12 > bytes.length || type === 'acTL') throw new Error('App icon must be a complete static PNG');
37
+ if (offset === 8 && (type !== 'IHDR' || length !== 13)) throw new Error('App icon PNG header is invalid');
38
+ if (type === 'IHDR') {
39
+ const width = bytes.readUInt32BE(offset + 8);
40
+ const height = bytes.readUInt32BE(offset + 12);
41
+ if (width < 128 || width > 1024 || width !== height) throw new Error('App icon must be square, 128–1024 pixels');
42
+ }
43
+ offset += length + 12;
44
+ if (type === 'IEND') { ended = length === 0 && offset === bytes.length; break; }
45
+ }
46
+ if (!ended) throw new Error('App icon PNG is truncated or has trailing content');
47
+ const decoded = PNG.sync.read(bytes, { checkCRC: true });
48
+ for (let index = 3; index < decoded.data.length; index += 4) {
49
+ if (decoded.data[index] !== 0) return bytes;
50
+ }
51
+ throw new Error('App icon is fully transparent; supply actual App artwork');
52
+ }
53
+
54
+ function storage(value) {
55
+ if (!value || !['nimi-mediated-default', 'app-owned-os-storage'].includes(value.kind)) {
56
+ throw new Error('App info storage_policy must declare its storage kind');
57
+ }
58
+ const disclosure = value.os_storage_disclosure;
59
+ if (value.kind === 'nimi-mediated-default') {
60
+ if (disclosure !== undefined && disclosure !== null) throw new Error('Mediated storage must not declare OS storage');
61
+ return { kind: value.kind, os_storage_disclosure: null };
62
+ }
63
+ if (!Array.isArray(disclosure) || disclosure.length === 0 || disclosure.length > 40) throw new Error('App-owned OS storage needs its path/purpose/size disclosure');
64
+ return { kind: value.kind, os_storage_disclosure: disclosure.map((item) => ({
65
+ path_pattern: text(item.path_pattern, 'storage path', 500),
66
+ purpose: text(item.purpose, 'storage purpose', 500),
67
+ expected_size_band: text(item.expected_size_band, 'storage size', 500),
68
+ })) };
69
+ }
70
+
71
+ function https(value, field) {
72
+ if (value === undefined || value === '') return '';
73
+ text(value, field, 2048);
74
+ const url = new URL(value);
75
+ if (url.protocol !== 'https:' || !url.hostname || url.username || url.password) throw new Error(`App info ${field} must be HTTPS without credentials`);
76
+ return value;
77
+ }
78
+
79
+ export function validateAppInfo(info) {
80
+ if (!info || info.format !== 'nimi.app-info/v1') throw new Error('Unsupported App info format');
81
+ for (const key of ['app_id', 'version', 'target_id']) text(info[key], key, 200);
82
+ text(info.display_name, 'display_name', 120);
83
+ text(info.summary, 'summary', 280);
84
+ if (info.icon?.media_type !== 'image/png' || typeof info.icon.data_base64 !== 'string') throw new Error('App info icon must declare PNG bytes');
85
+ const icon = Buffer.from(info.icon.data_base64, 'base64');
86
+ if (icon.toString('base64') !== info.icon.data_base64) throw new Error('App icon base64 is not canonical');
87
+ validateAppIcon(icon);
88
+ if (info.readme_markdown !== undefined && info.readme_markdown !== '') text(info.readme_markdown, 'readme', 96 * 1024, true);
89
+ if (info.release_notes_markdown !== undefined && info.release_notes_markdown !== '') text(info.release_notes_markdown, 'release notes', 32 * 1024, true);
90
+ text(info.license?.identifier, 'license identifier', 200);
91
+ text(info.license?.text, 'license text', 128 * 1024, true);
92
+ refs(info.app_access, 'app_access');
93
+ normalizeAppAccessItems(info.app_access);
94
+ refs(info.capability_contract_refs, 'capability_contract_refs');
95
+ refs(info.required_standardized_feature_refs, 'required_standardized_feature_refs');
96
+ storage(info.storage_policy);
97
+ if (info.author) text(info.author, 'author', 200);
98
+ https(info.homepage_url, 'homepage_url');
99
+ https(info.support_url, 'support_url');
100
+ if (Buffer.byteLength(JSON.stringify(info)) > APP_INFO_MAX_BYTES) throw new Error('App info exceeds 1 MiB');
101
+ return info;
102
+ }
103
+
104
+ function resource(root, relative, label, maxBytes) {
105
+ if (typeof relative !== 'string' || path.isAbsolute(relative) || relative.includes('\\')
106
+ || relative.split('/').some((part) => !part || part === '.' || part === '..')) throw new Error(`metadata.${label} must name an App-relative resource`);
107
+ const file = path.join(root, relative);
108
+ const stat = lstatSync(file);
109
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size === 0 || stat.size > maxBytes) throw new Error(`metadata.${label} is missing, not a regular file, or exceeds its size limit`);
110
+ return readFileSync(file);
111
+ }
112
+
113
+ export function readAppInfo(root, targetId) {
114
+ const manifest = parseYaml(readFileSync(path.join(root, 'nimi.app.yaml'), 'utf8'));
115
+ const pkg = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8'));
116
+ if (manifest.version !== pkg.version) throw new Error('package.json and nimi.app.yaml versions must be exact and lockstep before distribution');
117
+ const metadata = manifest.metadata;
118
+ if (!metadata || typeof metadata !== 'object') throw new Error('nimi.app.yaml metadata is required for distribution (summary, icon)');
119
+ const readText = (relative, label, max) => new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(resource(root, relative, label, max));
120
+ const info = validateAppInfo({
121
+ format: 'nimi.app-info/v1', app_id: manifest.app_id, version: manifest.version, target_id: targetId,
122
+ display_name: manifest.display_name, summary: metadata.summary,
123
+ icon: { media_type: 'image/png', data_base64: validateAppIcon(resource(root, metadata.icon, 'icon', 512 * 1024)).toString('base64') },
124
+ readme_markdown: metadata.readme === undefined ? '' : readText(metadata.readme, 'readme', 96 * 1024),
125
+ release_notes_markdown: metadata.release_notes === undefined ? '' : readText(metadata.release_notes, 'release_notes', 32 * 1024),
126
+ license: { identifier: pkg.license, text: readText('LICENSE', 'license', 128 * 1024) },
127
+ app_access: refs(manifest.app_access, 'app_access'),
128
+ capability_contract_refs: refs(manifest.capability_contract_refs, 'capability_contract_refs'),
129
+ required_standardized_feature_refs: refs(manifest.required_standardized_feature_refs, 'required_standardized_feature_refs'),
130
+ storage_policy: storage(manifest.storage_policy),
131
+ author: metadata.author || '', homepage_url: https(metadata.homepage_url, 'homepage_url'), support_url: https(metadata.support_url, 'support_url'),
132
+ });
133
+ const submissionPath = path.join(root, '.nimi/admission/submission.yaml');
134
+ if (existsSync(submissionPath)) {
135
+ const submission = parseYaml(readFileSync(submissionPath, 'utf8'));
136
+ for (const field of ['app_id', 'version', 'display_name', 'capability_contract_refs', 'required_standardized_feature_refs']) {
137
+ if (JSON.stringify(info[field]) !== JSON.stringify(submission[field])) throw new Error(`App info differs from submission ${field}; run nimi-app sync to project the declaration`);
138
+ }
139
+ if (JSON.stringify(storage(submission.storage_policy)) !== JSON.stringify(info.storage_policy)) throw new Error('App info differs from submission storage_policy; run nimi-app sync to project the declaration');
140
+ }
141
+ return info;
142
+ }
package/lib/app-pack.mjs CHANGED
@@ -12,13 +12,17 @@ import {
12
12
  mkdirSync,
13
13
  readFileSync,
14
14
  readdirSync,
15
+ readlinkSync,
15
16
  writeFileSync,
16
17
  } from 'node:fs';
17
18
  import path from 'node:path';
18
- import { parse as parseYaml } from 'yaml';
19
+ import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
20
+ import { APP_INFO_MAX_BYTES, readAppInfo, validateAppInfo } from './app-info.mjs';
19
21
  import { observeWindowsExecutableFacts } from './windows-powershell.mjs';
22
+ import { SYMBOLIC_LINK_MODE, validatePayloadLinks } from './payload-links.mjs';
23
+ import { observeMacOSExecutableFacts } from './macos-native.mjs';
20
24
 
21
- const PACKAGE_FORMAT = 'nimi.app-package/v1';
25
+ const PACKAGE_FORMAT = 'nimi.app-package/v2';
22
26
  const TARGET_METADATA_FORMAT = 'nimi.app-target-candidate/v1';
23
27
  const AGGREGATE_FORMAT = 'nimi.app-release-candidate/v1';
24
28
  const BUILD_PROFILE_PATH = '.nimi/config/build-profile.yaml';
@@ -28,6 +32,7 @@ const OUTPUT_DIR = 'dist/nimi-app';
28
32
  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;
29
33
  const TARGETS = Object.freeze({
30
34
  'windows-x86_64': Object.freeze({ os: 'windows', arch: 'x86_64' }),
35
+ 'macos-aarch64': Object.freeze({ os: 'macos', arch: 'arm64' }),
31
36
  });
32
37
 
33
38
  function compareText(left, right) {
@@ -103,7 +108,7 @@ function readCargoPackageVersion(source) {
103
108
  throw new Error('src-tauri/Cargo.toml [package] version is missing');
104
109
  }
105
110
 
106
- function collectPayload(payloadPath) {
111
+ function collectPayload(payloadPath, os) {
107
112
  const stat = lstatSync(payloadPath);
108
113
  if (stat.isSymbolicLink()) throw new Error('Pack payload must not contain symbolic links');
109
114
  if (stat.isFile()) {
@@ -116,8 +121,10 @@ function collectPayload(payloadPath) {
116
121
  const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
117
122
  const absolute = path.join(current, entry.name);
118
123
  const entryStat = lstatSync(absolute);
119
- if (entryStat.isSymbolicLink()) throw new Error(`Pack payload must not contain symbolic links: ${relative}`);
120
- if (entryStat.isDirectory()) {
124
+ if (entryStat.isSymbolicLink()) {
125
+ if (os !== 'macos') throw new Error(`Pack payload must not contain symbolic links: ${relative}`);
126
+ entries.push({ relative, bytes: Buffer.from(readlinkSync(absolute)), mode: SYMBOLIC_LINK_MODE });
127
+ } else if (entryStat.isDirectory()) {
121
128
  walk(absolute, relative);
122
129
  } else if (entryStat.isFile()) {
123
130
  entries.push({ relative, bytes: readFileSync(absolute), mode: entryStat.mode & 0o111 ? 0o755 : 0o644 });
@@ -157,7 +164,7 @@ export function writeNimiAppArchive(entries) {
157
164
  const normalized = entries.map((entry) => ({
158
165
  name: zipEntryName(entry.name),
159
166
  bytes: Buffer.isBuffer(entry.bytes) ? entry.bytes : Buffer.from(entry.bytes),
160
- mode: entry.mode === 0o755 ? 0o755 : 0o644,
167
+ mode: entry.mode === SYMBOLIC_LINK_MODE ? SYMBOLIC_LINK_MODE : entry.mode === 0o755 ? 0o755 : 0o644,
161
168
  })).sort((left, right) => compareText(left.name, right.name));
162
169
  if (normalized.length === 0) throw new Error('nimiapp archive requires at least one file');
163
170
  if (new Set(normalized.map((entry) => entry.name)).size !== normalized.length) throw new Error('nimiapp archive entries must be unique');
@@ -199,7 +206,7 @@ export function writeNimiAppArchive(entries) {
199
206
  central.writeUInt16LE(0, 32);
200
207
  central.writeUInt16LE(0, 34);
201
208
  central.writeUInt16LE(0, 36);
202
- central.writeUInt32LE(((0o100000 | entry.mode) << 16) >>> 0, 38);
209
+ central.writeUInt32LE(((entry.mode === SYMBOLIC_LINK_MODE ? entry.mode : 0o100000 | entry.mode) << 16) >>> 0, 38);
203
210
  central.writeUInt32LE(offset, 42);
204
211
  centralParts.push(central, name);
205
212
  offset += local.length + name.length + entry.bytes.length;
@@ -236,9 +243,10 @@ export function readNimiAppArchive(bytes) {
236
243
  const extraLength = archive.readUInt16LE(cursor + 30);
237
244
  const commentLength = archive.readUInt16LE(cursor + 32);
238
245
  const localOffset = archive.readUInt32LE(cursor + 42);
239
- const mode = (archive.readUInt32LE(cursor + 38) >>> 16) & 0o777;
246
+ const unixMode = archive.readUInt32LE(cursor + 38) >>> 16;
247
+ const mode = (unixMode & 0o170000) === 0o120000 ? unixMode : unixMode & 0o777;
240
248
  if (method !== 0 || extraLength !== 0 || commentLength !== 0) throw new Error('Unsupported nimiapp ZIP entry encoding');
241
- if (mode !== 0o644 && mode !== 0o755) throw new Error('Unsupported nimiapp ZIP entry mode');
249
+ if (mode !== 0o644 && mode !== 0o755 && mode !== SYMBOLIC_LINK_MODE) throw new Error('Unsupported nimiapp ZIP entry mode');
242
250
  const name = zipEntryName(archive.subarray(cursor + 46, cursor + 46 + nameLength).toString('utf8'));
243
251
  if (entries.has(name) || archive.readUInt32LE(localOffset) !== 0x04034b50) throw new Error('Invalid or duplicate nimiapp ZIP entry');
244
252
  const localNameLength = archive.readUInt16LE(localOffset + 26);
@@ -271,6 +279,7 @@ function readPackInputs(targetDir, targetId) {
271
279
  }
272
280
  const manifestPath = path.join(targetDir, 'nimi.app.yaml');
273
281
  const manifest = readYaml(manifestPath, 'nimi.app.yaml');
282
+ const appInfo = readAppInfo(targetDir, targetId);
274
283
  const buildProfile = readYaml(path.join(targetDir, BUILD_PROFILE_PATH), BUILD_PROFILE_PATH);
275
284
  const buildProfileRef = buildProfile.build_profile_ref;
276
285
  if (buildProfileRef !== ELECTRON_BUILD_PROFILE_REF && buildProfileRef !== TAURI_BUILD_PROFILE_REF) {
@@ -308,7 +317,7 @@ function readPackInputs(targetDir, targetId) {
308
317
  const runtimeHostPath = payloadStat.isFile()
309
318
  ? payload.resolved
310
319
  : resolveInside(payload.resolved, runtimeRelative, `targets.${targetId}.runtime_entry`).resolved;
311
- return { target, targetId, targetDir, packageJson, licensePath, manifestPath, appId, version, payloadPath: payload.resolved, runtimeEntry, runtimeHostPath };
320
+ return { target, targetId, targetDir, packageJson, licensePath, manifestPath, appInfo, appId, version, payloadPath: payload.resolved, runtimeEntry, runtimeHostPath };
312
321
  }
313
322
 
314
323
  export function classifyWindowsNativeTrustObservation(observation) {
@@ -358,10 +367,15 @@ function resolveTargetFacts(input, production, archivedRuntimeEntryBytes) {
358
367
  executionProfile: null,
359
368
  };
360
369
  }
370
+ if (input.target.os === 'macos') {
371
+ const facts = observeMacOSExecutableFacts(input.runtimeHostPath);
372
+ if (!archivedRuntimeEntryBytes.equals(readFileSync(input.runtimeHostPath))) throw new Error('Production Runtime entry changed during macOS native observation');
373
+ return facts;
374
+ }
361
375
  return observeProductionWindowsFacts(input, archivedRuntimeEntryBytes);
362
376
  }
363
377
 
364
- function validateNativeExecutionFacts(nativeTrust, executionProfile, label) {
378
+ function validateNativeExecutionFacts(nativeTrust, executionProfile, label, os) {
365
379
  if (!nativeTrust || typeof nativeTrust !== 'object' || Array.isArray(nativeTrust)) {
366
380
  throw new Error(`${label} native_trust must be an object`);
367
381
  }
@@ -371,6 +385,13 @@ function validateNativeExecutionFacts(nativeTrust, executionProfile, label) {
371
385
  }
372
386
  return;
373
387
  }
388
+ if (os === 'macos') {
389
+ if (!executionProfile || Object.keys(executionProfile).join(',') !== 'launch_mode' || executionProfile.launch_mode !== 'current-user') throw new Error(`${label} macOS execution_profile must use current-user launch`);
390
+ if (Object.keys(nativeTrust).sort().join(',') !== 'certificate_subject,macos_developer_id,macos_notarization,posture') throw new Error(`${label} macOS native_trust is inconsistent`);
391
+ if (nativeTrust.posture === 'production-unsigned' && nativeTrust.macos_developer_id === 'absent' && nativeTrust.macos_notarization === 'absent' && nativeTrust.certificate_subject === null) return;
392
+ if (nativeTrust.posture === 'observed-valid-native-signature' && nativeTrust.macos_developer_id === 'valid' && ['absent', 'notarized'].includes(nativeTrust.macos_notarization) && typeof nativeTrust.certificate_subject === 'string' && nativeTrust.certificate_subject.trim() === nativeTrust.certificate_subject && nativeTrust.certificate_subject) return;
393
+ throw new Error(`${label} macOS native_trust posture is inconsistent`);
394
+ }
374
395
  if (
375
396
  !executionProfile
376
397
  || typeof executionProfile !== 'object'
@@ -423,10 +444,12 @@ export function packAppTarget(cwd, options = {}) {
423
444
  const targetId = String(options.target || '').trim();
424
445
  if (!targetId) throw new Error('nimi-app pack requires --target');
425
446
  const input = readPackInputs(targetDir, targetId);
426
- const payloadEntries = collectPayload(input.payloadPath).map((entry) => {
447
+ const payloadEntries = collectPayload(input.payloadPath, input.target.os).map((entry) => {
427
448
  const name = `payload/${entry.relative.replaceAll('\\', '/')}`;
449
+ if (name === input.runtimeEntry && entry.mode === SYMBOLIC_LINK_MODE) throw new Error('Runtime entry must be a direct regular file');
428
450
  return { name, bytes: entry.bytes, mode: name === input.runtimeEntry ? 0o755 : entry.mode };
429
451
  });
452
+ validatePayloadLinks(new Map(payloadEntries.map((entry) => [entry.name, entry])), input.target.os);
430
453
  const runtimeEntry = payloadEntries.find((entry) => entry.name === input.runtimeEntry);
431
454
  if (!runtimeEntry) throw new Error(`runtime_entry is missing from target payload: ${input.runtimeEntry}`);
432
455
  const { nativeTrust, executionProfile } = resolveTargetFacts(input, options.production === true, runtimeEntry.bytes);
@@ -441,10 +464,14 @@ export function packAppTarget(cwd, options = {}) {
441
464
  native_trust: nativeTrust,
442
465
  execution_profile: executionProfile,
443
466
  };
467
+ const infoBytes = Buffer.from(canonicalJson(input.appInfo));
468
+ if (infoBytes.length > APP_INFO_MAX_BYTES) throw new Error('App info exceeds 1 MiB');
469
+ const declaration = Object.fromEntries(['app_id', 'display_name', 'version', 'app_access', 'capability_contract_refs', 'required_standardized_feature_refs', 'storage_policy'].map((key) => [key, input.appInfo[key]]));
444
470
  const archive = writeNimiAppArchive([
445
471
  { name: 'LICENSE', bytes: readFileSync(input.licensePath), mode: 0o644 },
446
472
  { name: 'manifest.json', bytes: canonicalJson(packageManifest), mode: 0o644 },
447
- { name: 'nimi.app.yaml', bytes: readFileSync(input.manifestPath), mode: 0o644 },
473
+ { name: 'nimi.app.yaml', bytes: stringifyYaml(declaration), mode: 0o644 },
474
+ { name: 'app-info.json', bytes: infoBytes, mode: 0o644 },
448
475
  ...payloadEntries,
449
476
  ]);
450
477
  const sha256 = createHash('sha256').update(archive).digest('hex');
@@ -453,7 +480,9 @@ export function packAppTarget(cwd, options = {}) {
453
480
  const stem = `${input.appId}-${input.version}-${input.targetId}`;
454
481
  const artifactPath = path.join(outputDir, `${stem}.nimiapp`);
455
482
  const metadataPath = path.join(outputDir, `${stem}.target.json`);
483
+ const appInfoPath = path.join(outputDir, `${stem}.app-info.json`);
456
484
  writeFileSync(artifactPath, archive);
485
+ writeFileSync(appInfoPath, infoBytes);
457
486
  const metadata = {
458
487
  format: TARGET_METADATA_FORMAT,
459
488
  app_id: input.appId,
@@ -464,12 +493,13 @@ export function packAppTarget(cwd, options = {}) {
464
493
  asset_name: path.basename(artifactPath),
465
494
  size: archive.length,
466
495
  sha256,
496
+ app_info: { asset_name: path.basename(appInfoPath), size: infoBytes.length, sha256: createHash('sha256').update(infoBytes).digest('hex') },
467
497
  runtime_entry: input.runtimeEntry,
468
498
  native_trust: packageManifest.native_trust,
469
499
  execution_profile: packageManifest.execution_profile,
470
500
  };
471
501
  writeFileSync(metadataPath, canonicalJson(metadata));
472
- return { ok: true, command: 'pack', dir: targetDir, artifactPath, metadataPath, ...metadata };
502
+ return { ok: true, command: 'pack', dir: targetDir, artifactPath, metadataPath, appInfoPath, ...metadata };
473
503
  }
474
504
 
475
505
  export function aggregateAppTargetCandidates(cwd, options = {}) {
@@ -498,12 +528,19 @@ export function aggregateAppTargetCandidates(cwd, options = {}) {
498
528
  }
499
529
  const runtimeEntry = canonicalRelative(target.runtime_entry, `${metadataLabel}.runtime_entry`);
500
530
  if (!runtimeEntry.startsWith('payload/')) throw new Error(`Target runtime_entry must resolve inside payload: ${runtimeEntry}`);
501
- validateNativeExecutionFacts(target.native_trust, target.execution_profile, metadataLabel);
531
+ validateNativeExecutionFacts(target.native_trust, target.execution_profile, metadataLabel, target.os);
502
532
  const artifactPath = path.join(outputDir, assetName);
503
533
  if (!existsSync(artifactPath)) throw new Error(`Target artifact is missing: ${target.asset_name}`);
504
534
  const bytes = readFileSync(artifactPath);
505
535
  if (bytes.length !== target.size || createHash('sha256').update(bytes).digest('hex') !== target.sha256) throw new Error(`Target artifact changed after pack: ${target.asset_name}`);
506
536
  const entries = readNimiAppArchive(bytes);
537
+ const infoAsset = target.app_info;
538
+ if (infoAsset?.asset_name !== `${appId}-${version}-${target.target_id}.app-info.json` || !Number.isSafeInteger(infoAsset.size) || infoAsset.size <= 0 || infoAsset.size > APP_INFO_MAX_BYTES) throw new Error(`Target App info reference is invalid: ${target.target_id}`);
539
+ const infoBytes = readFileSync(path.join(outputDir, infoAsset.asset_name));
540
+ if (infoBytes.length !== infoAsset.size || createHash('sha256').update(infoBytes).digest('hex') !== infoAsset.sha256 || !entries.get('app-info.json')?.bytes.equals(infoBytes)) throw new Error(`Target App info changed or differs from archive: ${target.target_id}`);
541
+ const info = validateAppInfo(JSON.parse(infoBytes));
542
+ if (info.app_id !== appId || info.version !== version || info.target_id !== target.target_id) throw new Error(`Target App info identity differs: ${target.target_id}`);
543
+ validatePayloadLinks(entries, target.os);
507
544
  const manifest = readPackageManifestFromArchive(entries, metadataLabel);
508
545
  if (manifest.format !== PACKAGE_FORMAT) throw new Error(`Target archive manifest format is invalid: ${target.asset_name}`);
509
546
  for (const field of ['app_id', 'version', 'target_id', 'os', 'arch', 'runtime_entry', 'native_trust', 'execution_profile']) {
@@ -511,7 +548,7 @@ export function aggregateAppTargetCandidates(cwd, options = {}) {
511
548
  throw new Error(`Target metadata does not match archive manifest ${field}: ${target.asset_name}`);
512
549
  }
513
550
  }
514
- validateNativeExecutionFacts(manifest.native_trust, manifest.execution_profile, `${target.asset_name} archive manifest`);
551
+ validateNativeExecutionFacts(manifest.native_trust, manifest.execution_profile, `${target.asset_name} archive manifest`, target.os);
515
552
  const runtimeEntryArchive = entries.get(runtimeEntry);
516
553
  if (!runtimeEntryArchive || runtimeEntryArchive.mode !== 0o755) {
517
554
  throw new Error(`Target archive runtime_entry is missing or non-executable: ${runtimeEntry}`);
@@ -1,3 +1,4 @@
1
+ import { readAppInfo } from './app-info.mjs';
1
2
  // @nimi-authority: rule.nimi.platform.app-ecosystem.p-scaf-018c
2
3
  // @nimi-authority: rule.nimi.platform.app-ecosystem.p-napp-009b
3
4
 
@@ -46,6 +47,7 @@ const SUBMISSION_PATH = '.nimi/admission/submission.yaml';
46
47
  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;
47
48
  const CURRENT_APP_TARGETS = Object.freeze({
48
49
  'windows-x86_64': Object.freeze({ os: 'windows', arch: 'x86_64' }),
50
+ 'macos-aarch64': Object.freeze({ os: 'macos', arch: 'arm64' }),
49
51
  });
50
52
 
51
53
  function resolveTargetDir(cwd, options = {}) {
@@ -116,7 +118,7 @@ function readSubmittedManifest(targetDir) {
116
118
  if (!SEMVER_PATTERN.test(version) || version !== document.version) {
117
119
  throw new Error('Existing submitted app version must be an exact semantic version');
118
120
  }
119
- return Object.freeze({ appId, displayName, profile, version, rendererOrigin: parsedOrigin.origin });
121
+ return Object.freeze({ appId, displayName, profile, version, rendererOrigin: parsedOrigin.origin, capabilityContractRefs: document.capability_contract_refs, requiredStandardizedFeatureRefs: document.required_standardized_feature_refs, storagePolicy: document.storage_policy });
120
122
  }
121
123
 
122
124
  function assertNoRetiredScaffoldState(targetDir) {
@@ -942,17 +944,6 @@ function assertProjectLifecycleCurrent(targetDir, versions, options = {}) {
942
944
  }
943
945
  assertNoStandaloneParentSources(targetDir);
944
946
  const authoring = assertCanonicalAuthoringInputs(targetDir, descriptor, files, version, nativeIdentity);
945
- if (existsSync(path.join(targetDir, SCAFFOLD_LOCK_PATH))) {
946
- const lock = readJsonFile(path.join(targetDir, SCAFFOLD_LOCK_PATH), 'scaffold lock');
947
- for (const [field, expected] of [
948
- ['capability_contract_refs', lock.capabilityContractRefs],
949
- ['required_standardized_feature_refs', lock.requiredStandardizedFeatureRefs],
950
- ]) {
951
- if (JSON.stringify(authoring.submission[field]) !== JSON.stringify(expected || [])) {
952
- throw new Error(`${SUBMISSION_PATH} ${field} must match the selected scaffold feature closure`);
953
- }
954
- }
955
- }
956
947
  assertManagedWorkflowCurrent(targetDir);
957
948
  assertPnpmWorkspaceCurrent(targetDir);
958
949
  if (options.requireInstalledLock === true) {
@@ -1032,10 +1023,10 @@ function buildExistingSubmittedAppSyncPlan(targetDir, versions) {
1032
1023
  supportManifest = normalizeSupportInput(currentSubmission.support_manifest, `${SUBMISSION_PATH} support_manifest`);
1033
1024
  }
1034
1025
  const submissionContent = renderAppSubmissionInput(identity, {
1035
- capabilityContractRefs: currentSubmission?.capability_contract_refs || [],
1036
- requiredStandardizedFeatureRefs: currentSubmission?.required_standardized_feature_refs || [],
1026
+ capabilityContractRefs: descriptor.capabilityContractRefs ?? currentSubmission?.capability_contract_refs ?? [],
1027
+ requiredStandardizedFeatureRefs: descriptor.requiredStandardizedFeatureRefs ?? currentSubmission?.required_standardized_feature_refs ?? [],
1037
1028
  aiProfileRecommendationRef: currentSubmission?.ai_profile_recommendation_ref,
1038
- storagePolicy: currentSubmission?.storage_policy || { kind: 'nimi-mediated-default' },
1029
+ storagePolicy: descriptor.storagePolicy ?? currentSubmission?.storage_policy ?? { kind: 'nimi-mediated-default' },
1039
1030
  supportManifest,
1040
1031
  });
1041
1032
  planned.push({ path: submissionPath, content: submissionContent, previous: currentSubmissionSource });
@@ -1160,6 +1151,9 @@ export function checkAppProject(cwd, options = {}, versions, runners = {}) {
1160
1151
  let nimicoding = null;
1161
1152
  if (!managed) nimicoding = runNimicodingSync(targetDir, 'check', runners);
1162
1153
  const { descriptor, buildProfile } = assertProjectLifecycleCurrent(targetDir, versions, { requireInstalledLock: true });
1154
+ if (options.production === true) {
1155
+ for (const target of Object.keys(buildProfile.targets)) readAppInfo(targetDir, target);
1156
+ }
1163
1157
  return emitResult({
1164
1158
  ok: true,
1165
1159
  command: 'check',
@@ -1192,6 +1186,7 @@ export function buildAppProject(cwd, options = {}, runners = {}) {
1192
1186
  const targetDir = resolveTargetDir(cwd, options);
1193
1187
  const profile = readBuildProfile(targetDir);
1194
1188
  const selected = selectBuildOwner(profile, options.target);
1189
+ if (options.production === true) readAppInfo(targetDir, selected.target);
1195
1190
  const result = runOwnerCommand(targetDir, 'build', selected.command, options, runners);
1196
1191
  if (options.production === true) {
1197
1192
  assertProductionRuntimeEntry(targetDir, selected);