@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.
@@ -0,0 +1,69 @@
1
+ import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { randomUUID } from 'node:crypto';
3
+ import path from 'node:path';
4
+
5
+ export function plannedFile(targetDir, relativePath, content) {
6
+ const filePath = path.join(targetDir, relativePath);
7
+ assertProjectOutputPath(targetDir, filePath);
8
+ return { path: filePath, content, previous: existsSync(filePath) ? readFileSync(filePath) : null };
9
+ }
10
+
11
+ export function assertProjectOutputPath(targetDir, filePath) {
12
+ const relative = path.relative(targetDir, filePath);
13
+ if (!relative || relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
14
+ throw new Error(`App output must stay in the project: ${filePath}`);
15
+ }
16
+ let current = targetDir;
17
+ const parts = relative.split(path.sep);
18
+ for (const [index, part] of parts.entries()) {
19
+ current = path.join(current, part);
20
+ let stat;
21
+ try { stat = lstatSync(current); }
22
+ catch (error) { if (error.code === 'ENOENT') break; throw error; }
23
+ if (stat.isSymbolicLink() || (index < parts.length - 1 && !stat.isDirectory())) {
24
+ throw new Error(`App output path collision: ${path.relative(targetDir, current)} must not be a symbolic link or non-directory ancestor`);
25
+ }
26
+ if (index === parts.length - 1 && !stat.isFile()) throw new Error(`App output file collision: ${relative}`);
27
+ }
28
+ }
29
+
30
+ export function changedFiles(planned) {
31
+ // Later normalization of the same owned file supplies its final content.
32
+ return [...new Map(planned.map((file) => [file.path, file])).values()].filter((file) => (
33
+ file.content === null ? file.previous !== null
34
+ : file.previous === null || !Buffer.from(file.content).equals(Buffer.from(file.previous))
35
+ ));
36
+ }
37
+
38
+ export function describeChanges(targetDir, planned) {
39
+ return changedFiles(planned).map((file) => ({
40
+ path: path.relative(targetDir, file.path).split(path.sep).join('/'),
41
+ action: file.content === null ? 'remove' : file.previous === null ? 'create' : 'update',
42
+ // Source text makes script/dependency/managed-block changes reviewable.
43
+ ...(path.extname(file.path).match(/^\.(?:json|ya?ml|md|[cm]?js|tsx?|toml|css)$/u)
44
+ ? { before: file.previous === null ? null : Buffer.from(file.previous).toString('utf8'), after: file.content === null ? null : Buffer.from(file.content).toString('utf8') }
45
+ : {}),
46
+ }));
47
+ }
48
+
49
+ export function applyProjectFiles(targetDir, planned) {
50
+ for (const file of planned) assertProjectOutputPath(targetDir, file.path);
51
+ const completed = [];
52
+ for (const file of changedFiles(planned)) {
53
+ const temporary = `${file.path}.${randomUUID()}.tmp`;
54
+ try {
55
+ if (file.content === null) rmSync(file.path);
56
+ else {
57
+ mkdirSync(path.dirname(file.path), { recursive: true });
58
+ writeFileSync(temporary, file.content);
59
+ renameSync(temporary, file.path);
60
+ }
61
+ completed.push(path.relative(targetDir, file.path).split(path.sep).join('/'));
62
+ } catch (cause) {
63
+ throw new Error(`App file update failed at ${path.relative(targetDir, file.path)}; completed files: ${completed.join(', ') || 'none'}. Fix the filesystem error and rerun the command.`, { cause });
64
+ } finally {
65
+ rmSync(temporary, { force: true });
66
+ }
67
+ }
68
+ return completed;
69
+ }
@@ -7,7 +7,9 @@ import path from 'node:path';
7
7
  import { parse as parseYaml, parseDocument as parseYamlDocument, stringify as stringifyYaml } from 'yaml';
8
8
 
9
9
  import { assertManifestAppAccessDeclaration } from './app-access-declaration.mjs';
10
- import { syncManagedApp, validateAppProject } from './app-doctor-update.mjs';
10
+ import { planManagedAppSync, validateAppProject, validateAppProjectInputs, validateManagedAppFiles } from './app-doctor-update.mjs';
11
+ import { LIFECYCLE_SKILL_PATH, hasLifecycleGuidanceOwner, lifecycleOwnerSteps, planLifecycleGuidance } from './app-lifecycle-guidance.mjs';
12
+ import { applyProjectFiles, describeChanges, plannedFile } from './app-project-files.mjs';
11
13
  import {
12
14
  SCAFFOLD_INTENT_PATH,
13
15
  SCAFFOLD_LOCK_PATH,
@@ -16,6 +18,7 @@ import {
16
18
  renderAppBuildProfile,
17
19
  renderAppIdentityInput,
18
20
  renderAppSubmissionInput,
21
+ renderScaffoldBoundary,
19
22
  } from './app-scaffold.mjs';
20
23
  import { validateAppScaffoldNpmRegistryVersion } from './app-scaffold-capabilities.mjs';
21
24
 
@@ -63,12 +66,22 @@ function readJsonFile(filePath, label) {
63
66
  }
64
67
  }
65
68
 
