@nimiplatform/app-tools 0.5.1 → 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.
@@ -280,15 +355,19 @@ declares the tested public SDK, Kit and Tauri shell versions used by new Apps an
280
355
  explicit `sync`; workspace development version bumps do not change those ranges.
281
356
  The release workflow requires those public versions before publishing App Tools.
282
357
 
283
- App Tools 0.5.1 uses SDK `^0.11.0` and Kit `^0.7.0`. Existing Apps upgrade explicitly:
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:
284
363
 
285
364
  ```bash
286
- pnpm add -D @nimiplatform/app-tools@^0.5.1
287
- pnpm run sync
365
+ pnpm exec nimi-app sync --dry-run --json
366
+ pnpm exec nimi-app sync
288
367
  pnpm install
289
- pnpm run check
290
- pnpm run test
291
- pnpm run app:build -- --target windows-x86_64
368
+ pnpm exec nimi-app check
369
+ pnpm exec nimi-app test
370
+ pnpm exec nimi-app build --target windows-x86_64
292
371
  ```
293
372
 
294
373
  Use the App's declared target for the final build. `sync` preserves App-owned
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
  };
@@ -346,7 +343,7 @@ function buildForbiddenPatterns() {
346
343
  }
347
344
 
348
345
  // @nimi-authority: rule.nimi.platform.app-ecosystem.p-scaf-016b
