@nimiplatform/app-tools 0.3.0 → 0.5.1

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.
package/README.md CHANGED
@@ -119,7 +119,7 @@ public App repository
119
119
 
120
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.
121
121
 
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 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 remains a separate product path whose entry is not yet implemented.
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
123
 
124
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.
125
125
 
@@ -220,3 +220,86 @@ Published CLI usage is:
220
220
  ```bash
221
221
  pnpm dlx --package @nimiplatform/app-tools nimi-app --help
222
222
  ```
223
+
224
+ ## Portable App information (package v2)
225
+
226
+ A distribution package includes `app-info.json`, containing its actual icon,
227
+ summary, available usage guide and version notes, license and portable requirements.
228
+ Every `pack`, including development-mode packaging and non-release CI, requires
229
+ valid App information. Complete `nimi.app.yaml` and its resources before packing;
230
+ production check/build validates them before the build starts:
231
+
232
+ ```yaml
233
+ metadata:
234
+ summary: A short description of what your App helps people do.
235
+ icon: assets/app-icon.png
236
+ readme: README.md
237
+ release_notes: RELEASE_NOTES.md
238
+ author: Your team
239
+ homepage_url: https://example.com
240
+ support_url: https://example.com/support
241
+ capability_contract_refs: []
242
+ required_standardized_feature_refs: []
243
+ storage_policy:
244
+ kind: nimi-mediated-default
245
+ ```
246
+
247
+ Use the canonical requirement references your App needs; an explicitly empty
248
+ list is valid. Apps with their own OS storage must declare
249
+ `kind: app-owned-os-storage` and `os_storage_disclosure` entries containing
250
+ `path_pattern`, `purpose` and `expected_size_band`. These paths are disclosures,
251
+ not instructions for Nimi to delete files. The author, homepage and support
252
+ links are optional claims for local/private imports; Registry admission keeps
253
+ its independent public-source, open-source license and support requirements.
254
+
255
+ The icon must be a complete static PNG, square, 128–1024 pixels, no larger than
256
+ 512 KiB, and not fully transparent. Supply your App's real artwork: the old
257
+ 1×1 scaffold native icon is not distribution artwork. `metadata` paths are
258
+ relative to the App repository. README and version notes are optional for local or
259
+ private packages; omit their metadata paths when not provided. Registry admission
260
+ requires both documents. Supplied README is limited to 96 KiB, version notes to
261
+ 32 KiB, and the root LICENSE to 128 KiB. `package.json.license` supplies the
262
+ explicit license identifier; it does not turn a private license into an
263
+ open-source Registry license. Name and summary allow 120 and 280 characters.
264
+ Scaffold `sync` preserves these author-edited metadata, requirement and storage
265
+ fields while continuing to check the managed identity and carrier fields.
266
+ The scaffold does not supply finished artwork. Add the declared icon, a summary
267
+ and license information; provide any declared documents or omit optional document
268
+ paths for local/private packages. Until then, package-producing CI will fail.
269
+ Incomplete projects remain editable with `dev` and ordinary non-production builds.
270
+
271
+ Pack writes `nimi.app-package/v2` and emits the exact embedded information bytes
272
+ as `<app_id>-<version>-<target_id>.app-info.json` next to the `.nimiapp` and
273
+ `.target.json`. Aggregate verifies both files and their equality with the
274
+ embedded document. The managed Release workflow uploads this sidecar; a Registry
275
+ candidate must reference its actual immutable Release asset identity, URL, size
276
+ and digest. No App icon or document is copied into Registry storage.
277
+
278
+ App Tools releases independently of SDK, Kit and Tauri shell. Its `nimiScaffoldVersions`
279
+ declares the tested public SDK, Kit and Tauri shell versions used by new Apps and
280
+ explicit `sync`; workspace development version bumps do not change those ranges.
281
+ The release workflow requires those public versions before publishing App Tools.
282
+
283
+ App Tools 0.5.1 uses SDK `^0.11.0` and Kit `^0.7.0`. Existing Apps upgrade explicitly:
284
+
285
+ ```bash
286
+ pnpm add -D @nimiplatform/app-tools@^0.5.1
287
+ pnpm run sync
288
+ pnpm install
289
+ pnpm run check
290
+ pnpm run test
291
+ pnpm run app:build -- --target windows-x86_64
292
+ ```
293
+
294
+ Use the App's declared target for the final build. `sync` preserves App-owned
295
+ product code; update any affected SDK/Kit API usage in that code before release.
296
+
297
+ The v2 Runtime rejects v1 packages. Existing immutable publisher Releases and
298
+ approved descriptors must not be edited to invent the missing asset. Prepare a
299
+ new App version and real target builds, publish new immutable assets, and follow
300
+ normal Registry review. The coordinated pre-release Registry data cutover must
301
+ retire v1 entries/descriptors from the active dataset, retaining their history
302
+ in Git; adding v2 releases alone cannot make old descriptors satisfy the new
303
+ required-field schema. Do not deploy the v2 consumer before that reviewed
304
+ cutover is ready. Installed information is source-qualified and stored offline
305
+ 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,
@@ -345,6 +345,7 @@ function buildForbiddenPatterns() {
345
345
  ];