66
- function readSubmittedManifest(targetDir) {
69
+ function hasProjectFile(targetDir, relativePath, sources) {
70
+ return sources?.has(relativePath) ? sources.get(relativePath) !== null : existsSync(path.join(targetDir, relativePath));
71
+ }
72
+
73
+ function readProjectText(targetDir, relativePath, sources) {
74
+ return sources?.has(relativePath)
75
+ ? Buffer.from(sources.get(relativePath)).toString('utf8')
76
+ : readFileSync(path.join(targetDir, relativePath), 'utf8');
77
+ }
78
+
79
+ function readSubmittedManifest(targetDir, sources) {
67
80
  const manifestPath = path.join(targetDir, 'nimi.app.yaml');
68
- if (!existsSync(manifestPath)) {
81
+ if (!hasProjectFile(targetDir, 'nimi.app.yaml', sources)) {
69
82
  throw new Error('Existing submitted app requires nimi.app.yaml');
70
83
  }
71
- const source = readFileSync(manifestPath, 'utf8');
84
+ const source = readProjectText(targetDir, 'nimi.app.yaml', sources);
72
85
  assertManifestAppAccessDeclaration(source, manifestPath);
73
86
  let document;
74
87
  try {
@@ -401,10 +414,10 @@ function normalizePnpmWorkspace(targetDir) {
401
414
  };
402
415
  }
403
416
 
404
- function assertPnpmWorkspaceCurrent(targetDir) {
417
+ function assertPnpmWorkspaceCurrent(targetDir, sources) {
405
418
  const workspacePath = path.join(targetDir, 'pnpm-workspace.yaml');
406
- if (!existsSync(workspacePath)) return;
407
- const source = readFileSync(workspacePath, 'utf8');
419
+ if (!hasProjectFile(targetDir, 'pnpm-workspace.yaml', sources)) return;
420
+ const source = readProjectText(targetDir, 'pnpm-workspace.yaml', sources);
408
421
  const workspace = parseYamlFile(source, workspacePath);
409
422
  const overrides = workspace?.overrides;
410
423
  if (overrides !== undefined && (!overrides || typeof overrides !== 'object' || Array.isArray(overrides))) {
@@ -565,12 +578,12 @@ function assertTauriConfigCurrent(config, appId) {
565
578
  }
566
579
  }
567
580
 
568
- function normalizeStandaloneSourceFiles(targetDir) {
581
+ function normalizeStandaloneSourceFiles(targetDir, sources) {
569
582
  const planned = [];
570
583
  for (const name of ['vite.config.ts', 'vite.config.js', 'vite.config.mjs']) {
571
584
  const filePath = path.join(targetDir, name);
572
- if (!existsSync(filePath)) continue;
573
- const previous = readFileSync(filePath, 'utf8');
585
+ if (!hasProjectFile(targetDir, name, sources)) continue;
586
+ const previous = readProjectText(targetDir, name, sources);
574
587
  let content = previous
575
588
  .replace(/^const nimiRepoRoot\s*=.*\r?\n/gmu, '')
576
589
  .replace(/^const nimiSdkSourceRoot\s*=.*\r?\n/gmu, '')
@@ -582,8 +595,8 @@ function normalizeStandaloneSourceFiles(targetDir) {
582
595
  planned.push({ path: filePath, content, previous });
583
596
  }
584
597
  const stylesPath = path.join(targetDir, 'src', 'styles.css');
585
- if (existsSync(stylesPath)) {
586
- const previous = readFileSync(stylesPath, 'utf8');
598
+ if (hasProjectFile(targetDir, 'src/styles.css', sources)) {
599
+ const previous = readProjectText(targetDir, 'src/styles.css', sources);
587
600
  const content = previous.replace(
588
601
  /^@source\s+["'][^"']*\/nimi\/kit\/\*\*\/\*\.\{ts,tsx\}["'];?\r?$/gmu,
589
602
  '@source "../node_modules/@nimiplatform/kit/**/*.{js,mjs,ts,tsx}";',
@@ -593,11 +606,11 @@ function normalizeStandaloneSourceFiles(targetDir) {
593
606
  return planned;
594
607
  }
595
608
 
596
- function assertNoStandaloneParentSources(targetDir) {
609
+ function assertNoStandaloneParentSources(targetDir, sources) {
597
610
  for (const relativePath of ['vite.config.ts', 'vite.config.js', 'vite.config.mjs', 'src/styles.css']) {
598
611
  const filePath = path.join(targetDir, ...relativePath.split('/'));
599
- if (!existsSync(filePath)) continue;
600
- const source = readFileSync(filePath, 'utf8');
612
+ if (!hasProjectFile(targetDir, relativePath, sources)) continue;
613
+ const source = readProjectText(targetDir, relativePath, sources);
601
614
  if (
602
615
  /nimiRepoRoot|nimiSdkSourceRoot|nimiKitSourceRoot|\/nimi-realm\/nimi\/(?:sdks|kit)\//u.test(source)
603
616
  || /find:\s*\/\^@nimiplatform\\\/(?:sdk|kit)(?:\\\/|\$)/u.test(source)
@@ -626,13 +639,13 @@ function tauriIdentifierFromAppId(appId) {
626
639
  return `ai.nimi.apps.${appId}`;
627
640
  }
628
641
 
629
- function readProjectLifecycleFiles(targetDir, buildProfileRef) {
642
+ function readProjectLifecycleFiles(targetDir, buildProfileRef, sources) {
630
643
  const packagePath = path.join(targetDir, 'package.json');
631
644
  if (!existsSync(packagePath)) throw new Error('Required App lifecycle file is missing: package.json');
632
645
  const files = {
633
646
  packagePath,
634
- packageSource: readFileSync(packagePath, 'utf8'),
635
- packageJson: readJsonFile(packagePath, 'package.json'),
647
+ packageSource: readProjectText(targetDir, 'package.json', sources),
648
+ packageJson: JSON.parse(readProjectText(targetDir, 'package.json', sources)),
636
649
  cargoPath: null,
637
650
  cargoSource: null,
638
651
  tauriPath: null,
@@ -645,9 +658,9 @@ function readProjectLifecycleFiles(targetDir, buildProfileRef) {
645
658
  for (const requiredPath of [files.cargoPath, files.tauriPath]) {
646
659
  if (!existsSync(requiredPath)) throw new Error(`Required App lifecycle file is missing: ${path.relative(targetDir, requiredPath)}`);
647
660
  }
648
- files.cargoSource = readFileSync(files.cargoPath, 'utf8');
649
- files.tauriSource = readFileSync(files.tauriPath, 'utf8');
650
- files.tauriConfig = readJsonFile(files.tauriPath, 'src-tauri/tauri.conf.json');
661
+ files.cargoSource = readProjectText(targetDir, 'src-tauri/Cargo.toml', sources);
662
+ files.tauriSource = readProjectText(targetDir, 'src-tauri/tauri.conf.json', sources);
663
+ files.tauriConfig = JSON.parse(files.tauriSource);
651
664
  return files;
652
665
  }
653
666
 
@@ -701,12 +714,12 @@ function assertVersionLockstep(files, descriptor, buildProfileRef) {
701
714
  return version;
702
715
  }
703
716
 
704
- function assertCanonicalAuthoringInputs(targetDir, descriptor, files, version, nativeIdentity) {
717
+ function assertCanonicalAuthoringInputs(targetDir, descriptor, files, version, nativeIdentity, sources) {
705
718
  const identityPath = path.join(targetDir, APP_IDENTITY_PATH);
706
719
  const submissionPath = path.join(targetDir, SUBMISSION_PATH);
707
- if (!existsSync(identityPath)) throw new Error(`Required App lifecycle file is missing: ${APP_IDENTITY_PATH}`);
708
- if (!existsSync(submissionPath)) throw new Error(`Required App lifecycle file is missing: ${SUBMISSION_PATH}`);
709
- const identity = assertExactKeys(parseYamlFile(readFileSync(identityPath, 'utf8'), identityPath), APP_IDENTITY_PATH, [
720
+ if (!hasProjectFile(targetDir, APP_IDENTITY_PATH, sources)) throw new Error(`Required App lifecycle file is missing: ${APP_IDENTITY_PATH}`);
721
+ if (!hasProjectFile(targetDir, SUBMISSION_PATH, sources)) throw new Error(`Required App lifecycle file is missing: ${SUBMISSION_PATH}`);
722
+ const identity = assertExactKeys(parseYamlFile(readProjectText(targetDir, APP_IDENTITY_PATH, sources), identityPath), APP_IDENTITY_PATH, [
710
723
  'app_id', 'display_name', 'version', 'npm_package_name', 'cargo_package_name', 'tauri_identifier', 'package_author', 'identity_role',
711
724
  ]);
712
725
  const packageAuthor = files.packageJson.author === undefined ? null : files.packageJson.author;
@@ -725,7 +738,7 @@ function assertCanonicalAuthoringInputs(targetDir, descriptor, files, version, n
725
738
  if (identity[key] !== expected) throw new Error(`${APP_IDENTITY_PATH} ${key} must match its canonical owner`);
726
739
  }
727
740
 
728
- const submission = assertExactKeys(parseYamlFile(readFileSync(submissionPath, 'utf8'), submissionPath), SUBMISSION_PATH, [
741
+ const submission = assertExactKeys(parseYamlFile(readProjectText(targetDir, SUBMISSION_PATH, sources), submissionPath), SUBMISSION_PATH, [
729
742
  'app_id',
730
743
  'display_name',
731
744
  'version',
@@ -776,14 +789,14 @@ function assertCanonicalAuthoringInputs(targetDir, descriptor, files, version, n
776
789
  return { identity, submission };
777
790
  }
778
791
 
779
- function assertManagedWorkflowCurrent(targetDir) {
792
+ function assertManagedWorkflowCurrent(targetDir, sources) {
780
793
  const workflowPath = path.join(targetDir, MANAGED_WORKFLOW_PATH);
781
- if (!existsSync(workflowPath)) throw new Error(`Required App lifecycle file is missing: ${MANAGED_WORKFLOW_PATH}`);
782
- if (readFileSync(workflowPath, 'utf8') !== managedAppReleaseWorkflowSource()) {
794
+ if (!hasProjectFile(targetDir, MANAGED_WORKFLOW_PATH, sources)) throw new Error(`Required App lifecycle file is missing: ${MANAGED_WORKFLOW_PATH}`);
795
+ if (readProjectText(targetDir, MANAGED_WORKFLOW_PATH, sources) !== managedAppReleaseWorkflowSource()) {
783
796
  throw new Error(`${MANAGED_WORKFLOW_PATH} must match the app-tools managed workflow`);
784
797
  }
785
798
  const workflowDir = path.dirname(workflowPath);
786
- for (const name of readdirSync(workflowDir).sort()) {
799
+ for (const name of existsSync(workflowDir) ? readdirSync(workflowDir).sort() : []) {
787
800
  const candidatePath = path.join(workflowDir, name);
788
801
  if (candidatePath === workflowPath || !/\.ya?ml$/iu.test(name)) continue;
789
802
  const source = readFileSync(candidatePath, 'utf8');
@@ -821,10 +834,10 @@ function canonicalProjectPath(value, field) {
821
834
  return value;
822
835
  }
823
836
 
824
- function readBuildProfile(targetDir) {
837
+ function readBuildProfile(targetDir, sources) {
825
838
  const filePath = path.join(targetDir, BUILD_PROFILE_PATH);
826
- if (!existsSync(filePath)) throw new Error(`Required App lifecycle file is missing: ${BUILD_PROFILE_PATH}`);
827
- const profile = parseYamlFile(readFileSync(filePath, 'utf8'), filePath);
839
+ if (!hasProjectFile(targetDir, BUILD_PROFILE_PATH, sources)) throw new Error(`Required App lifecycle file is missing: ${BUILD_PROFILE_PATH}`);
840
+ const profile = parseYamlFile(readProjectText(targetDir, BUILD_PROFILE_PATH, sources), filePath);
828
841
  if (!profile || typeof profile !== 'object' || Array.isArray(profile)) {
829
842
  throw new Error(`${BUILD_PROFILE_PATH} must contain an object`);
830
843
  }
@@ -925,9 +938,10 @@ function runOwnerCommand(targetDir, kind, command, options, runners) {
925
938
  }
926
939
 
927
940
  function assertProjectLifecycleCurrent(targetDir, versions, options = {}) {
928
- const descriptor = readSubmittedManifest(targetDir);
929
- const buildProfile = readBuildProfile(targetDir);
930
- const files = readProjectLifecycleFiles(targetDir, buildProfile.buildProfileRef);
941
+ const sources = options.sources;
942
+ const descriptor = readSubmittedManifest(targetDir, sources);
943
+ const buildProfile = readBuildProfile(targetDir, sources);
944
+ const files = readProjectLifecycleFiles(targetDir, buildProfile.buildProfileRef, sources);
931
945
  assertPackageManifestCurrent(files.packageJson, versions);
932
946
  const version = assertVersionLockstep(files, descriptor, buildProfile.buildProfileRef);
933
947
  let nativeIdentity = {
@@ -942,10 +956,10 @@ function assertProjectLifecycleCurrent(targetDir, versions, options = {}) {
942
956
  tauriIdentifier: files.tauriConfig.identifier,
943
957
  };
944
958
  }
945
- assertNoStandaloneParentSources(targetDir);
946
- const authoring = assertCanonicalAuthoringInputs(targetDir, descriptor, files, version, nativeIdentity);
947
- assertManagedWorkflowCurrent(targetDir);
948
- assertPnpmWorkspaceCurrent(targetDir);
959
+ assertNoStandaloneParentSources(targetDir, sources);
960
+ const authoring = assertCanonicalAuthoringInputs(targetDir, descriptor, files, version, nativeIdentity, sources);
961
+ assertManagedWorkflowCurrent(targetDir, sources);
962
+ assertPnpmWorkspaceCurrent(targetDir, sources);
949
963
  if (options.requireInstalledLock === true) {
950
964
  assertPnpmLockCurrent(targetDir, files.packageJson);
951
965
  if (buildProfile.buildProfileRef === TAURI_BUILD_PROFILE_REF) {
@@ -955,10 +969,10 @@ function assertProjectLifecycleCurrent(targetDir, versions, options = {}) {
955
969
  return { descriptor, files, version, buildProfile, authoring };
956
970
  }
957
971
 
958
- function buildExistingSubmittedAppSyncPlan(targetDir, versions) {
959
- const descriptor = readSubmittedManifest(targetDir);
960
- const buildProfile = readBuildProfile(targetDir);
961
- const files = readProjectLifecycleFiles(targetDir, buildProfile.buildProfileRef);
972
+ function buildExistingSubmittedAppSyncPlan(targetDir, versions, sources) {
973
+ const descriptor = readSubmittedManifest(targetDir, sources);
974
+ const buildProfile = readBuildProfile(targetDir, sources);
975
+ const files = readProjectLifecycleFiles(targetDir, buildProfile.buildProfileRef, sources);
962
976
  const version = files.packageJson.version;
963
977
  if (typeof version !== 'string' || !SEMVER_PATTERN.test(version)) {
964
978
  throw new Error('package.json version must be an exact semantic version before sync');
@@ -988,7 +1002,7 @@ function buildExistingSubmittedAppSyncPlan(targetDir, versions) {
988
1002
  );
989
1003
  identity.tauriIdentifier = tauriIdentifierFromAppId(descriptor.appId);
990
1004
  }
991
- planned.push(...normalizeStandaloneSourceFiles(targetDir));
1005
+ planned.push(...normalizeStandaloneSourceFiles(targetDir, sources));
992
1006
  const identityPath = path.join(targetDir, APP_IDENTITY_PATH);
993
1007
  planned.push({
994
1008
  path: identityPath,
@@ -996,7 +1010,7 @@ function buildExistingSubmittedAppSyncPlan(targetDir, versions) {
996
1010
  previous: existsSync(identityPath) ? readFileSync(identityPath, 'utf8') : '',
997
1011
  });
998
1012
  const submissionPath = path.join(targetDir, SUBMISSION_PATH);
999
- const currentSubmissionSource = existsSync(submissionPath) ? readFileSync(submissionPath, 'utf8') : '';
1013
+ const currentSubmissionSource = hasProjectFile(targetDir, SUBMISSION_PATH, sources) ? readProjectText(targetDir, SUBMISSION_PATH, sources) : '';
1000
1014
  const currentSubmission = currentSubmissionSource ? parseYamlFile(currentSubmissionSource, submissionPath) : null;
1001
1015
  let supportManifest;
1002
1016
  if (currentSubmission) {
@@ -1031,7 +1045,7 @@ function buildExistingSubmittedAppSyncPlan(targetDir, versions) {
1031
1045
  });
1032
1046
  planned.push({ path: submissionPath, content: submissionContent, previous: currentSubmissionSource });
1033
1047
  const buildProfilePath = path.join(targetDir, BUILD_PROFILE_PATH);
1034
- const currentBuildProfile = existsSync(buildProfilePath) ? readFileSync(buildProfilePath, 'utf8') : '';
1048
+ const currentBuildProfile = hasProjectFile(targetDir, BUILD_PROFILE_PATH, sources) ? readProjectText(targetDir, BUILD_PROFILE_PATH, sources) : '';
1035
1049
  const buildProfileInput = currentBuildProfile
1036
1050
  ? parseYamlFile(currentBuildProfile, buildProfilePath)
1037
1051
  : {};
@@ -1066,7 +1080,7 @@ function buildExistingSubmittedAppSyncPlan(targetDir, versions) {
1066
1080
  });
1067
1081
  const workspace = normalizePnpmWorkspace(targetDir);
1068
1082
  if (workspace) planned.push(workspace);
1069
- return { descriptor, planned, buildProfileRef: buildProfile.buildProfileRef };
1083
+ return { descriptor, planned: planned.map((file) => plannedFile(targetDir, path.relative(targetDir, file.path), file.content)), buildProfileRef: buildProfile.buildProfileRef };
1070
1084
  }
1071
1085
 
1072
1086
  function lifecycleNextSteps(buildProfileRef, versions) {
@@ -1095,49 +1109,117 @@ function emitResult(payload, options, message) {
1095
1109
  return payload;
1096
1110
  }
1097
1111
 
1098
- function applySyncPlan(targetDir, plan) {
1099
- const synchronizedFiles = [];
1100
- for (const file of plan.planned) {
1101
- if (file.content === file.previous) continue;
1102
- mkdirSync(path.dirname(file.path), { recursive: true });
1103
- writeFileSync(file.path, file.content);
1104
- synchronizedFiles.push(path.relative(targetDir, file.path).split(path.sep).join('/'));
1112
+ function planSources(targetDir, planned) {
1113
+ return new Map(planned.map((file) => [path.relative(targetDir, file.path).split(path.sep).join('/'), file.content]));
1114
+ }
1115
+
1116
+ function validateProjectPlan(targetDir, versions, planned, managed) {
1117
+ const sources = planSources(targetDir, planned);
1118
+ const current = assertProjectLifecycleCurrent(targetDir, versions, { sources });
1119
+ for (const target of Object.keys(current.buildProfile.targets)) selectBuildOwner(current.buildProfile, target);
1120
+ validateAppProjectInputs(targetDir, parseYaml(readProjectText(targetDir, 'nimi.app.yaml', sources)), current.files.packageJson, managed, sources);
1121
+ return current;
1122
+ }
1123
+
1124
+ export function validateAppInitialization(targetDir, versions) {
1125
+ const current = assertProjectLifecycleCurrent(targetDir, versions);
1126
+ for (const target of Object.keys(current.buildProfile.targets)) selectBuildOwner(current.buildProfile, target);
1127
+ }
1128
+
1129
+ function executeProjectPlan(targetDir, options, versions, runners, plan, scaffold) {
1130
+ if (scaffold) validateManagedAppFiles(targetDir, scaffold.snapshot.lock, planSources(targetDir, plan.planned));
1131
+ validateProjectPlan(targetDir, versions, plan.planned, Boolean(scaffold));
1132
+ const preview = {
1133
+ ok: true, command: options.adopt ? 'init' : 'sync', dir: targetDir,
1134
+ managed: Boolean(scaffold), appId: plan.descriptor.appId,
1135
+ dryRun: options.dryRun === true, skillPath: LIFECYCLE_SKILL_PATH,
1136
+ changes: describeChanges(targetDir, plan.planned), ownerSteps: lifecycleOwnerSteps(versions),
1137
+ nextSteps: lifecycleNextSteps(plan.buildProfileRef, versions),
1138
+ };
1139
+ if (options.dryRun) return emitResult(preview, options, `${preview.command} preview: ${preview.changes.map((file) => `${file.action} ${file.path}`).join(', ') || 'no app-tools changes'}`);
1140
+ const nimicoding = runNimicodingSync(targetDir, 'apply', runners);
1141
+ const lockPath = path.join(targetDir, SCAFFOLD_LOCK_PATH);
1142
+ const lockFile = plan.planned.find((file) => file.path === lockPath);
1143
+ const synchronizedFiles = applyProjectFiles(targetDir, [
1144
+ ...plan.planned.filter((file) => file !== lockFile),
1145
+ ...planLifecycleGuidance(targetDir),
1146
+ ]);
1147
+ assertProjectLifecycleCurrent(targetDir, versions);
1148
+ if (scaffold) {
1149
+ validateManagedAppFiles(targetDir, scaffold.snapshot.lock);
1150
+ synchronizedFiles.push(...applyProjectFiles(targetDir, [lockFile]));
1105
1151
  }
1106
- return synchronizedFiles;
1152
+ validateAppProject(targetDir, { silent: true }, versions, runners);
1153
+ return emitResult({ ...preview, synchronizedFiles, nimicodingSync: nimicoding?.summary || null }, options, `${preview.command} completed for ${targetDir}`);
1107
1154
  }
1108
1155
 
1156
+ // @nimi-authority: rule.nimi.platform.app-ecosystem.p-scaf-018c
1109
1157
  export function syncAppProject(cwd, options = {}, versions, runners = {}) {
1110
1158
  const targetDir = resolveTargetDir(cwd, options);
1111
1159
  assertNoRetiredScaffoldState(targetDir);
1112
- const managed = existsSync(path.join(targetDir, SCAFFOLD_LOCK_PATH));
1113
- if (managed) {
1114
- const refreshed = syncManagedApp(cwd, { dir: targetDir, silent: true }, versions, runners);
1115
- const plan = buildExistingSubmittedAppSyncPlan(targetDir, versions);
1116
- const synchronizedFiles = applySyncPlan(targetDir, plan);
1117
- validateAppProject(cwd, { dir: targetDir, silent: true }, versions, runners);
1118
- assertProjectLifecycleCurrent(targetDir, versions);
1119
- return emitResult({
1120
- ...refreshed,
1121
- managed: true,
1122
- synchronizedFiles,
1123
- nextSteps: lifecycleNextSteps(plan.buildProfileRef, versions),
1124
- }, options, `sync completed for ${targetDir}`);
1125
- }
1126
- const plan = managed ? null : buildExistingSubmittedAppSyncPlan(targetDir, versions);
1127
- const nimicoding = runNimicodingSync(targetDir, 'apply', runners);
1128
- const synchronizedFiles = applySyncPlan(targetDir, plan);
1129
- validateAppProject(cwd, { dir: targetDir, silent: true }, versions, runners);
1130
- assertProjectLifecycleCurrent(targetDir, versions);
1131
- return emitResult({
1132
- ok: true,
1133
- command: 'sync',
1134
- dir: targetDir,
1135
- managed,
1136
- appId: plan?.descriptor.appId || readSubmittedManifest(targetDir).appId,
1137
- synchronizedFiles,
1138
- nimicodingSync: nimicoding?.summary || null,
1139
- nextSteps: lifecycleNextSteps(plan.buildProfileRef, versions),
1140
- }, options, `sync completed for ${targetDir}`);
1160
+ const guidance = planLifecycleGuidance(targetDir);
1161
+ const scaffold = existsSync(path.join(targetDir, SCAFFOLD_LOCK_PATH))
1162
+ ? planManagedAppSync(targetDir, {}, versions) : null;
1163
+ const base = scaffold?.planned || [];
1164
+ const plan = buildExistingSubmittedAppSyncPlan(targetDir, versions, planSources(targetDir, base));
1165
+ plan.planned = [...base, ...plan.planned, ...guidance];
1166
+ return executeProjectPlan(targetDir, options, versions, runners, plan, scaffold);
1167
+ }
1168
+
1169
+ function adoptionSources(targetDir, options) {
1170
+ const input = options.input ? readJsonFile(path.resolve(targetDir, options.input), 'adoption input') : {};
1171
+ assertExactKeys(input, 'adoption input', [], ['manifest', 'build_profile']);
1172
+ const sources = new Map();
1173
+ for (const [key, relativePath] of [['manifest', 'nimi.app.yaml'], ['build_profile', BUILD_PROFILE_PATH]]) {
1174
+ if (!Object.hasOwn(input, key)) continue;
1175
+ requireObject(input[key], `adoption input ${key}`);
1176
+ if (existsSync(path.join(targetDir, relativePath))) {
1177
+ const existing = parseYamlFile(readProjectText(targetDir, relativePath), relativePath);
1178
+ if (stableInputJson(existing) !== stableInputJson(input[key])) throw new Error(`Adoption input conflicts with ${relativePath}`);
1179
+ } else sources.set(relativePath, stringifyYaml(input[key], { lineWidth: 0 }));
1180
+ }
1181
+ return sources;
1182
+ }
1183
+
1184
+ function stableInputJson(value) {
1185
+ if (Array.isArray(value)) return JSON.stringify(value.map((item) => JSON.parse(stableInputJson(item))));
1186
+ if (value && typeof value === 'object') return JSON.stringify(Object.fromEntries(Object.keys(value).sort().map((key) => [key, JSON.parse(stableInputJson(value[key]))])));
1187
+ return JSON.stringify(value);
1188
+ }
1189
+
1190
+ // @nimi-authority: rule.nimi.platform.app-ecosystem.p-scaf-008
1191
+ export function adoptAppProject(cwd, options = {}, versions, runners = {}) {
1192
+ const targetDir = resolveTargetDir(cwd, options);
1193
+ assertNoRetiredScaffoldState(targetDir);
1194
+ if (existsSync(path.join(targetDir, SCAFFOLD_INTENT_PATH)) || existsSync(path.join(targetDir, SCAFFOLD_LOCK_PATH))) {
1195
+ throw new Error('Existing-App adoption cannot replace fresh scaffold intent/lock. Use nimi-app init or sync for this scaffold.');
1196
+ }
1197
+ const guidance = planLifecycleGuidance(targetDir);
1198
+ const sources = adoptionSources(targetDir, options);
1199
+ let plan;
1200
+ try {
1201
+ plan = buildExistingSubmittedAppSyncPlan(targetDir, versions, sources);
1202
+ } catch (cause) {
1203
+ throw new Error(`${cause.message}. Prepare the real App-owned Host and build/test inputs using ${LIFECYCLE_SKILL_PATH}`, { cause });
1204
+ }
1205
+ if (plan.buildProfileRef !== ELECTRON_BUILD_PROFILE_REF) throw new Error('Existing-App init supports electron-packager-pnpm-vite; existing Tauri projects retain their sync path.');
1206
+ const files = readProjectLifecycleFiles(targetDir, plan.buildProfileRef);
1207
+ const profile = readBuildProfile(targetDir, sources);
1208
+ for (const command of [profile.testCommand, profile.buildCommand, ...Object.keys(profile.targets).map((target) => selectBuildOwner(profile, target).command)]) {
1209
+ const script = command.match(/^pnpm\s+run\s+([^\s]+)(?:\s|$)/u)?.[1];
1210
+ if (script && (!files.packageJson.scripts?.[script] || /\bnimi-app\s+(?:test|build)\b/u.test(files.packageJson.scripts[script]))) {
1211
+ throw new Error(`Adoption requires an actual non-recursive package script: ${script}`);
1212
+ }
1213
+ }
1214
+ const established = hasLifecycleGuidanceOwner(targetDir);
1215
+ const boundary = plannedFile(targetDir, '.nimi/contracts/scaffold-boundary.yaml', renderScaffoldBoundary());
1216
+ plan.planned.push(boundary, ...[...sources].map(([relativePath, content]) => plannedFile(targetDir, relativePath, content)), ...guidance);
1217
+ if (!established) {
1218
+ for (const file of plan.planned.filter((file) => [MANAGED_WORKFLOW_PATH, APP_IDENTITY_PATH, '.nimi/contracts/scaffold-boundary.yaml'].includes(path.relative(targetDir, file.path).split(path.sep).join('/')))) {
1219
+ if (file.previous !== null && !Buffer.from(file.previous).equals(Buffer.from(file.content))) throw new Error(`Unknown adoption file collision: ${path.relative(targetDir, file.path)}`);
1220
+ }
1221
+ }
1222
+ return executeProjectPlan(targetDir, { ...options, adopt: true }, versions, runners, plan, null);
1141
1223
  }
1142
1224
 
1143
1225
  export function checkAppProject(cwd, options = {}, versions, runners = {}) {
@@ -1147,10 +1229,11 @@ export function checkAppProject(cwd, options = {}, versions, runners = {}) {
1147
1229
  }
1148
1230
  assertNoRetiredScaffoldState(targetDir);
1149
1231
  const managed = existsSync(path.join(targetDir, SCAFFOLD_LOCK_PATH));
1232
+ const existingState = managed ? null : assertProjectLifecycleCurrent(targetDir, versions, { requireInstalledLock: true });
1150
1233
  const validation = validateAppProject(cwd, { dir: targetDir, silent: true }, versions, runners);
1151
1234
  let nimicoding = null;
1152
1235
  if (!managed) nimicoding = runNimicodingSync(targetDir, 'check', runners);
1153
- const { descriptor, buildProfile } = assertProjectLifecycleCurrent(targetDir, versions, { requireInstalledLock: true });
1236
+ const { descriptor, buildProfile } = existingState || assertProjectLifecycleCurrent(targetDir, versions, { requireInstalledLock: true });
1154
1237
  if (options.production === true) {
1155
1238
  for (const target of Object.keys(buildProfile.targets)) readAppInfo(targetDir, target);
1156
1239
  }
@@ -204,8 +204,11 @@ function renderDefaultElectronProductionPackager(identity) {
204
204
  " await writeFile(productionManifestPath, `${JSON.stringify(productionManifest, null, 2)}\\n`);",
205
205
  " await rm(path.join(productionSourceRoot, 'pnpm-lock.yaml'));",
206
206
  '',
207
- " const nativeDestination = path.join(productionSourceRoot, 'node_modules', ...NATIVE_BINDING_PACKAGE.split('/'));",
208
- ' await rm(nativeDestination, { recursive: true, force: true });',
207
+ " const installedNativePackage = path.join(productionSourceRoot, 'node_modules', ...NATIVE_BINDING_PACKAGE.split('/'));",
208
+ ' const nativeDestination = MACOS_BUILD',
209
+ " ? path.join(stagingRoot, 'nimi-native', 'protected-local')",
210
+ ' : installedNativePackage;',
211
+ ' await rm(installedNativePackage, { recursive: true, force: true });',
209
212
  ' await mkdir(path.dirname(nativeDestination), { recursive: true });',
210
213
  ' await cp(nativePackageRoot, nativeDestination, { recursive: true, dereference: true, force: false });',
211
214
  ' await mkdir(packagerTempRoot, { recursive: true });',
@@ -223,7 +226,8 @@ function renderDefaultElectronProductionPackager(identity) {
223
226
  ' out: outputRoot,',
224
227
  ' tmpdir: packagerTempRoot,',
225
228
  ' overwrite: false,',
226
- ' asar: false,',
229
+ " asar: { unpack: '**/*.node' },",
230
+ " ...(MACOS_BUILD ? { extraResource: [path.join(stagingRoot, 'nimi-native')] } : {}),",
227
231
  ' prune: false,',
228
232
  ' quiet: true,',
229
233
  ' derefSymlinks: true,',
@@ -234,7 +238,7 @@ function renderDefaultElectronProductionPackager(identity) {
234
238
  ' preEmbedProvisioningProfile: false, strictVerify: true,',
235
239
  " optionsForFile: () => ({ entitlements: [], hardenedRuntime: false, timestamp: 'none' }),",
236
240
  ' } } : {}),',
237
- ' afterInitialize: [async ({ buildPath }) => {',
241
+ ' beforeAsar: [async ({ buildPath }) => {',
238
242
  " const packagedManifestPath = path.join(buildPath, 'package.json');",
239
243
  " const packagedManifest = JSON.parse(await readFile(packagedManifestPath, 'utf8'));",
240
244
  ' packagedManifest.version = APP_VERSION;',
@@ -1,6 +1,7 @@
1
1
  import path from 'node:path';
2
2
  import { createHash } from 'node:crypto';
3
3
  import YAML from 'yaml';
4
+ import { lifecycleSkillFiles } from './app-lifecycle-guidance.mjs';
4
5
  import {
5
6
  WORKBENCH_CORE_SOURCE_ROOT,
6
7
  readAppSourceFile,
@@ -1096,7 +1097,7 @@ export function renderAppSubmissionInput(identity, options = {}) {
1096
1097
  }, { lineWidth: 0 });
1097
1098
  }
1098
1099
 
1099
- function buildScaffoldBoundary() {
1100
+ export function renderScaffoldBoundary() {
1100
1101
  return YAML.stringify({
1101
1102
  scaffold_contract: 'P-SCAF',
1102
1103
  profile: 'standalone',
@@ -1147,7 +1148,7 @@ function buildStructuredFiles(identity, profile, versions) {
1147
1148
  },
1148
1149
  {
1149
1150
  path: '.nimi/contracts/scaffold-boundary.yaml',
1150
- content: buildScaffoldBoundary(),
1151
+ content: renderScaffoldBoundary(),
1151
1152
  mutationClass: 'scaffold-managed glue',
1152
1153
  },
1153
1154
  {
@@ -1179,7 +1180,8 @@ function buildIdentityMapping(identity, targetDir = '') {
1179
1180
  devPort: identity.devPort,
1180
1181
  devRendererOrigin: `http://127.0.0.1:${identity.devPort}`,
1181
1182
  appOwnedNamespace: identity.appOwnedNamespace,
1182
- targetDir: targetDir || null,
1183
+ // Checkout location belongs to CLI diagnostics, not persisted identity.
1184
+ targetDir: null,
1183
1185
  };
1184
1186
  }
1185
1187
 
@@ -1426,9 +1428,11 @@ function buildAppScaffoldSnapshotWithResolver(
1426
1428
  buildScaffoldIntentFile(identity, versions, targetDir),
1427
1429
  ];
1428
1430
  validateScaffoldFileOwnership(createFiles);
1429
- const filesWithoutLock = [...createFiles];
1431
+ const guidanceFiles = lifecycleSkillFiles();
1432
+ const filesWithoutLock = [...createFiles, ...guidanceFiles];
1430
1433
  const lock = buildScaffoldLock(identity, versions, filesWithoutLock, targetDir);
1431
1434
  const initFiles = [
1435
+ ...guidanceFiles,
1432
1436
  {
1433
1437
  path: SCAFFOLD_LOCK_PATH,
1434
1438
  content: jsonFile(lock),
@@ -1469,7 +1473,7 @@ export function buildAppScaffoldCandidateSnapshot(input) {
1469
1473
  return buildAppScaffoldSnapshotWithResolver(input, resolveAppScaffoldCandidateFeatures);
1470
1474
  }
1471
1475
 
1472
- export function buildAppScaffoldSnapshotFromIntent({ intent, versions, targetDir = '', allowDerivedAppAccessDrift = false }) {
1476
+ export function buildAppScaffoldSnapshotFromIntent({ intent, versions, targetDir = '', allowDerivedAppAccessDrift = false, refreshDerived = false }) {
1473
1477
  if (intent?.intentVersion !== SCAFFOLD_INTENT_VERSION) {
1474
1478
  throw new Error(`Unsupported scaffold intent version: ${String(intent?.intentVersion || 'missing')}`);
1475
1479
  }
@@ -1493,7 +1497,14 @@ export function buildAppScaffoldSnapshotFromIntent({ intent, versions, targetDir
1493
1497
  targetDir: canonicalTargetDir,
1494
1498
  }, resolveAppScaffoldIntentFeatures);
1495
1499
  const expectedIntent = JSON.parse(snapshot.filesByPath.get(SCAFFOLD_INTENT_PATH).content);
1496
- const comparableIntent = allowDerivedAppAccessDrift
1500
+ // @nimi-authority: rule.nimi.platform.app-ecosystem.p-scaf-018c
1501
+ const immutableInputs = new Set(['intentVersion', 'scaffoldVersion', 'initRequired', 'initCommand', 'initOrder', 'profile', 'appId', 'appTitle', 'version', 'packageName', 'packageAuthor', 'cargoPackageName', 'tauriIdentifier', 'accentPack', 'directFeatures', 'devPort', 'semantics']);
1502
+ if (canonicalJson(Object.keys(intent).sort()) !== canonicalJson(Object.keys(expectedIntent).sort())) {
1503
+ throw new Error('Scaffold intent fields do not match the current canonical resolved intent');
1504
+ }
1505
+ const comparableIntent = refreshDerived
1506
+ ? Object.fromEntries(Object.entries(expectedIntent).map(([key, value]) => [key, immutableInputs.has(key) ? intent[key] : value]))
1507
+ : allowDerivedAppAccessDrift
1497
1508
  ? { ...intent, appAccessItems: expectedIntent.appAccessItems }
1498
1509
  : intent;
1499
1510
  if (canonicalJson(comparableIntent) !== canonicalJson(expectedIntent)) {