@nimiplatform/app-tools 0.4.0 → 0.5.2

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
@@ -4,6 +4,75 @@
4
4
 
5
5
  It does not own GitHub publisher or repository truth, registry review/main, Runtime installed state, Desktop process state, or Nimi Access. Nimi Account and the private Nimi backend are not publisher credentials or App-release infrastructure.
6
6
 
7
+ ## AI development and existing projects
8
+
9
+ The package includes one `skills/nimi-app-lifecycle/SKILL.md` with on-demand
10
+ guides for creating, adapting, platform upgrades, upstream sync, releases and
11
+ acceptance. Read it inside the installed package before initializing an existing
12
+ repository. `nimi-app --help` prints its resolved location. Installation does
13
+ not activate instructions; explicit init/sync maintains the project skill under
14
+ `.agents/skills/nimi-app-lifecycle/` and an independent AGENTS.md block.
15
+
16
+ Prepare the existing App's actual pnpm/Vite/Electron renderer, supervised Host
17
+ and build/test scripts first. Init does not convert a server framework, invent
18
+ tests or replace product UI. Install the selected app-tools and the exact
19
+ nimi-coding version declared in its `nimiScaffoldVersions`, then preview:
20
+
21
+ ```bash
22
+ pnpm exec nimi-app init --adopt --dry-run --json
23
+ pnpm exec nimi-app init --adopt
24
+ pnpm install
25
+ pnpm exec nimi-app check
26
+ ```
27
+
28
+ Existing nimi.app.yaml and `.nimi/config/build-profile.yaml` supply the inputs.
29
+ If either is missing, pass `--input .nimi/local/adopt-input.json`. This temporary
30
+ JSON accepts only `manifest` and `build_profile`, using those same schemas.
31
+ For an App whose named scripts are already implemented, an input is:
32
+
33
+ ```json
34
+ {
35
+ "manifest": {
36
+ "app_id": "example.editor", "display_name": "Example Editor", "version": "0.1.0",
37
+ "profile": "standalone", "manifest_role": "submitted-input",
38
+ "app_access": ["runtime.consume"], "capability_contract_refs": ["text.generate"],
39
+ "required_standardized_feature_refs": [], "storage_policy": { "kind": "nimi-mediated-default" },
40
+ "local_development": { "electron": { "renderer_origin": "http://127.0.0.1:1466" } }
41
+ },
42
+ "build_profile": {
43
+ "build_profile_ref": "electron-packager-pnpm-vite", "profile_role": "developer-workflow-input",
44
+ "test_command": "pnpm run test:app", "build_command": "pnpm run build:electron:production",
45
+ "targets": {
46
+ "windows-x86_64": {
47
+ "os": "windows", "arch": "x86_64",
48
+ "payload_path": "dist-electron-package/example-editor-shell-win32-x64",
49
+ "runtime_entry": "payload/example-editor-shell.exe"
50
+ }
51
+ }
52
+ }
53
+ }
54
+ ```
55
+
56
+ Use actual identity, version, declarations and target outputs. Complete portable
57
+ App information before packaging. Supplied input must agree with an existing
58
+ file. Unknown managed-file collisions and broken markers fail before writes;
59
+ existing Host, business code, README and license remain App-owned. Adoption
60
+ creates no fresh scaffold intent/lock. Init validates output declarations;
61
+ build/pack later verify actual payloads.
62
+
63
+ `init --dry-run --json` and `sync --dry-run --json` show app-tools file/field
64
+ changes without writes, installation or owner mutation. The separate
65
+ nimi-coding step and expected version are listed without simulating its internals.
66
+ For an upgrade, install the target app-tools and exact nimi-coding before apply.
67
+ Sync recomputes fresh scaffold derived projections while retaining immutable
68
+ identity/direct features and App-owned code; then install the normalized
69
+ dependencies, refresh package-manager locks, check and verify the affected task.
70
+ The checkout directory is reported in command output, not persisted as App
71
+ identity; syncing an upgraded project after relocating it does not dirty its
72
+ intent/lock merely because the absolute path changed.
73
+ An installed nimi-coding version that differs from the selected tool matrix is
74
+ rejected before its projection command runs.
75
+
7
76
  ## Command family
8
77
 
9
78
  The public CLI has exactly eight commands:
@@ -14,7 +83,7 @@ create -> dependency install -> init -> sync -> check
14
83
  ```
15
84
 
16
85
  - `create` writes a standalone private App project with a dotted App ID, exact version, public dependency declarations, developer build/submission inputs and one managed workflow. It does not install dependencies or create admission truth.
17
- - `init` materializes package-owned projections and the scaffold lock after dependencies are installed.
86
+ - `init` materializes package-owned projections and lifecycle guidance after dependencies are installed. Fresh scaffolds also receive their scaffold lock; `init --adopt` preserves an existing App without creating scaffold intent or lock.
18
87
  - `sync` refreshes only scaffold-managed dependencies, configuration, workflow and glue. App-owned product code is preserved.
19
88
  - `check` is non-mutating and incorporates the former scaffold validation behavior.
20
89
  - `dev` requests the official Desktop-supervised Electron development Host.
@@ -77,7 +146,7 @@ pnpm dev -- --resume <selector>
77
146
 
78
147
  The list shows the current project's registrations and creation times. Copy the desired selector from that list; Desktop resolves it to the exact existing Runtime-owned registration. Selectors last for the current Desktop session, so list again after restarting Desktop. No selector is stored in the App repository, and no App ID or path automatically reopens a subject. Plain `pnpm dev` keeps its fresh-registration behavior when no matching run is active. These options require a Desktop build that supports explicit launcher selection.
79
148
 
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.
149
+ 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 packaging, native `.node` addons unpacked, 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
150
 
82
151
  App Tools 0.3 also prepares the `macos-aarch64` target on an Apple Silicon Mac.
83
152
  The same owner command produces `dist-electron-package/<app>-shell-darwin-arm64/`
@@ -102,8 +171,9 @@ Tauri remains an explicit alternative through `pnpm run build:tauri:production`;
102
171
  ## Canonical release boundary
103
172
 
104
173
  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:
174
+ is available for configured pilot repositories. Protected Registry admission and
175
+ installed App lifecycle use their separate Platform, Runtime and Desktop owners;
176
+ each App's declared target still needs its own acceptance.
107
177
 
108
178
  ```text
109
179
  public App repository
@@ -111,12 +181,17 @@ public App repository
111
181
  -> immutable protected version tag
112
182
  -> tag-triggered publisher GitHub Actions
113
183
  -> immutable GitHub Release assets
114
- -> publisher-fork registry pull request
184
+ -> publisher-owned registry pull request
115
185
  -> human-reviewed static registry main
116
186
  -> Runtime download/install
117
187
  -> Desktop exact Host launch
118
188
  ```
119
189
 
190
+ External publishers submit from their own fork. An authorized publisher sharing
191
+ the Registry namespace can use a same-repository branch. Both paths use one
192
+ publisher-owned branch and pull request for the exact App version and Release;
193
+ human maintainers own admission.
194
+
120
195
  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
196
 
122
197
  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.
@@ -224,8 +299,10 @@ pnpm dlx --package @nimiplatform/app-tools nimi-app --help
224
299
  ## Portable App information (package v2)
225
300
 
226
301
  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:
302
+ summary, available usage guide and version notes, license and portable requirements.
303
+ Every `pack`, including development-mode packaging and non-release CI, requires
304
+ valid App information. Complete `nimi.app.yaml` and its resources before packing;
305
+ production check/build validates them before the build starts:
229
306
 
230
307
  ```yaml
231
308
  metadata:
@@ -261,8 +338,10 @@ explicit license identifier; it does not turn a private license into an
261
338
  open-source Registry license. Name and summary allow 120 and 280 characters.
262
339
  Scaffold `sync` preserves these author-edited metadata, requirement and storage
263
340
  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.
341
+ The scaffold does not supply finished artwork. Add the declared icon, a summary
342
+ and license information; provide any declared documents or omit optional document
343
+ paths for local/private packages. Until then, package-producing CI will fail.
344
+ Incomplete projects remain editable with `dev` and ordinary non-production builds.
266
345
 
267
346
  Pack writes `nimi.app-package/v2` and emits the exact embedded information bytes
268
347
  as `<app_id>-<version>-<target_id>.app-info.json` next to the `.nimiapp` and