349
- function scanForbiddenPatterns(targetDir, profile, selectedLabels = null) {
346
+ function scanForbiddenPatterns(targetDir, profile, selectedLabels = null, plannedSources) {
350
347
  const findings = [];
351
348
  const patterns = buildForbiddenPatterns();
352
349
  const testFileAllowedLabels = new Set([
@@ -362,9 +359,15 @@ function scanForbiddenPatterns(targetDir, profile, selectedLabels = null) {
362
359
  'renderer or app storage of protected material',
363
360
  'environment custody of protected material',
364
361
  ]);
365
- for (const filePath of collectTextFiles(targetDir)) {
366
- const relativePath = path.relative(targetDir, filePath).split(path.sep).join('/');
367
- 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');
368
371
  const isManagedReleaseWorkflow = relativePath === '.github/workflows/nimi-app-release.yml'
369
372
  && text.replaceAll('\r\n', '\n') === managedAppReleaseWorkflowSource();
370
373
  const isTestFile = /^(?:test|tests)\//.test(relativePath) || /(?:^|\/)\w[^/]*\.(?:test|spec)\.[cm]?[jt]sx?$/i.test(relativePath);
@@ -484,8 +487,7 @@ function assertElectronLocalDevelopmentManifest(document) {
484
487
  return parsed.origin;
485
488
  }
486
489
 
487
- function assertOfficialDevelopmentEntrypoints(targetDir, rendererOrigin) {
488
- const packageJson = readJsonFile(path.join(targetDir, 'package.json'), 'package.json');
490
+ function assertOfficialDevelopmentEntrypoints(targetDir, rendererOrigin, packageJson = readJsonFile(path.join(targetDir, 'package.json'), 'package.json')) {
489
491
  const scripts = packageJson?.scripts;
490
492
  if (!scripts || typeof scripts !== 'object' || Array.isArray(scripts)) {
491
493
  throw new Error('package.json scripts are required');
@@ -532,15 +534,30 @@ function assertNimicodingProjectionCurrent(targetDir, runners) {
532
534
  }
533
535
  }
534
536
 
535
- 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) {
536
550
  const drift = [];
537
551
  for (const [relativePath, entry] of Object.entries(lock.managedFileHashes || {})) {
538
552
  const absolutePath = path.join(targetDir, relativePath);
539
- if (!existsSync(absolutePath)) {
553
+ const content = plannedSources?.has(relativePath)
554
+ ? plannedSources.get(relativePath)
555
+ : existsSync(absolutePath) ? readContentForHash(absolutePath) : null;
556
+ if (content === null) {
540
557
  drift.push(`${relativePath}: missing`);
541
558
  continue;
542
559
  }
543
- const currentHash = hashScaffoldManagedContent(relativePath, readContentForHash(absolutePath));
560
+ const currentHash = hashScaffoldManagedContent(relativePath, content);
544
561
  if (currentHash !== entry.sha256) {
545
562
  drift.push(`${relativePath}: sha256 drift`);
546
563
  }
@@ -555,8 +572,10 @@ function validateAppProjectState(targetDir, versions, runners = {}) {
555
572
  if (existsSync(path.join(targetDir, SCAFFOLD_INTENT_PATH))) {
556
573
  readLock(targetDir);
557
574
  }
575
+ assertLifecycleGuidanceCurrent(targetDir);
558
576
  return validateExistingSubmittedApp(targetDir);
559
577
  }
578
+ assertLifecycleGuidanceCurrent(targetDir);
560
579
  const lock = readLock(targetDir);
561
580
  const intent = readIntent(targetDir);
562
581
  const snapshot = expectedSnapshotFromLock(lock, versions, intent, targetDir);
@@ -615,15 +634,32 @@ export function initApp(cwd, options = {}, versions, runners = {}) {
615
634
  const intent = readIntent(targetDir);
616
635
  const currentManifest = readCurrentAppManifest(targetDir);
617
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
+ }
618
649
  if (!runners?.runNimicodingSync) {
619
650
  throw new Error('Missing nimicoding sync runner');
620
651
  }
621
652
  const nimicoding = runners.runNimicodingSync(targetDir, 'apply');
622
- for (const file of snapshot.initFiles) {
623
- writeScaffoldFile(targetDir, file, currentManifest);
624
- }
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]);
625
660
  validateAppProjectState(targetDir, versions, runners);
626
661
  const payload = {
662
+ ...preview,
627
663
  ok: true,
628
664
  command: 'init',
629
665
  dir: targetDir,
@@ -720,21 +756,7 @@ function readCurrentAppManifest(targetDir) {
720
756
  return manifest;
721
757
  }
722
758
 
723
- function writeScaffoldFile(targetDir, file, currentManifest) {
724
- const targetPath = path.join(targetDir, file.path);
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
- }
734
- writeFileSync(targetPath, file.content);
735
- }
736
-
737
- export function syncManagedApp(cwd, options = {}, versions, runners = {}) {
759
+ export function planManagedAppSync(cwd, options = {}, versions) {
738
760
  const targetDir = resolveTargetDir(cwd, options);
739
761
  const lock = readLock(targetDir);
740
762
  const intent = readIntent(targetDir);
@@ -748,43 +770,17 @@ export function syncManagedApp(cwd, options = {}, versions, runners = {}) {
748
770
  version: packageJson.version,
749
771
  },
750
772
  };
751
- const snapshot = expectedSnapshotFromLock(lock, versions, versionedIntent, targetDir, { allowDerivedAppAccessDrift: true });
773
+ const snapshot = expectedSnapshotFromLock(lock, versions, versionedIntent, targetDir, { refreshDerived: true });
752
774
  assertNoClassificationConflict(lock, snapshot);
753
- if (!runners?.runNimicodingSync) {
754
- throw new Error('Missing nimicoding sync runner');
755
- }
756
- runners.runNimicodingSync(targetDir, 'apply');
757
-
758
- for (const file of snapshot.filesWithoutLock) {
759
- const managedEntry = snapshot.lock.managedFileHashes[file.path];
760
- if (!managedEntry) {
761
- 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 });
762
781
  }
763
- writeScaffoldFile(targetDir, file, currentManifest);
764
- }
765
- writeScaffoldFile(targetDir, {
766
- path: SCAFFOLD_LOCK_PATH,
767
- content: `${JSON.stringify(snapshot.lock, null, 2)}\n`,
782
+ return plannedFile(targetDir, file.path, content);
768
783
  });
769
-
770
- validateAppProjectState(targetDir, versions, runners);
771
- const payload = {
772
- ok: true,
773
- command: 'sync',
774
- dir: targetDir,
775
- scaffoldVersion: snapshot.lock.scaffoldVersion,
776
- profile: snapshot.lock.profile,
777
- appId: snapshot.lock.appId,
778
- features: snapshot.lock.features,
779
- refreshedManagedFiles: Object.keys(snapshot.lock.managedFileHashes).length,
780
- };
781
- if (options.silent) {
782
- return payload;
783
- }
784
- if (options.json) {
785
- process.stdout.write(`${JSON.stringify(payload, null, 2)}\n`);
786
- } else {
787
- process.stdout.write(`[nimi-app] sync refreshed managed scaffold files at ${targetDir}\n`);
788
- }
789
- return payload;
784
+ planned.push(...planLifecycleGuidance(targetDir), plannedFile(targetDir, SCAFFOLD_LOCK_PATH, `${JSON.stringify(snapshot.lock, null, 2)}\n`));
785
+ return { targetDir, snapshot, planned };
790
786
  }
@@ -0,0 +1,90 @@
1
+ import { existsSync, lstatSync, readdirSync, readFileSync } from 'node:fs';
2
+ import { fileURLToPath } from 'node:url';
3
+ import path from 'node:path';
4
+ import { assertProjectOutputPath, changedFiles, plannedFile } from './app-project-files.mjs';
5
+
6
+ export const LIFECYCLE_SKILL_PATH = fileURLToPath(new URL('../skills/nimi-app-lifecycle/SKILL.md', import.meta.url));
7
+ export const PROJECT_SKILL_DIR = '.agents/skills/nimi-app-lifecycle';
8
+ const SKILL_FILES = ['SKILL.md', ...['create', 'adapt', 'upgrade-platform', 'sync-upstream', 'release', 'acceptance'].map((name) => `references/${name}.md`)];
9
+ const START = '<!-- nimi-app:managed:start -->';
10
+ const END = '<!-- nimi-app:managed:end -->';
11
+ const AGENTS_BLOCK = `${START}
12
+ ## Nimi App development
13
+
14
+ - For creating, adapting, upgrading or releasing this App, read [the lifecycle skill](.agents/skills/nimi-app-lifecycle/SKILL.md) and only the relevant scenario.
15
+ - Keep App-owned product behavior, Host code, business accounts and non-AI services with this repository. Use the SDK/Kit Local App carrier for Nimi AI, configuration, storage and session access.
16
+ - App Tools owns its lifecycle skill, this block, managed workflow and declared engineering fields; preserve other instructions, product source and licenses. Existing adoption does not create fresh scaffold intent or lock.
17
+ - Product-operation guides apply to their specific business tasks; they do not replace the Nimi development boundary.
18
+ - Reuse the user's confirmed scope and authorization. Report command checks separately from actual App journeys; unrun relevant paths remain NOT-VERIFIED.
19
+ ${END}`;
20
+
21
+ function readAgentsBlock(source) {
22
+ const starts = source.split(START).length - 1;
23
+ const ends = source.split(END).length - 1;
24
+ if (!starts && !ends) return null;
25
+ if (starts !== 1 || ends !== 1 || source.indexOf(END) < source.indexOf(START)) {
26
+ throw new Error('AGENTS.md contains duplicate or unbalanced nimi-app managed markers');
27
+ }
28
+ return { start: source.indexOf(START), end: source.indexOf(END) + END.length };
29
+ }
30
+
31
+ export function hasLifecycleGuidanceOwner(targetDir) {
32
+ const agentsPath = path.join(targetDir, 'AGENTS.md');
33
+ assertProjectOutputPath(targetDir, agentsPath);
34
+ return existsSync(agentsPath) && readAgentsBlock(readFileSync(agentsPath, 'utf8')) !== null;
35
+ }
36
+
37
+ export function lifecycleSkillFiles() {
38
+ const sourceRoot = path.dirname(LIFECYCLE_SKILL_PATH);
39
+ return SKILL_FILES.map((name) => ({
40
+ path: `${PROJECT_SKILL_DIR}/${name}`,
41
+ content: readFileSync(path.join(sourceRoot, name), 'utf8'),
42
+ mutationClass: 'scaffold-managed glue',
43
+ ownerKind: 'lifecycle-guidance',
44
+ ownerId: 'nimi-app-lifecycle',
45
+ }));
46
+ }
47
+
48
+ // @nimi-authority: rule.nimi.platform.app-ecosystem.p-scaf-018d
49
+ export function planLifecycleGuidance(targetDir) {
50
+ const agentsPath = path.join(targetDir, 'AGENTS.md');
51
+ assertProjectOutputPath(targetDir, agentsPath);
52
+ assertProjectOutputPath(targetDir, path.join(targetDir, PROJECT_SKILL_DIR, 'SKILL.md'));
53
+ if (existsSync(agentsPath) && !lstatSync(agentsPath).isFile()) throw new Error('AGENTS.md must be a regular file');
54
+ const previous = existsSync(agentsPath) ? readFileSync(agentsPath, 'utf8') : '';
55
+ const block = readAgentsBlock(previous);
56
+ const content = block
57
+ ? previous.slice(0, block.start) + AGENTS_BLOCK + previous.slice(block.end)
58
+ : `${previous}${previous && !previous.endsWith('\n') ? '\n' : ''}${previous ? '\n' : ''}${AGENTS_BLOCK}\n`;
59
+ const planned = [plannedFile(targetDir, 'AGENTS.md', content)];
60
+ const expected = new Map(lifecycleSkillFiles().map((file) => [file.path, file]));
61
+ const root = path.join(targetDir, PROJECT_SKILL_DIR);
62
+ const visit = (directory) => {
63
+ if (!lstatSync(directory).isDirectory()) throw new Error(`Lifecycle skill directory collision: ${directory}`);
64
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
65
+ const filePath = path.join(directory, entry.name);
66
+ if (entry.isDirectory()) visit(filePath);
67
+ else if (!entry.isFile()) throw new Error(`Lifecycle skill file collision: ${filePath}`);
68
+ else {
69
+ const relativePath = path.relative(targetDir, filePath).split(path.sep).join('/');
70
+ const file = expected.get(relativePath);
71
+ if (!block && (!file || readFileSync(filePath, 'utf8') !== file.content)) {
72
+ throw new Error(`Unknown lifecycle skill content: ${relativePath}. Preserve or relocate it before adoption.`);
73
+ }
74
+ if (!file) planned.push(plannedFile(targetDir, relativePath, null));
75
+ }
76
+ }
77
+ };
78
+ if (existsSync(root)) visit(root);
79
+ for (const file of expected.values()) planned.push(plannedFile(targetDir, file.path, file.content));
80
+ return planned;
81
+ }
82
+
83
+ export function assertLifecycleGuidanceCurrent(targetDir) {
84
+ const drift = changedFiles(planLifecycleGuidance(targetDir));
85
+ if (drift.length) throw new Error(`Lifecycle guidance drift: ${drift.map((file) => path.relative(targetDir, file.path)).join(', ')}. Run nimi-app sync.`);
86
+ }
87
+
88
+ export function lifecycleOwnerSteps(versions) {
89
+ return [{ owner: '@nimiplatform/nimi-coding', version: versions.nimicodingVersion, command: 'nimicoding sync --apply --json', executor: 'project-local package bin.nimicoding via the current Node.js executable', previewed: false }];
90
+ }