346
346
  }
347
347
 
348
+ // @nimi-authority: rule.nimi.platform.app-ecosystem.p-scaf-016b
348
349
  function scanForbiddenPatterns(targetDir, profile, selectedLabels = null) {
349
350
  const findings = [];
350
351
  const patterns = buildForbiddenPatterns();
@@ -366,12 +367,15 @@ function scanForbiddenPatterns(targetDir, profile, selectedLabels = null) {
366
367
  const text = readFileSync(filePath, 'utf8');
367
368
  const isManagedReleaseWorkflow = relativePath === '.github/workflows/nimi-app-release.yml'
368
369
  && text.replaceAll('\r\n', '\n') === managedAppReleaseWorkflowSource();
369
- const isTestFile = relativePath.startsWith('test/') || /(?:^|\/)\w[^/]*\.(?:test|spec)\.[cm]?[jt]sx?$/i.test(relativePath);
370
+ const isTestFile = /^(?:test|tests)\//.test(relativePath) || /(?:^|\/)\w[^/]*\.(?:test|spec)\.[cm]?[jt]sx?$/i.test(relativePath);
371
+ const isAgentSkillReference = /^(?:\.agents|\.claude)\/skills\//.test(relativePath);
370
372
  for (const [label, pattern] of patterns) {
371
373
  if (selectedLabels && !selectedLabels.has(label)) {
372
374
  continue;
373
375
  }
374
- if (selectedLabels && isTestFile) {
376
+ // Existing repositories may vendor agent skills and their example code.
377
+ // Those examples and test fixtures are not the App's protected callers.
378
+ if (selectedLabels && (isTestFile || isAgentSkillReference)) {
375
379
  continue;
376
380
  }
377
381
  // Test files reference provider/model names to assert behavior (including
@@ -536,7 +540,7 @@ function assertManagedFilesCurrent(targetDir, lock) {
536
540
  drift.push(`${relativePath}: missing`);
537
541
  continue;
538
542
  }
539
- const currentHash = hashScaffoldContent(readContentForHash(absolutePath));
543
+ const currentHash = hashScaffoldManagedContent(relativePath, readContentForHash(absolutePath));
540
544
  if (currentHash !== entry.sha256) {
541
545
  drift.push(`${relativePath}: sha256 drift`);
542
546
  }
@@ -609,13 +613,14 @@ function validateExistingSubmittedApp(targetDir) {
609
613
  export function initApp(cwd, options = {}, versions, runners = {}) {
610
614
  const targetDir = resolveTargetDir(cwd, options);
611
615
  const intent = readIntent(targetDir);
616
+ const currentManifest = readCurrentAppManifest(targetDir);
612
617
  const snapshot = buildAppScaffoldSnapshotFromIntent({ intent, versions, targetDir });
613
618
  if (!runners?.runNimicodingSync) {
614
619
  throw new Error('Missing nimicoding sync runner');
615
620
  }
616
621
  const nimicoding = runners.runNimicodingSync(targetDir, 'apply');
617
622
  for (const file of snapshot.initFiles) {
618
- writeScaffoldFile(targetDir, file);
623
+ writeScaffoldFile(targetDir, file, currentManifest);
619
624
  }
620
625
  validateAppProjectState(targetDir, versions, runners);
621
626
  const payload = {
@@ -703,9 +708,29 @@ function assertNoClassificationConflict(lock, snapshot) {
703
708
  }
704
709
  }
705
710
 
706
- function writeScaffoldFile(targetDir, file) {
711
+ function readCurrentAppManifest(targetDir) {
712
+ const manifestPath = path.join(targetDir, 'nimi.app.yaml');
713
+ if (!existsSync(manifestPath)) return undefined;
714
+ let manifest;
715
+ try { manifest = parseYaml(readFileSync(manifestPath, 'utf8')); }
716
+ catch (error) { throw new Error(`nimi.app.yaml is invalid: ${error.message}`, { cause: error }); }
717
+ if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) {
718
+ throw new Error('nimi.app.yaml must contain an App declaration mapping before init or sync');
719
+ }
720
+ return manifest;
721
+ }
722
+
723
+ function writeScaffoldFile(targetDir, file, currentManifest) {
707
724
  const targetPath = path.join(targetDir, file.path);
708
725
  mkdirSync(path.dirname(targetPath), { recursive: true });
726
+ if (file.path === 'nimi.app.yaml' && currentManifest) {
727
+ const next = parseYaml(file.content);
728
+ for (const field of APP_AUTHOR_DECLARATION_FIELDS) {
729
+ if (Object.hasOwn(currentManifest, field)) next[field] = currentManifest[field];
730
+ }
731
+ writeFileSync(targetPath, stringifyYaml(next, { lineWidth: 0 }));
732
+ return;
733
+ }
709
734
  writeFileSync(targetPath, file.content);
710
735
  }
711
736
 
@@ -713,6 +738,7 @@ export function syncManagedApp(cwd, options = {}, versions, runners = {}) {
713
738
  const targetDir = resolveTargetDir(cwd, options);
714
739
  const lock = readLock(targetDir);
715
740
  const intent = readIntent(targetDir);
741
+ const currentManifest = readCurrentAppManifest(targetDir);
716
742
  const packageJson = readJsonFile(path.join(targetDir, 'package.json'), 'package.json');
717
743
  const versionedIntent = {
718
744
  ...intent,
@@ -734,7 +760,7 @@ export function syncManagedApp(cwd, options = {}, versions, runners = {}) {
734
760
  if (!managedEntry) {
735
761
  continue;
736
762
  }
737
- writeScaffoldFile(targetDir, file);
763
+ writeScaffoldFile(targetDir, file, currentManifest);
738
764
  }
739
765
  writeScaffoldFile(targetDir, {
740
766
  path: SCAFFOLD_LOCK_PATH,
@@ -0,0 +1,149 @@
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
+ let url;
75
+ try { url = new URL(value); } catch { throw new Error(`App info ${field} must be a valid HTTPS URL without credentials`); }
76
+ if (url.protocol !== 'https:' || !url.hostname || url.username || url.password) throw new Error(`App info ${field} must be HTTPS without credentials`);
77
+ return value;
78
+ }
79
+
80
+ export function validateAppInfo(info) {
81
+ if (!info || info.format !== 'nimi.app-info/v1') throw new Error('Unsupported App info format');
82
+ for (const key of ['app_id', 'version', 'target_id']) text(info[key], key, 200);
83
+ text(info.display_name, 'display_name', 120);
84
+ text(info.summary, 'summary', 280);
85
+ if (info.icon?.media_type !== 'image/png' || typeof info.icon.data_base64 !== 'string') throw new Error('App info icon must declare PNG bytes');
86
+ const icon = Buffer.from(info.icon.data_base64, 'base64');
87
+ if (icon.toString('base64') !== info.icon.data_base64) throw new Error('App icon base64 is not canonical');
88
+ validateAppIcon(icon);
89
+ if (info.readme_markdown !== undefined && info.readme_markdown !== '') text(info.readme_markdown, 'readme', 96 * 1024, true);
90
+ if (info.release_notes_markdown !== undefined && info.release_notes_markdown !== '') text(info.release_notes_markdown, 'release notes', 32 * 1024, true);
91
+ text(info.license?.identifier, 'license identifier', 200);
92
+ text(info.license?.text, 'license text', 128 * 1024, true);
93
+ refs(info.app_access, 'app_access');
94
+ normalizeAppAccessItems(info.app_access);
95
+ refs(info.capability_contract_refs, 'capability_contract_refs');
96
+ refs(info.required_standardized_feature_refs, 'required_standardized_feature_refs');
97
+ storage(info.storage_policy);
98
+ if (info.author) text(info.author, 'author', 200);
99
+ https(info.homepage_url, 'homepage_url');
100
+ https(info.support_url, 'support_url');
101
+ if (Buffer.byteLength(JSON.stringify(info)) > APP_INFO_MAX_BYTES) throw new Error('App info exceeds 1 MiB');
102
+ return info;
103
+ }
104
+
105
+ function resource(root, relative, label, maxBytes) {
106
+ if (typeof relative !== 'string' || path.isAbsolute(relative) || relative.includes('\\')
107
+ || relative.split('/').some((part) => !part || part === '.' || part === '..')) throw new Error(`metadata.${label} must name an App-relative resource`);
108
+ const file = path.join(root, relative);
109
+ const field = label === 'license' ? 'App license' : `metadata.${label}`;
110
+ try {
111
+ const stat = lstatSync(file);
112
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size === 0 || stat.size > maxBytes) throw new Error(`must be a nonempty regular file of at most ${maxBytes} bytes`);
113
+ return readFileSync(file);
114
+ } catch (error) {
115
+ if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') throw new Error(`${field} resource is missing: ${relative}`);
116
+ throw new Error(`${field} resource ${relative}: ${error.message}`, { cause: error });
117
+ }
118
+ }
119
+
120
+ export function readAppInfo(root, targetId) {
121
+ const manifest = parseYaml(readFileSync(path.join(root, 'nimi.app.yaml'), 'utf8'));
122
+ const pkg = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8'));
123
+ if (manifest.version !== pkg.version) throw new Error('package.json and nimi.app.yaml versions must be exact and lockstep before distribution');
124
+ const metadata = manifest.metadata;
125
+ if (!metadata || typeof metadata !== 'object') throw new Error('nimi.app.yaml metadata is required for distribution (summary, icon)');
126
+ const readText = (relative, label, max) => new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(resource(root, relative, label, max));
127
+ const info = validateAppInfo({
128
+ format: 'nimi.app-info/v1', app_id: manifest.app_id, version: manifest.version, target_id: targetId,
129
+ display_name: manifest.display_name, summary: metadata.summary,
130
+ icon: { media_type: 'image/png', data_base64: validateAppIcon(resource(root, metadata.icon, 'icon', 512 * 1024)).toString('base64') },
131
+ readme_markdown: metadata.readme === undefined ? '' : readText(metadata.readme, 'readme', 96 * 1024),
132
+ release_notes_markdown: metadata.release_notes === undefined ? '' : readText(metadata.release_notes, 'release_notes', 32 * 1024),
133
+ license: { identifier: pkg.license, text: readText('LICENSE', 'license', 128 * 1024) },
134
+ app_access: refs(manifest.app_access, 'app_access'),
135
+ capability_contract_refs: refs(manifest.capability_contract_refs, 'capability_contract_refs'),
136
+ required_standardized_feature_refs: refs(manifest.required_standardized_feature_refs, 'required_standardized_feature_refs'),
137
+ storage_policy: storage(manifest.storage_policy),
138
+ author: metadata.author || '', homepage_url: https(metadata.homepage_url, 'homepage_url'), support_url: https(metadata.support_url, 'support_url'),
139
+ });
140
+ const submissionPath = path.join(root, '.nimi/admission/submission.yaml');
141
+ if (existsSync(submissionPath)) {
142
+ const submission = parseYaml(readFileSync(submissionPath, 'utf8'));
143
+ for (const field of ['app_id', 'version', 'display_name', 'capability_contract_refs', 'required_standardized_feature_refs']) {
144
+ 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`);
145
+ }
146
+ 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');
147
+ }
148
+ return info;
149
+ }
package/lib/app-pack.mjs CHANGED
@@ -16,12 +16,13 @@ import {
16
16
  writeFileSync,
17
17
  } from 'node:fs';
18
18
  import path from 'node:path';
19
- 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';
20
21
  import { observeWindowsExecutableFacts } from './windows-powershell.mjs';
21
22
  import { SYMBOLIC_LINK_MODE, validatePayloadLinks } from './payload-links.mjs';
22
23
  import { observeMacOSExecutableFacts } from './macos-native.mjs';
23
24
 
24
- const PACKAGE_FORMAT = 'nimi.app-package/v1';
25
+ const PACKAGE_FORMAT = 'nimi.app-package/v2';
25
26
  const TARGET_METADATA_FORMAT = 'nimi.app-target-candidate/v1';
26
27
  const AGGREGATE_FORMAT = 'nimi.app-release-candidate/v1';
27
28
  const BUILD_PROFILE_PATH = '.nimi/config/build-profile.yaml';
@@ -278,6 +279,7 @@ function readPackInputs(targetDir, targetId) {
278
279
  }
279
280
  const manifestPath = path.join(targetDir, 'nimi.app.yaml');
280
281
  const manifest = readYaml(manifestPath, 'nimi.app.yaml');
282
+ const appInfo = readAppInfo(targetDir, targetId);
281
283
  const buildProfile = readYaml(path.join(targetDir, BUILD_PROFILE_PATH), BUILD_PROFILE_PATH);
282
284
  const buildProfileRef = buildProfile.build_profile_ref;
283
285
  if (buildProfileRef !== ELECTRON_BUILD_PROFILE_REF && buildProfileRef !== TAURI_BUILD_PROFILE_REF) {
@@ -315,7 +317,7 @@ function readPackInputs(targetDir, targetId) {
315
317
  const runtimeHostPath = payloadStat.isFile()
316
318
  ? payload.resolved
317
319
  : resolveInside(payload.resolved, runtimeRelative, `targets.${targetId}.runtime_entry`).resolved;
318
- 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 };
319
321
  }
320
322
 
321
323
  export function classifyWindowsNativeTrustObservation(observation) {
@@ -462,10 +464,14 @@ export function packAppTarget(cwd, options = {}) {
462
464
  native_trust: nativeTrust,
463
465
  execution_profile: executionProfile,
464
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]]));
465
470
  const archive = writeNimiAppArchive([
466
471
  { name: 'LICENSE', bytes: readFileSync(input.licensePath), mode: 0o644 },
467
472
  { name: 'manifest.json', bytes: canonicalJson(packageManifest), mode: 0o644 },
468
- { 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 },
469
475
  ...payloadEntries,
470
476
  ]);
471
477
  const sha256 = createHash('sha256').update(archive).digest('hex');
@@ -474,7 +480,9 @@ export function packAppTarget(cwd, options = {}) {
474
480
  const stem = `${input.appId}-${input.version}-${input.targetId}`;
475
481
  const artifactPath = path.join(outputDir, `${stem}.nimiapp`);
476
482
  const metadataPath = path.join(outputDir, `${stem}.target.json`);
483
+ const appInfoPath = path.join(outputDir, `${stem}.app-info.json`);
477
484
  writeFileSync(artifactPath, archive);
485
+ writeFileSync(appInfoPath, infoBytes);
478
486
  const metadata = {
479
487
  format: TARGET_METADATA_FORMAT,
480
488
  app_id: input.appId,
@@ -485,12 +493,13 @@ export function packAppTarget(cwd, options = {}) {
485
493
  asset_name: path.basename(artifactPath),
486
494
  size: archive.length,
487
495
  sha256,
496
+ app_info: { asset_name: path.basename(appInfoPath), size: infoBytes.length, sha256: createHash('sha256').update(infoBytes).digest('hex') },
488
497
  runtime_entry: input.runtimeEntry,
489
498
  native_trust: packageManifest.native_trust,
490
499
  execution_profile: packageManifest.execution_profile,
491
500
  };
492
501
  writeFileSync(metadataPath, canonicalJson(metadata));
493
- return { ok: true, command: 'pack', dir: targetDir, artifactPath, metadataPath, ...metadata };
502
+ return { ok: true, command: 'pack', dir: targetDir, artifactPath, metadataPath, appInfoPath, ...metadata };
494
503
  }
495
504
 
496
505
  export function aggregateAppTargetCandidates(cwd, options = {}) {
@@ -525,6 +534,14 @@ export function aggregateAppTargetCandidates(cwd, options = {}) {
525
534
  const bytes = readFileSync(artifactPath);
526
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}`);
527
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 infoPath = path.join(outputDir, infoAsset.asset_name);
540
+ if (!existsSync(infoPath)) throw new Error(`Target App info asset is missing: ${infoAsset.asset_name}`);
541
+ const infoBytes = readFileSync(infoPath);
542
+ 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}`);
543
+ const info = validateAppInfo(JSON.parse(infoBytes));
544
+ 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}`);
528
545
  validatePayloadLinks(entries, target.os);
529
546
  const manifest = readPackageManifestFromArchive(entries, metadataLabel);
530
547
  if (manifest.format !== PACKAGE_FORMAT) throw new Error(`Target archive manifest format is invalid: ${target.asset_name}`);
@@ -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
 
@@ -117,7 +118,7 @@ function readSubmittedManifest(targetDir) {
117
118
  if (!SEMVER_PATTERN.test(version) || version !== document.version) {
118
119
  throw new Error('Existing submitted app version must be an exact semantic version');
119
120
  }
120
- 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 });
121
122
  }
122
123
 
123
124
  function assertNoRetiredScaffoldState(targetDir) {
@@ -943,17 +944,6 @@ function assertProjectLifecycleCurrent(targetDir, versions, options = {}) {
943
944
  }
944
945
  assertNoStandaloneParentSources(targetDir);
945
946
  const authoring = assertCanonicalAuthoringInputs(targetDir, descriptor, files, version, nativeIdentity);
946
- if (existsSync(path.join(targetDir, SCAFFOLD_LOCK_PATH))) {
947
- const lock = readJsonFile(path.join(targetDir, SCAFFOLD_LOCK_PATH), 'scaffold lock');
948
- for (const [field, expected] of [
949
- ['capability_contract_refs', lock.capabilityContractRefs],
950
- ['required_standardized_feature_refs', lock.requiredStandardizedFeatureRefs],
951
- ]) {
952
- if (JSON.stringify(authoring.submission[field]) !== JSON.stringify(expected || [])) {
953
- throw new Error(`${SUBMISSION_PATH} ${field} must match the selected scaffold feature closure`);
954
- }
955
- }
956
- }
957
947
  assertManagedWorkflowCurrent(targetDir);
958
948
  assertPnpmWorkspaceCurrent(targetDir);
959
949
  if (options.requireInstalledLock === true) {
@@ -1033,10 +1023,10 @@ function buildExistingSubmittedAppSyncPlan(targetDir, versions) {
1033
1023
  supportManifest = normalizeSupportInput(currentSubmission.support_manifest, `${SUBMISSION_PATH} support_manifest`);
1034
1024
  }
1035
1025
  const submissionContent = renderAppSubmissionInput(identity, {
1036
- capabilityContractRefs: currentSubmission?.capability_contract_refs || [],
1037
- requiredStandardizedFeatureRefs: currentSubmission?.required_standardized_feature_refs || [],
1026
+ capabilityContractRefs: descriptor.capabilityContractRefs ?? currentSubmission?.capability_contract_refs ?? [],
1027
+ requiredStandardizedFeatureRefs: descriptor.requiredStandardizedFeatureRefs ?? currentSubmission?.required_standardized_feature_refs ?? [],
1038
1028
  aiProfileRecommendationRef: currentSubmission?.ai_profile_recommendation_ref,
1039
- storagePolicy: currentSubmission?.storage_policy || { kind: 'nimi-mediated-default' },
1029
+ storagePolicy: descriptor.storagePolicy ?? currentSubmission?.storage_policy ?? { kind: 'nimi-mediated-default' },
1040
1030
  supportManifest,
1041
1031
  });
1042
1032
  planned.push({ path: submissionPath, content: submissionContent, previous: currentSubmissionSource });
@@ -1161,6 +1151,9 @@ export function checkAppProject(cwd, options = {}, versions, runners = {}) {
1161
1151
  let nimicoding = null;
1162
1152
  if (!managed) nimicoding = runNimicodingSync(targetDir, 'check', runners);
1163
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
+ }
1164
1157
  return emitResult({
1165
1158
  ok: true,
1166
1159
  command: 'check',
@@ -1193,6 +1186,7 @@ export function buildAppProject(cwd, options = {}, runners = {}) {
1193
1186
  const targetDir = resolveTargetDir(cwd, options);
1194
1187
  const profile = readBuildProfile(targetDir);
1195
1188
  const selected = selectBuildOwner(profile, options.target);
1189
+ if (options.production === true) readAppInfo(targetDir, selected.target);
1196
1190
  const result = runOwnerCommand(targetDir, 'build', selected.command, options, runners);
1197
1191
  if (options.production === true) {
1198
1192
  assertProductionRuntimeEntry(targetDir, selected);
@@ -202,6 +202,7 @@ const APP_RELEASE_WORKFLOW = [
202
202
  ' path: |',
203
203
  ' dist/nimi-app/*.nimiapp',
204
204
  ' dist/nimi-app/*.target.json',
205
+ ' dist/nimi-app/*.app-info.json',
205
206
  ' if-no-files-found: error',
206
207
  ' attest-target:',
207
208
  " if: github.event_name == 'push' && github.ref_type == 'tag'",
@@ -248,6 +249,7 @@ const APP_RELEASE_WORKFLOW = [
248
249
  ' path: |',
249
250
  ' dist/nimi-app/*.nimiapp',
250
251
  ' dist/nimi-app/*.target.json',
252
+ ' dist/nimi-app/*.app-info.json',
251
253
  ' dist/nimi-app/*.candidate.json',
252
254
  ' if-no-files-found: error',
253
255
  ' release:',
@@ -287,7 +289,7 @@ const APP_RELEASE_WORKFLOW = [
287
289
  " sleep 10",
288
290
  " done",
289
291
  " }",
290
- ' assets=(release-assets/*.nimiapp release-assets/*.candidate.json)',
292
+ ' assets=(release-assets/*.nimiapp release-assets/*.app-info.json release-assets/*.candidate.json)',
291
293
  ' test "${#assets[@]}" -gt 0',
292
294
  " expected=$(printf '%s\\n' \"${assets[@]##*/}\" | jq -R -s -c 'split(\"\\n\")[:-1] | sort')",
293
295
  ' if release_id=$(gh release view "$GITHUB_REF_NAME" --repo "$GITHUB_REPOSITORY" --json databaseId --jq .databaseId 2>/dev/null); then',
@@ -864,6 +866,15 @@ function buildNimiAppManifest(identity) {
864
866
  profile: identity.profile,
865
867
  manifest_role: 'submitted-input',
866
868
  app_access: identity.appAccessItems,
869
+ capability_contract_refs: identity.capabilityResolution.capabilityContractRefs,
870
+ required_standardized_feature_refs: identity.capabilityResolution.requiredStandardizedFeatureRefs,
871
+ storage_policy: { kind: 'nimi-mediated-default' },
872
+ metadata: {
873
+ summary: '',
874
+ icon: 'assets/app-icon.png',
875
+ readme: 'README.md',
876
+ release_notes: 'RELEASE_NOTES.md',
877
+ },
867
878
  local_development: {
868
879
  electron: {
869
880
  renderer_origin: `http://127.0.0.1:${identity.devPort}`,
@@ -1336,7 +1347,7 @@ function buildScaffoldLock(identity, versions, files, targetDir = '') {
1336
1347
  for (const file of files) {
1337
1348
  const mutationClass = file.mutationClass;
1338
1349
  taxonomy[mutationClass].push(file.path);
1339
- const digest = hashScaffoldContent(file.content);
1350
+ const digest = hashScaffoldManagedContent(file.path, file.content);
1340
1351
  if (mutationClass === 'app-owned product code') {
1341
1352
  appOwnedInitialHashes[file.path] = {
1342
1353
  class: mutationClass,
@@ -1571,3 +1582,13 @@ export function createAppScaffoldCandidate(input) {
1571
1582
  const plan = input.plan || buildAppScaffoldCandidateCreatePlan(input);
1572
1583
  return createAppScaffold({ ...input, plan });
1573
1584
  }
1585
+
1586
+ export const APP_AUTHOR_DECLARATION_FIELDS = Object.freeze(['metadata', 'capability_contract_refs', 'required_standardized_feature_refs', 'storage_policy']);
1587
+
1588
+ // Source configuration is editable; existing scaffold checks still cover identity and carrier fields.
1589
+ export function hashScaffoldManagedContent(relativePath, content) {
1590
+ if (relativePath !== 'nimi.app.yaml') return hashScaffoldContent(content);
1591
+ const manifest = YAML.parse(content.toString());
1592
+ for (const field of APP_AUTHOR_DECLARATION_FIELDS) delete manifest[field];
1593
+ return hashScaffoldContent(YAML.stringify(manifest, { lineWidth: 0 }));
1594
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nimiplatform/app-tools",
3
- "version": "0.3.0",
3
+ "version": "0.5.1",
4
4
  "description": "Public app-authoring CLI for Nimi App projects.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -18,11 +18,11 @@
18
18
  "provenance": true
19
19
  },
20
20
  "nimiScaffoldVersions": {
21
- "sdkVersion": "^0.10.0",
22
- "appToolsVersion": "^0.3.0",
21
+ "sdkVersion": "^0.11.0",
22
+ "appToolsVersion": "^0.5.1",
23
23
  "nimicodingVersion": "0.6.2",
24
24
  "aiSdkVersion": "^6.0.85",
25
- "kitVersion": "^0.6.0",
25
+ "kitVersion": "^0.7.0",
26
26
  "reactVersion": "^19.2.8",
27
27
  "reactDomVersion": "^19.2.8",
28
28
  "i18nextVersion": "^25.10.10",
@@ -68,6 +68,7 @@
68
68
  "README.md"
69
69
  ],
70
70
  "dependencies": {
71
+ "pngjs": "7.0.0",
71
72
  "postcss": "^8.5.26",
72
73
  "postcss-selector-parser": "^7.1.5",
73
74
  "semver": "^7.8.5",
@@ -26,36 +26,23 @@ function publicPackageRange(manifest, label) {
26
26
  return `^${requiredString(manifest.version, `${label}.version`)}`;
27
27
  }
28
28
 
29
- function nimiShellTauriVersion() {
30
- const cargo = readFileSync(path.join(REPO_ROOT, 'kit/shell/tauri/Cargo.toml'), 'utf8');
31
- if (!/^name\s*=\s*"nimi-shell-tauri"\s*$/mu.test(cargo)) {
32
- throw new Error('Scaffold version source is invalid: kit/shell/tauri package name');
33
- }
34
- const match = cargo.match(/^version\s*=\s*"([^"]+)"\s*$/mu);
35
- const version = requiredString(match?.[1], 'kit/shell/tauri.version');
36
- validateAppScaffoldCargoDependencyValue(version, 'kit/shell/tauri.version');
37
- return version;
38
- }
39
-
29
+ // @nimi-authority: rule.nimi.platform.governance-release.p-gov-027-component-release-identity
30
+ // The manifest owns tested public dependency versions independently of workspace development versions.
40
31
  export function buildScaffoldVersionProjection() {
41
32
  const rootManifest = readJson('package.json');
42
33
  const appToolsManifest = readJson('app-tools/package.json');
43
- const sdkManifest = readJson('sdks/typescript/package.json');
44
- const kitManifest = readJson('kit/package.json');
45
34
  const current = appToolsManifest.nimiScaffoldVersions;
46
35
  if (!current || typeof current !== 'object' || Array.isArray(current)) {
47
36
  throw new Error('app-tools package manifest is missing nimiScaffoldVersions');
48
37
  }
38
+ validateAppScaffoldCargoDependencyValue(current.nimiShellTauriVersion, 'nimiScaffoldVersions.nimiShellTauriVersion');
49
39
  return Object.freeze({
50
40
  ...current,
51
- sdkVersion: publicPackageRange(sdkManifest, '@nimiplatform/sdk'),
52
41
  appToolsVersion: publicPackageRange(appToolsManifest, '@nimiplatform/app-tools'),
53
42
  nimicodingVersion: requiredString(
54
43
  rootManifest.devDependencies?.['@nimiplatform/nimi-coding'],
55
44
  'root.devDependencies.@nimiplatform/nimi-coding',
56
45
  ),
57
- kitVersion: publicPackageRange(kitManifest, '@nimiplatform/kit'),
58
- nimiShellTauriVersion: nimiShellTauriVersion(),
59
46
  packageManager: requiredString(rootManifest.packageManager, 'root.packageManager'),
60
47
  });
61
48
  }
@@ -1,11 +1,13 @@
1
+ import type { NimiLocalAppClient } from '@nimiplatform/sdk/app';
1
2
  import { createContext, useContext, type ReactNode } from 'react';
2
3
  import type { NimiPortableAppAIConfig } from '@nimiplatform/sdk/ai';
3
- import type { NimiLocalAppArtifactImageMime } from '@nimiplatform/sdk/app';
4
4
  import type { StudioCapabilityRunInput, StudioCapabilityRunResult } from './runtime-types.js';
5
5
  import type { StudioCapabilityDescriptor } from './module-registration.js';
6
6
  import type { StudioRunTargetSummary } from './history.js';
7
7
  import type { StudioPromptDraftKey } from './prompt-drafts.js';
8
8
 
9
+ type NimiLocalAppArtifactUploadMime = Parameters<NimiLocalAppClient['ai']['artifacts']['upload']>[0]['mimeType'];
10
+
9
11
  export type StudioHostCommandResult<TValue extends object = Record<string, never>> =
10
12
  | { readonly ok: true; readonly value?: TValue }
11
13
  | { readonly ok: false; readonly error?: unknown };
@@ -47,11 +49,11 @@ export type AIStudioHostPort = {
47
49
  }[]>;
48
50
  readonly uploadLocalAppArtifact: (input: {
49
51
  readonly bytes: Uint8Array;
50
- readonly mimeType: NimiLocalAppArtifactImageMime;
52
+ readonly mimeType: NimiLocalAppArtifactUploadMime;
51
53
  }) => Promise<{
52
54
  readonly artifactId: string;
53
55
  readonly sizeBytes: number;
54
- readonly mimeType: NimiLocalAppArtifactImageMime;
56
+ readonly mimeType: NimiLocalAppArtifactUploadMime;
55
57
  }>;
56
58
  readonly aiConfig: {
57
59
  readonly get: () => Promise<NimiPortableAppAIConfig | null>;
@@ -1,6 +1,6 @@
1
1
  import { runNimiRuntimeScenarioJob } from '@nimiplatform/sdk/runtime';
2
2
  import { ExecutionMode, ScenarioType, VisionLocateGeometry, type VisionLocateResult } from '@nimiplatform/sdk/runtime/generated';
3
- import type { NimiLocalAppArtifactImageMime, NimiLocalAppVisionLocateResult } from '@nimiplatform/sdk/app';
3
+ import type { NimiLocalAppVisionLocateResult } from '@nimiplatform/sdk/app';
4
4
  import { createStudioScenarioJobClient, type StudioCapabilityRuntimeContext } from '../../ai-studio-core/runtime.js';
5
5
 
6
6
  function localVisionResult(result: VisionLocateResult): NimiLocalAppVisionLocateResult {
@@ -32,7 +32,7 @@ export async function runVisionLocate(context: StudioCapabilityRuntimeContext) {
32
32
  const bytes = Uint8Array.from(atob(image.dataUrl.slice(prefix.length)), char => char.charCodeAt(0));
33
33
  let upload;
34
34
  try {
35
- upload = await context.host.client.ai.artifacts.upload({ bytes, mimeType: image.mimeType as NimiLocalAppArtifactImageMime });
35
+ upload = await context.host.client.ai.artifacts.upload({ bytes, mimeType: image.mimeType as Parameters<typeof context.host.client.ai.artifacts.upload>[0]['mimeType'] });
36
36
  } catch (error) {
37
37
  if (context.input.signal?.aborted) return abortedBeforeSubmit();
38
38
  throw error;