@@ -276,6 +355,24 @@ declares the tested public SDK, Kit and Tauri shell versions used by new Apps an
276
355
  explicit `sync`; workspace development version bumps do not change those ranges.
277
356
  The release workflow requires those public versions before publishing App Tools.
278
357
 
358
+ Existing Apps follow the [platform upgrade guide](skills/nimi-app-lifecycle/references/upgrade-platform.md).
359
+ Select a published app-tools version and the exact nimi-coding version in that
360
+ release's `nimiScaffoldVersions`. Install both in the App's `devDependencies`
361
+ before invoking the target tool. Read the SDK/Kit migration notes and update the
362
+ affected App-owned API uses, then preview and apply:
363
+
364
+ ```bash
365
+ pnpm exec nimi-app sync --dry-run --json
366
+ pnpm exec nimi-app sync
367
+ pnpm install
368
+ pnpm exec nimi-app check
369
+ pnpm exec nimi-app test
370
+ pnpm exec nimi-app build --target windows-x86_64
371
+ ```
372
+
373
+ Use the App's declared target for the final build. `sync` preserves App-owned
374
+ product code; update any affected SDK/Kit API usage in that code before release.
375
+
279
376
  The v2 Runtime rejects v1 packages. Existing immutable publisher Releases and
280
377
  approved descriptors must not be edited to invent the missing asset. Prepare a
281
378
  new App version and real target builds, publish new immutable assets, and follow
package/bin/nimi-app.mjs CHANGED
@@ -15,6 +15,7 @@ import {
15
15
  testApp,
16
16
  } from '../lib/index.mjs';
17
17
  import { APP_SCAFFOLD_MODULE_REGISTRY } from '../lib/app-scaffold-capabilities.mjs';
18
+ import { LIFECYCLE_SKILL_PATH } from '../lib/app-lifecycle-guidance.mjs';
18
19
  import { createInterface } from 'node:readline/promises';
19
20
 
20
21
  function parseArgs(argv) {
@@ -22,6 +23,7 @@ function parseArgs(argv) {
22
23
  const values = {
23
24
  dir: '', profile: '', appId: '', version: '', title: '', packageName: '', author: '',
24
25
  features: undefined, shell: '', cdpPort: undefined, noCdp: false, listRegistrations: false, resume: '', conformance: '', target: '', aggregate: false, production: false, json: false,
26
+ adopt: false, dryRun: false, input: '',
25
27
  };
26
28
  const seen = new Set();
27
29
  const readValue = (index, flag, key, preserve = false) => {
@@ -37,6 +39,17 @@ function parseArgs(argv) {
37
39
  return index + 1;
38
40
  };
39
41
  for (let index = 0; index < rest.length; index += 1) {
42
+ if (rest[index] === '--input') {
43
+ index = readValue(index, '--input', 'input');
44
+ continue;
45
+ }
46
+ if (rest[index] === '--adopt' || rest[index] === '--dry-run') {
47
+ const key = rest[index] === '--adopt' ? 'adopt' : 'dryRun';
48
+ if (seen.has(key)) throw new Error(`Duplicate option: ${rest[index]}`);
49
+ seen.add(key);
50
+ values[key] = true;
51
+ continue;
52
+ }
40
53
  if (rest[index] === '--') {
41
54
  continue;
42
55
  }
@@ -134,8 +147,8 @@ function parseArgs(argv) {
134
147
  function assertCommandOptions(command, providedOptions) {
135
148
  const allowed = {
136
149
  create: new Set(['dir', 'profile', 'appId', 'version', 'title', 'packageName', 'author', 'features', 'json']),
137
- init: new Set(['dir', 'json']),
138
- sync: new Set(['dir', 'json']),
150
+ init: new Set(['dir', 'json', 'adopt', 'input', 'dryRun']),
151
+ sync: new Set(['dir', 'json', 'dryRun']),
139
152
  check: new Set(['dir', 'json', 'conformance', 'production']),
140
153
  dev: new Set(['dir', 'shell', 'cdpPort', 'noCdp', 'listRegistrations', 'resume']),
141
154
  test: new Set(['dir', 'json']),
@@ -165,8 +178,8 @@ function printUsage() {
165
178
  '',
166
179
  'Usage:',
167
180
  ' nimi-app create [--dir path] [--profile standalone] [--features admitted-ids|all] [--app-id dotted.id] [--version semver] [--title title] [--package-name name] [--author person-or-team] [--json]',
168
- ' nimi-app init [--dir path] [--json]',
169
- ' nimi-app sync [--dir path] [--json]',
181
+ ' nimi-app init [--adopt [--input json-path]] [--dry-run] [--dir path] [--json]',
182
+ ' nimi-app sync [--dry-run] [--dir path] [--json]',
170
183
  ' nimi-app check [--dir path] [--conformance simulator | --production] [--json]',
171
184
  ' nimi-app dev [--dir path] [--shell electron] [--list-registrations | --resume <selector>] [--cdp-port 1024..65535 | --no-cdp]',
172
185
  ' nimi-app test [--dir path] [--json]',
@@ -201,6 +214,8 @@ function printUsage() {
201
214
  'Required order:',
202
215
  ' create -> dependency install -> init -> sync -> check -> dev/test/build -> pack',
203
216
  ' Run init and later commands only after dependency installation.',
217
+ ` Before init, read the packaged lifecycle skill: ${LIFECYCLE_SKILL_PATH}`,
218
+ ' Existing adoption requires real pnpm/Vite/Electron Host and build/test inputs; it creates no fresh scaffold lock.',
204
219
  '',
205
220
  'Development CDP:',
206
221
  ' Electron CDP defaults to an automatically selected loopback port.',
@@ -302,6 +317,9 @@ try {
302
317
  aggregate,
303
318
  production,
304
319
  json,
320
+ adopt,
321
+ dryRun,
322
+ input,
305
323
  providedOptions,
306
324
  } = parsedArgs;
307
325
  if (!command || command === '--help' || command === '-h') {
@@ -309,6 +327,7 @@ try {
309
327
  process.exit(0);
310
328
  }
311
329
  assertCommandOptions(command, providedOptions);
330
+ if (input && !adopt) throw new Error('--input requires nimi-app init --adopt');
312
331
  if (command !== 'dev' && (cdpPort !== undefined || noCdp)) {
313
332
  throw new Error('--cdp-port and --no-cdp are available only for nimi-app dev');
314
333
  }
@@ -351,12 +370,16 @@ try {
351
370
  initAppScaffold(process.cwd(), {
352
371
  dir,
353
372
  json,
373
+ adopt,
374
+ input,
375
+ dryRun,
354
376
  });
355
377
  break;
356
378
  case 'sync':
357
379
  syncApp(process.cwd(), {
358
380
  dir,
359
381
  json,
382
+ dryRun,
360
383
  });
361
384
  break;
362
385
  case 'check':
@@ -1,5 +1,5 @@
1
1
  import { APP_AUTHOR_DECLARATION_FIELDS, hashScaffoldManagedContent } from './app-scaffold.mjs';
2
- import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
2
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
5
5
  import {
@@ -13,11 +13,14 @@ import {
13
13
  } from './app-scaffold.mjs';
14
14
  import { assertManifestAppAccessDeclaration } from './app-access-declaration.mjs';
15
15
  import { validateSimulatorAppSourceWithCanonicalKitExports } from './simulator-conformance.mjs';
16
+ import { assertLifecycleGuidanceCurrent, LIFECYCLE_SKILL_PATH, lifecycleOwnerSteps, planLifecycleGuidance } from './app-lifecycle-guidance.mjs';
17
+ import { applyProjectFiles, describeChanges, plannedFile } from './app-project-files.mjs';
16
18
 
17
19
  const SCAN_EXCLUDED_DIRS = new Set([
18
20
  '.git',
19
21
  '.turbo',
20
22
  '.vite',
23
+ '.next',
21
24
  'build',
22
25
  'coverage',
23
26
  'dist',
@@ -198,6 +201,7 @@ function expectedSnapshotFromLock(lock, versions, intent, targetDir, options = {
198
201
  versions,
199
202
  targetDir,
200
203
  allowDerivedAppAccessDrift: options.allowDerivedAppAccessDrift === true,
204
+ refreshDerived: options.refreshDerived === true,
201
205
  });
202
206
  if (stableStringify(intent.directFeatures) !== stableStringify(lock.directFeatures)) {
203
207
  throw new Error('Scaffold feature selection is immutable; create a fresh scaffold for a different feature closure');
@@ -249,6 +253,14 @@ function projectHashClasses(entries) {
249
253
  );
250
254
  }
251
255
 
256
+ function isScannedTextPath(relativePath) {
257
+ const parts = relativePath.split('/');
258
+ return !parts.some((part) => SCAN_EXCLUDED_DIRS.has(part))
259
+ && !SCAN_EXCLUDED_FILES.has(parts.at(-1))
260
+ && !/^\.nimi\/(?:config|contracts|methodology|spec|local|cache)\//u.test(relativePath)
261
+ && TEXT_EXTENSIONS.has(path.extname(relativePath));
262
+ }
263
+
252
264
  function collectTextFiles(rootDir) {
253
265
  const results = [];
254
266
  const walk = (currentDir) => {
@@ -265,26 +277,11 @@ function collectTextFiles(rootDir) {
265
277
  continue;
266
278
  }
267
279
  const relativePath = path.relative(rootDir, fullPath).split(path.sep).join('/');
268
- if (SCAN_EXCLUDED_FILES.has(entry.name)) {
269
- continue;
270
- }
271
- if (
272
- relativePath.startsWith('.nimi/config/')
273
- || relativePath.startsWith('.nimi/contracts/')
274
- || relativePath.startsWith('.nimi/methodology/')
275
- || relativePath.startsWith('.nimi/spec/')
276
- || relativePath.startsWith('.nimi/local/')
277
- || relativePath.startsWith('.nimi/cache/')
278
- ) {
279
- continue;
280
- }
280
+ if (!isScannedTextPath(relativePath)) continue;
281
281
  const stat = statSync(fullPath);
282
282
  if (stat.size > 1024 * 1024) {
283
283
  continue;
284
284
  }
285
- if (!TEXT_EXTENSIONS.has(path.extname(entry.name))) {
286
- continue;
287
- }
288
285
  results.push(fullPath);
289
286
  }
290
287
  };
@@ -345,7 +342,8 @@ function buildForbiddenPatterns() {
345
342
  ];
346
343
  }
347
344
 
348
- function scanForbiddenPatterns(targetDir, profile, selectedLabels = null) {
345
+ // @nimi-authority: rule.nimi.platform.app-ecosystem.p-scaf-016b
346
+ function scanForbiddenPatterns(targetDir, profile, selectedLabels = null, plannedSources) {
349
347
  const findings = [];
350
348
  const patterns = buildForbiddenPatterns();
351
349
  const testFileAllowedLabels = new Set([
@@ -361,17 +359,26 @@ function scanForbiddenPatterns(targetDir, profile, selectedLabels = null) {
361
359
  'renderer or app storage of protected material',
362
360
  'environment custody of protected material',
363
361
  ]);
364
- for (const filePath of collectTextFiles(targetDir)) {
365
- const relativePath = path.relative(targetDir, filePath).split(path.sep).join('/');
366
- const text = readFileSync(filePath, 'utf8');
362
+ const relativePaths = new Set(collectTextFiles(targetDir).map((filePath) => path.relative(targetDir, filePath).split(path.sep).join('/')));
363
+ for (const [relativePath, content] of plannedSources || []) {
364
+ if (content !== null && isScannedTextPath(relativePath) && Buffer.byteLength(content) <= 1024 * 1024) relativePaths.add(relativePath);
365
+ }
366
+ for (const relativePath of relativePaths) {
367
+ if (plannedSources?.has(relativePath) && plannedSources.get(relativePath) === null) continue;
368
+ const text = plannedSources?.has(relativePath)
369
+ ? Buffer.from(plannedSources.get(relativePath)).toString('utf8')
370
+ : readFileSync(path.join(targetDir, relativePath), 'utf8');
367
371
  const isManagedReleaseWorkflow = relativePath === '.github/workflows/nimi-app-release.yml'
368
372
  && text.replaceAll('\r\n', '\n') === managedAppReleaseWorkflowSource();
369
- const isTestFile = relativePath.startsWith('test/') || /(?:^|\/)\w[^/]*\.(?:test|spec)\.[cm]?[jt]sx?$/i.test(relativePath);
373
+ const isTestFile = /^(?:test|tests)\//.test(relativePath) || /(?:^|\/)\w[^/]*\.(?:test|spec)\.[cm]?[jt]sx?$/i.test(relativePath);
374
+ const isAgentSkillReference = /^(?:\.agents|\.claude)\/skills\//.test(relativePath);
370
375
  for (const [label, pattern] of patterns) {
371
376
  if (selectedLabels && !selectedLabels.has(label)) {
372
377
  continue;
373
378
  }
374
- if (selectedLabels && isTestFile) {
379
+ // Existing repositories may vendor agent skills and their example code.
380
+ // Those examples and test fixtures are not the App's protected callers.
381
+ if (selectedLabels && (isTestFile || isAgentSkillReference)) {
375
382
  continue;
376
383
  }
377
384
  // Test files reference provider/model names to assert behavior (including
@@ -480,8 +487,7 @@ function assertElectronLocalDevelopmentManifest(document) {
480
487
  return parsed.origin;
481
488
  }
482
489
 
483
- function assertOfficialDevelopmentEntrypoints(targetDir, rendererOrigin) {
484
- const packageJson = readJsonFile(path.join(targetDir, 'package.json'), 'package.json');
490
+ function assertOfficialDevelopmentEntrypoints(targetDir, rendererOrigin, packageJson = readJsonFile(path.join(targetDir, 'package.json'), 'package.json')) {
485
491
  const scripts = packageJson?.scripts;
486
492
  if (!scripts || typeof scripts !== 'object' || Array.isArray(scripts)) {
487
493
  throw new Error('package.json scripts are required');
@@ -528,15 +534,30 @@ function assertNimicodingProjectionCurrent(targetDir, runners) {
528
534
  }
529
535
  }
530
536
 
531
- function assertManagedFilesCurrent(targetDir, lock) {
537
+ export function validateAppProjectInputs(targetDir, manifest, packageJson, managed = false, plannedSources) {
538
+ assertManifestAppAccessDeclaration(stringifyYaml(manifest), 'nimi.app.yaml');
539
+ const rendererOrigin = assertElectronLocalDevelopmentManifest(manifest);
540
+ assertOfficialDevelopmentEntrypoints(targetDir, rendererOrigin, packageJson);
541
+ const findings = scanForbiddenPatterns(targetDir, manifest.profile, managed ? null : LOCAL_DEVELOPMENT_BYPASS_LABELS, plannedSources);
542
+ if (findings.length) throw new Error(`Forbidden App source patterns: ${findings.join('; ')}`);
543
+ }
544
+
545
+ export function validateManagedAppFiles(targetDir, lock, plannedSources) {
546
+ assertManagedFilesCurrent(targetDir, lock, plannedSources);
547
+ }
548
+
549
+ function assertManagedFilesCurrent(targetDir, lock, plannedSources) {
532
550
  const drift = [];
533
551
  for (const [relativePath, entry] of Object.entries(lock.managedFileHashes || {})) {
534
552
  const absolutePath = path.join(targetDir, relativePath);
535
- if (!existsSync(absolutePath)) {
553
+ const content = plannedSources?.has(relativePath)
554
+ ? plannedSources.get(relativePath)
555
+ : existsSync(absolutePath) ? readContentForHash(absolutePath) : null;
556
+ if (content === null) {
536
557
  drift.push(`${relativePath}: missing`);
537
558
  continue;
538
559
  }
539
- const currentHash = hashScaffoldManagedContent(relativePath, readContentForHash(absolutePath));
560
+ const currentHash = hashScaffoldManagedContent(relativePath, content);
540
561
  if (currentHash !== entry.sha256) {
541
562
  drift.push(`${relativePath}: sha256 drift`);
542
563
  }
@@ -551,8 +572,10 @@ function validateAppProjectState(targetDir, versions, runners = {}) {
551
572
  if (existsSync(path.join(targetDir, SCAFFOLD_INTENT_PATH))) {
552
573
  readLock(targetDir);
553
574
  }
575
+ assertLifecycleGuidanceCurrent(targetDir);
554
576
  return validateExistingSubmittedApp(targetDir);
555
577
  }
578
+ assertLifecycleGuidanceCurrent(targetDir);
556
579
  const lock = readLock(targetDir);
557
580
  const intent = readIntent(targetDir);
558
581
  const snapshot = expectedSnapshotFromLock(lock, versions, intent, targetDir);
@@ -609,16 +632,34 @@ function validateExistingSubmittedApp(targetDir) {
609
632
  export function initApp(cwd, options = {}, versions, runners = {}) {
610
633
  const targetDir = resolveTargetDir(cwd, options);
611
634
  const intent = readIntent(targetDir);
635
+ const currentManifest = readCurrentAppManifest(targetDir);
612
636
  const snapshot = buildAppScaffoldSnapshotFromIntent({ intent, versions, targetDir });
637
+ validateAppProjectInputs(targetDir, currentManifest, readJsonFile(path.join(targetDir, 'package.json')), true);
638
+ const initializedPaths = new Set(snapshot.initFiles.map((file) => file.path));
639
+ assertManagedFilesCurrent(targetDir, { managedFileHashes: Object.fromEntries(Object.entries(snapshot.lock.managedFileHashes).filter(([relativePath]) => !initializedPaths.has(relativePath))) });
640
+ const planned = [...planLifecycleGuidance(targetDir), ...snapshot.initFiles.map((file) => plannedFile(targetDir, file.path, file.content))];
641
+ const preview = {
642
+ ok: true, command: 'init', dir: targetDir, dryRun: options.dryRun === true,
643
+ skillPath: LIFECYCLE_SKILL_PATH, changes: describeChanges(targetDir, planned), ownerSteps: lifecycleOwnerSteps(versions),
644
+ };
645
+ if (options.dryRun) {
646
+ process.stdout.write(`${options.json ? JSON.stringify(preview, null, 2) : `[nimi-app] init preview: ${preview.changes.map((file) => `${file.action} ${file.path}`).join(', ')}`}\n`);
647
+ return preview;
648
+ }
613
649
  if (!runners?.runNimicodingSync) {
614
650
  throw new Error('Missing nimicoding sync runner');
615
651
  }
616
652
  const nimicoding = runners.runNimicodingSync(targetDir, 'apply');
617
- for (const file of snapshot.initFiles) {
618
- writeScaffoldFile(targetDir, file);
619
- }
653
+ // The owner may have added its own AGENTS block; compose ours afterward.
654
+ const lockFile = planned.find((file) => file.path === path.join(targetDir, SCAFFOLD_LOCK_PATH));
655
+ applyProjectFiles(targetDir, [...planned.filter((file) => file !== lockFile), ...planLifecycleGuidance(targetDir)]);
656
+ assertProjectConfiguration(targetDir);
657
+ assertManagedFilesCurrent(targetDir, snapshot.lock);
658
+ assertNimicodingProjectionCurrent(targetDir, runners);
659
+ applyProjectFiles(targetDir, [lockFile]);
620
660
  validateAppProjectState(targetDir, versions, runners);
621
661
  const payload = {
662
+ ...preview,
622
663
  ok: true,
623
664
  command: 'init',
624
665
  dir: targetDir,
@@ -703,25 +744,23 @@ function assertNoClassificationConflict(lock, snapshot) {
703
744
  }
704
745
  }
705
746
 
706
- function writeScaffoldFile(targetDir, file) {
707
- const targetPath = path.join(targetDir, file.path);
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
- }
718
- writeFileSync(targetPath, file.content);
747
+ function readCurrentAppManifest(targetDir) {
748
+ const manifestPath = path.join(targetDir, 'nimi.app.yaml');
749
+ if (!existsSync(manifestPath)) return undefined;
750
+ let manifest;
751
+ try { manifest = parseYaml(readFileSync(manifestPath, 'utf8')); }
752
+ catch (error) { throw new Error(`nimi.app.yaml is invalid: ${error.message}`, { cause: error }); }
753
+ if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) {
754
+ throw new Error('nimi.app.yaml must contain an App declaration mapping before init or sync');
755
+ }
756
+ return manifest;
719
757
  }
720
758
 
721
- export function syncManagedApp(cwd, options = {}, versions, runners = {}) {
759
+ export function planManagedAppSync(cwd, options = {}, versions) {
722
760
  const targetDir = resolveTargetDir(cwd, options);
723
761
  const lock = readLock(targetDir);
724
762
  const intent = readIntent(targetDir);
763
+ const currentManifest = readCurrentAppManifest(targetDir);
725
764
  const packageJson = readJsonFile(path.join(targetDir, 'package.json'), 'package.json');
726
765
  const versionedIntent = {
727
766
  ...intent,
@@ -731,43 +770,17 @@ export function syncManagedApp(cwd, options = {}, versions, runners = {}) {
731
770
  version: packageJson.version,
732
771
  },
733
772
  };
734
- const snapshot = expectedSnapshotFromLock(lock, versions, versionedIntent, targetDir, { allowDerivedAppAccessDrift: true });
773
+ const snapshot = expectedSnapshotFromLock(lock, versions, versionedIntent, targetDir, { refreshDerived: true });
735
774
  assertNoClassificationConflict(lock, snapshot);
736
- if (!runners?.runNimicodingSync) {
737
- throw new Error('Missing nimicoding sync runner');
738
- }
739
- runners.runNimicodingSync(targetDir, 'apply');
740
-
741
- for (const file of snapshot.filesWithoutLock) {
742
- const managedEntry = snapshot.lock.managedFileHashes[file.path];
743
- if (!managedEntry) {
744
- continue;
775
+ const planned = snapshot.filesWithoutLock.filter((file) => snapshot.lock.managedFileHashes[file.path]).map((file) => {
776
+ let content = file.content;
777
+ if (file.path === 'nimi.app.yaml' && currentManifest) {
778
+ const next = parseYaml(content);
779
+ for (const field of APP_AUTHOR_DECLARATION_FIELDS) if (Object.hasOwn(currentManifest, field)) next[field] = currentManifest[field];
780
+ content = stringifyYaml(next, { lineWidth: 0 });
745
781
  }
746
- writeScaffoldFile(targetDir, file);
747
- }
748
- writeScaffoldFile(targetDir, {
749
- path: SCAFFOLD_LOCK_PATH,
750
- content: `${JSON.stringify(snapshot.lock, null, 2)}\n`,
782
+ return plannedFile(targetDir, file.path, content);
751
783
  });
752
-
753
- validateAppProjectState(targetDir, versions, runners);
754
- const payload = {
755
- ok: true,
756
- command: 'sync',
757
- dir: targetDir,
758
- scaffoldVersion: snapshot.lock.scaffoldVersion,
759
- profile: snapshot.lock.profile,
760
- appId: snapshot.lock.appId,
761
- features: snapshot.lock.features,
762
- refreshedManagedFiles: Object.keys(snapshot.lock.managedFileHashes).length,
763
- };
764
- if (options.silent) {
765
- return payload;
766
- }
767
- if (options.json) {
768
- process.stdout.write(`${JSON.stringify(payload, null, 2)}\n`);
769
- } else {
770
- process.stdout.write(`[nimi-app] sync refreshed managed scaffold files at ${targetDir}\n`);
771
- }
772
- return payload;
784
+ planned.push(...planLifecycleGuidance(targetDir), plannedFile(targetDir, SCAFFOLD_LOCK_PATH, `${JSON.stringify(snapshot.lock, null, 2)}\n`));
785
+ return { targetDir, snapshot, planned };
773
786
  }
package/lib/app-info.mjs CHANGED
@@ -71,7 +71,8 @@ function storage(value) {
71
71
  function https(value, field) {
72
72
  if (value === undefined || value === '') return '';
73
73
  text(value, field, 2048);
74
- const url = new URL(value);
74
+ let url;
75
+ try { url = new URL(value); } catch { throw new Error(`App info ${field} must be a valid HTTPS URL without credentials`); }
75
76
  if (url.protocol !== 'https:' || !url.hostname || url.username || url.password) throw new Error(`App info ${field} must be HTTPS without credentials`);
76
77
  return value;
77
78
  }
@@ -105,9 +106,15 @@ function resource(root, relative, label, maxBytes) {
105
106
  if (typeof relative !== 'string' || path.isAbsolute(relative) || relative.includes('\\')
106
107
  || relative.split('/').some((part) => !part || part === '.' || part === '..')) throw new Error(`metadata.${label} must name an App-relative resource`);
107
108
  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);
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
+ }
111
118
  }
112
119
 
113
120
  export function readAppInfo(root, targetId) {