@adelin-io/cli 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. package/README.md +76 -2
  2. package/authoring-release.json +174 -0
  3. package/package.json +30 -4
  4. package/runtime-integrity.json +9 -0
  5. package/scripts/adelin.mjs +7768 -0
  6. package/scripts/assemble-checkout.mjs +93 -0
  7. package/scripts/local-save.mjs +513 -0
  8. package/scripts/materialize.mjs +319 -0
  9. package/scripts/runtime.mjs +8950 -0
  10. package/scripts/typecheck.mjs +72 -0
  11. package/scripts/workspace-state.mjs +183 -0
  12. package/skill/README.md +77 -0
  13. package/skill/SKILL.md +100 -0
  14. package/skill/authoring/access.md +193 -0
  15. package/skill/authoring/analytics.md +20 -0
  16. package/skill/authoring/app-memory.md +128 -0
  17. package/skill/authoring/app-requirements.md +99 -0
  18. package/skill/authoring/app-structure.md +265 -0
  19. package/skill/authoring/assets.md +117 -0
  20. package/skill/authoring/auth.md +263 -0
  21. package/skill/authoring/content-binding.md +26 -0
  22. package/skill/authoring/i18n.md +184 -0
  23. package/skill/authoring/language.md +503 -0
  24. package/skill/authoring/local-workflow.md +1667 -0
  25. package/skill/authoring/offline/connectivity.md +50 -0
  26. package/skill/authoring/offline/example.md +102 -0
  27. package/skill/authoring/offline/history-sync.md +39 -0
  28. package/skill/authoring/offline/index.md +29 -0
  29. package/skill/authoring/offline/package-storage.md +37 -0
  30. package/skill/authoring/offline/platforms.md +35 -0
  31. package/skill/authoring/offline/startup-navigation.md +53 -0
  32. package/skill/authoring/platform-files.md +616 -0
  33. package/skill/authoring/player/casting.md +47 -0
  34. package/skill/authoring/player/controls.md +95 -0
  35. package/skill/authoring/player/downloads.md +90 -0
  36. package/skill/authoring/player/drm.md +31 -0
  37. package/skill/authoring/player/index.md +39 -0
  38. package/skill/authoring/player/live-dvr.md +74 -0
  39. package/skill/authoring/player/platforms.md +47 -0
  40. package/skill/authoring/player/playback.md +43 -0
  41. package/skill/authoring/player/tracks-subtitles.md +32 -0
  42. package/skill/authoring/profiles.md +213 -0
  43. package/skill/authoring/remote-keys.md +139 -0
  44. package/skill/authoring/search.md +27 -0
  45. package/skill/authoring/store.md +85 -0
  46. package/skill/authoring/tv-text-entry.md +146 -0
  47. package/skill/design/approved/README.md +14 -0
  48. package/skill/design/approved/vesper-phone-home.jpg +0 -0
  49. package/skill/design/approved/vesper-tv-detail.jpg +0 -0
  50. package/skill/design/approved/vesper-tv-home.jpg +0 -0
  51. package/skill/design/design-guide.md +610 -0
  52. package/skill/design/edge-to-edge.md +66 -0
  53. package/skill/design/icons.md +50 -0
  54. package/skill/design/responsive-layout.md +175 -0
  55. package/skill/design/safe-area.md +221 -0
  56. package/skill/design/streaming-playbook.md +131 -0
  57. package/skill/design/visual-review.md +150 -0
  58. package/skill/examples/README.md +24 -0
  59. package/skill/examples/cinema/DESIGN.md +58 -0
  60. package/skill/examples/cinema/app.tsx +17 -0
  61. package/skill/examples/cinema/assets/logo.png +0 -0
  62. package/skill/examples/cinema/components/Action.tsx +40 -0
  63. package/skill/examples/cinema/components/Action.tv.tsx +44 -0
  64. package/skill/examples/cinema/components/CatalogGrid.tsx +31 -0
  65. package/skill/examples/cinema/components/ContinueRail.tsx +98 -0
  66. package/skill/examples/cinema/components/Feedback.tsx +28 -0
  67. package/skill/examples/cinema/components/Field.tsx +41 -0
  68. package/skill/examples/cinema/components/LibraryRail.tsx +46 -0
  69. package/skill/examples/cinema/components/PlayAction.tsx +29 -0
  70. package/skill/examples/cinema/components/Root.tsx +59 -0
  71. package/skill/examples/cinema/components/Shell.tsx +70 -0
  72. package/skill/examples/cinema/components/Tab.tsx +22 -0
  73. package/skill/examples/cinema/components/TitleCard.tsx +68 -0
  74. package/skill/examples/cinema/components/TitleMeta.tsx +36 -0
  75. package/skill/examples/cinema/locales/en.ts +211 -0
  76. package/skill/examples/cinema/locales/lt.ts +211 -0
  77. package/skill/examples/cinema/preview/phone-home.jpg +0 -0
  78. package/skill/examples/cinema/preview/tv-detail.jpg +0 -0
  79. package/skill/examples/cinema/preview/tv-home.jpg +0 -0
  80. package/skill/examples/cinema/screens/portrait/Account.tsx +110 -0
  81. package/skill/examples/cinema/screens/portrait/Browse.tsx +73 -0
  82. package/skill/examples/cinema/screens/portrait/Detail.tsx +159 -0
  83. package/skill/examples/cinema/screens/portrait/Home.tsx +196 -0
  84. package/skill/examples/cinema/screens/portrait/Player.tsx +299 -0
  85. package/skill/examples/cinema/screens/portrait/Search.tsx +46 -0
  86. package/skill/examples/cinema/screens/portrait/Search.tv.tsx +55 -0
  87. package/skill/examples/cinema/screens/portrait/SignIn.tsx +101 -0
  88. package/skill/examples/cinema/screens/portrait/SignUp.tsx +106 -0
  89. package/skill/examples/cinema/store.tsx +132 -0
  90. package/skill/examples/cinema/theme.ts +32 -0
  91. package/skill/examples/documentary/DESIGN.md +33 -0
  92. package/skill/examples/documentary/app.tsx +17 -0
  93. package/skill/examples/documentary/components/Action.tsx +43 -0
  94. package/skill/examples/documentary/components/CatalogGrid.tsx +47 -0
  95. package/skill/examples/documentary/components/Feedback.tsx +27 -0
  96. package/skill/examples/documentary/components/Field.tsx +33 -0
  97. package/skill/examples/documentary/components/LibraryRail.tsx +47 -0
  98. package/skill/examples/documentary/components/Root.tsx +62 -0
  99. package/skill/examples/documentary/components/Shell.tsx +93 -0
  100. package/skill/examples/documentary/components/StoryCard.tsx +53 -0
  101. package/skill/examples/documentary/components/StoryMeta.tsx +22 -0
  102. package/skill/examples/documentary/preview/phone-home.jpg +0 -0
  103. package/skill/examples/documentary/preview/tv-detail.jpg +0 -0
  104. package/skill/examples/documentary/preview/tv-home.jpg +0 -0
  105. package/skill/examples/documentary/screens/portrait/Account.tsx +97 -0
  106. package/skill/examples/documentary/screens/portrait/Browse.tsx +71 -0
  107. package/skill/examples/documentary/screens/portrait/Detail.tsx +133 -0
  108. package/skill/examples/documentary/screens/portrait/Home.tsx +89 -0
  109. package/skill/examples/documentary/screens/portrait/Player.tsx +116 -0
  110. package/skill/examples/documentary/screens/portrait/Search.tsx +48 -0
  111. package/skill/examples/documentary/screens/portrait/SignIn.tsx +96 -0
  112. package/skill/examples/documentary/screens/portrait/SignUp.tsx +101 -0
  113. package/skill/examples/documentary/store.tsx +115 -0
  114. package/skill/examples/documentary/theme.ts +20 -0
  115. package/skill/examples/series/DESIGN.md +55 -0
  116. package/skill/examples/series/app.tsx +17 -0
  117. package/skill/examples/series/components/Action.tsx +42 -0
  118. package/skill/examples/series/components/CatalogGrid.tsx +43 -0
  119. package/skill/examples/series/components/ContinueRail.tsx +78 -0
  120. package/skill/examples/series/components/Feedback.tsx +26 -0
  121. package/skill/examples/series/components/Field.tsx +34 -0
  122. package/skill/examples/series/components/LibraryRail.tsx +38 -0
  123. package/skill/examples/series/components/OutcomeNote.tsx +28 -0
  124. package/skill/examples/series/components/PlayAction.tsx +29 -0
  125. package/skill/examples/series/components/RestoreAction.tsx +33 -0
  126. package/skill/examples/series/components/Root.tsx +75 -0
  127. package/skill/examples/series/components/SaveTitle.tsx +34 -0
  128. package/skill/examples/series/components/Shell.tsx +75 -0
  129. package/skill/examples/series/components/TitleCard.tsx +62 -0
  130. package/skill/examples/series/components/UnlockAction.tsx +10 -0
  131. package/skill/examples/series/preview/phone-home.jpg +0 -0
  132. package/skill/examples/series/preview/tv-detail.jpg +0 -0
  133. package/skill/examples/series/preview/tv-home.jpg +0 -0
  134. package/skill/examples/series/screens/portrait/Account.tsx +125 -0
  135. package/skill/examples/series/screens/portrait/Browse.tsx +61 -0
  136. package/skill/examples/series/screens/portrait/Detail.tsx +231 -0
  137. package/skill/examples/series/screens/portrait/Home.tsx +109 -0
  138. package/skill/examples/series/screens/portrait/MyList.tsx +44 -0
  139. package/skill/examples/series/screens/portrait/Plans.tsx +131 -0
  140. package/skill/examples/series/screens/portrait/Player.tsx +138 -0
  141. package/skill/examples/series/screens/portrait/Profiles.tsx +103 -0
  142. package/skill/examples/series/screens/portrait/Search.tsx +50 -0
  143. package/skill/examples/series/screens/portrait/SignIn.tsx +94 -0
  144. package/skill/examples/series/screens/portrait/SignUp.tsx +100 -0
  145. package/skill/examples/series/store.tsx +192 -0
  146. package/skill/examples/series/theme.ts +32 -0
  147. package/skill/guides/final-pricing-capabilities.md +13 -0
  148. package/skill/reference/api.md +842 -0
  149. package/skill/reference/components.md +1782 -0
  150. package/skill/reference/packages.md +24 -0
  151. package/skill/scripts/assemble-checkout.mjs +93 -0
  152. package/skill/scripts/local-save.mjs +513 -0
  153. package/skill/scripts/materialize.mjs +319 -0
  154. package/skill/scripts/workspace-state.mjs +183 -0
  155. package/types/adelin-access.d.ts +70 -0
  156. package/types/adelin-analytics.d.ts +5 -0
  157. package/types/adelin-assets.d.ts +26 -0
  158. package/types/adelin-auth.d.ts +37 -0
  159. package/types/adelin-content.d.ts +120 -0
  160. package/types/adelin-device.d.ts +195 -0
  161. package/types/adelin-downloads.d.ts +47 -0
  162. package/types/adelin-env.d.ts +8 -0
  163. package/types/adelin-globals.d.ts +19 -0
  164. package/types/adelin-i18n.d.ts +31 -0
  165. package/types/adelin-native-stack.d.ts +178 -0
  166. package/types/adelin-navigation.d.ts +264 -0
  167. package/types/adelin-profiles.d.ts +51 -0
  168. package/types/adelin-react.d.ts +49 -0
  169. package/types/adelin-reanimated.d.ts +376 -0
  170. package/types/adelin-storage.d.ts +9 -0
  171. package/types/adelin-store.d.ts +74 -0
  172. package/types/adelin-ui.d.ts +1518 -0
  173. package/types/adelin-utils.d.ts +7 -0
  174. package/types/adelin-worklets.d.ts +15 -0
  175. package/workspace-tsconfig.json +53 -0
@@ -0,0 +1,24 @@
1
+ # @adelin packages
2
+
3
+ The complete set of names an app can import. A name that is not listed here does not exist,
4
+ so there is no need to look for it elsewhere. Component props are the `*Props` interfaces in
5
+ the workspace's `@adelin/*` type declarations; [components.md](components.md) describes each
6
+ component.
7
+
8
+ - `@adelin/react`: React (default export: `import React from "@adelin/react"`), useState, useEffect, useMemo, useCallback, useRef, useReducer, useContext
9
+ - `@adelin/ui`: View, Text, Pressable, Button, TouchableOpacity, Image, ScrollView, ViewportOffsetScope, FlashList, SectionList, Carousel, Chips, TextInput, ActivityIndicator, LinearGradient, SafeAreaView, BlurView, CheckBox, KeyboardAvoidingView, Modal, SlidingText, Svg, Switch, Slider, Skeleton, WebView, RefreshControl, VideoPlayer, VideoView, VideoThumbnail, ScrubThumbnail, ScrubFilmstrip, SlickTile, ProgressTile, VideoTile, SpotlightTile, PosterTile, ThumbTile, RankTile, MorphTile, StackTile, BillboardHero, CinematicHero, GalleryHero, TrailerHero, TVKeyboard, Icon, FocusGroup, Screen, StyleSheet, theme, useFocus, focus, useWindowDimensions, useSafeAreaInsets, ScrollTarget, Portal, createTheme, useVideoPlayer
10
+ - `@adelin/reanimated`: Animated (default export: `import Animated from "@adelin/reanimated"`), createAnimatedComponent, useSharedValue, useAnimatedStyle, withTiming, withSpring, withDelay, withSequence, withRepeat, cancelAnimation, interpolate, interpolateColor, Extrapolation, Extrapolate, Easing, useDerivedValue, useAnimatedReaction, makeMutable, isSharedValue, runOnJS, runOnUI, clamp, withClamp, GentleSpringConfig, GentleSpringConfigWithDuration, Reanimated3DefaultSpringConfig, Reanimated3DefaultSpringConfigWithDuration, SnappySpringConfig, SnappySpringConfigWithDuration, WigglySpringConfig, WigglySpringConfigWithDuration, BounceIn, BounceInDown, BounceInLeft, BounceInRight, BounceInUp, BounceOut, BounceOutDown, BounceOutLeft, BounceOutRight, BounceOutUp, FadeIn, FadeInDown, FadeInLeft, FadeInRight, FadeInUp, FadeOut, FadeOutDown, FadeOutLeft, FadeOutRight, FadeOutUp, FlipInEasyX, FlipInEasyY, FlipInXDown, FlipInXUp, FlipInYLeft, FlipInYRight, FlipOutEasyX, FlipOutEasyY, FlipOutXDown, FlipOutXUp, FlipOutYLeft, FlipOutYRight, LightSpeedInLeft, LightSpeedInRight, LightSpeedOutLeft, LightSpeedOutRight, PinwheelIn, PinwheelOut, RollInLeft, RollInRight, RollOutLeft, RollOutRight, RotateInDownLeft, RotateInDownRight, RotateInUpLeft, RotateInUpRight, RotateOutDownLeft, RotateOutDownRight, RotateOutUpLeft, RotateOutUpRight, SlideInDown, SlideInLeft, SlideInRight, SlideInUp, SlideOutDown, SlideOutLeft, SlideOutRight, SlideOutUp, StretchInX, StretchInY, StretchOutX, StretchOutY, ZoomIn, ZoomInDown, ZoomInEasyDown, ZoomInEasyUp, ZoomInLeft, ZoomInRight, ZoomInRotate, ZoomInUp, ZoomOut, ZoomOutDown, ZoomOutEasyDown, ZoomOutEasyUp, ZoomOutLeft, ZoomOutRight, ZoomOutRotate, ZoomOutUp, Keyframe, LinearTransition, FadingTransition, SequencedTransition, JumpingTransition, CurvedTransition, EntryExitTransition, LayoutAnimationConfig, Layout, ReduceMotion, useReducedMotion, ReducedMotionConfig, css, cubicBezier, linear, steps, useAnimatedScrollHandler, useComposedEventHandler, useEvent, useScrollOffset, useScrollViewOffset, useAnimatedRef, measure, scrollTo, useAnimatedProps, useFrameCallback, enableLayoutAnimations, isReanimated3, isConfigured, contrastColor, convertToRGBA, isColor, createAnimatedPropAdapter
11
+ - `@adelin/navigation`: defineApp, appNavigation, NavigationContainer, useNavigation, useRoute, useFocusEffect, useIsFocused, useNavigationState, usePreventRemove, CommonActions, StackActions, createNavigationContainerRef, useNavigationContainerRef, DefaultTheme, DarkTheme, useTheme, ThemeProvider, ThemeContext, NavigationContext, NavigationRouteContext, findFocusedRoute, getFocusedRouteNameFromRoute, createStaticNavigation, createComponentForStaticNavigation, Link, useScrollToTop, useLocale, LocaleDirContext, BaseNavigationContainer, ServerContainer, NavigationIndependentTree, useNavigationIndependentTree
12
+ - `@adelin/store`: useSelector, useDispatch, createSlice, createAsyncThunk, appDispatch
13
+ - `@adelin/auth`: useAuth, signIn, signUp, signOut, requestPasswordRecovery, completePasswordRecovery, addPasswordLoginMethod, addProviderLoginMethod, deleteAccount, setMarketingConsent, signInWithProvider
14
+ - `@adelin/access`: useAccess, subscribe, startTrial, buy, rent, restorePurchases, manageSubscription
15
+ - `@adelin/content`: content, useSearch, useLiveViewers
16
+ - `@adelin/utils`: formatDate, uniqueBy
17
+ - `@adelin/storage`: storage
18
+ - `@adelin/device`: useConnectivity, useAppMode, appMode, useTVEventHandler, useBackHandler, Keys, exitApp, BackHandler, TVEventControl, DeviceInfo, Platform, capabilities
19
+ - `@adelin/downloads`: downloads, useDownloads
20
+ - `@adelin/profiles`: profiles, favorites, progress
21
+ - `@adelin/worklets`: scheduleOnRN, scheduleOnUI, runOnJS, runOnUI, getCurrentThreadId
22
+ - `@adelin/native-stack`: createNativeStackNavigator, createNativeStackScreen
23
+ - `@adelin/i18n`: useTranslation, languageName
24
+ - `@adelin/analytics`: openPrivacyChoices
@@ -0,0 +1,93 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { readFileSync, lstatSync, readdirSync, writeFileSync, linkSync, unlinkSync } from 'node:fs';
3
+ import { dirname, join, parse, resolve, sep } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+
6
+ const MAX_BUNDLE_BYTES = 1024 * 1024;
7
+ const CHUNK_BYTES = 12 * 1024;
8
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
9
+
10
+ function refuse() { throw new Error('Checkout chunks are incomplete or invalid. Start a new checkout.'); }
11
+
12
+ function lstatIfPresent(path) {
13
+ try { return lstatSync(path); }
14
+ catch (error) { if (error.code === 'ENOENT') return null; throw error; }
15
+ }
16
+
17
+ function assertSafePath(path) {
18
+ const absolute = resolve(path);
19
+ const root = parse(absolute).root;
20
+ let cursor = root;
21
+ for (const segment of absolute.slice(root.length).split(sep).filter(Boolean)) {
22
+ cursor = join(cursor, segment);
23
+ if (lstatIfPresent(cursor)?.isSymbolicLink()) refuse();
24
+ }
25
+ }
26
+
27
+ function readJsonFile(path, limit) {
28
+ assertSafePath(path);
29
+ const stat = lstatIfPresent(path);
30
+ if (!stat?.isFile() || stat.size > limit) refuse();
31
+ try { return JSON.parse(readFileSync(path, 'utf8')); }
32
+ catch { refuse(); }
33
+ }
34
+
35
+ /** Assemble exact indexed bytes and publish one bundle without replacing local data. */
36
+ export function assembleCheckout(metadata, chunkFiles, outputPath, expectedAppId) {
37
+ if (!UUID.test(expectedAppId) || !metadata || typeof metadata !== 'object' ||
38
+ !UUID.test(metadata.bundleId) || metadata.appId !== expectedAppId ||
39
+ !Number.isSafeInteger(metadata.byteCount) || metadata.byteCount < 1 ||
40
+ metadata.byteCount > MAX_BUNDLE_BYTES ||
41
+ !Number.isSafeInteger(metadata.chunkCount) ||
42
+ metadata.chunkCount !== Math.ceil(metadata.byteCount / CHUNK_BYTES) ||
43
+ !/^[a-f0-9]{64}$/.test(metadata.sha256) ||
44
+ !Array.isArray(chunkFiles) || chunkFiles.length !== metadata.chunkCount) refuse();
45
+ const parts = [];
46
+ for (let index = 0; index < chunkFiles.length; index++) {
47
+ const chunk = readJsonFile(chunkFiles[index], 24 * 1024);
48
+ if (!chunk || chunk.bundleId !== metadata.bundleId || chunk.appId !== expectedAppId ||
49
+ chunk.index !== index || chunk.chunkCount !== metadata.chunkCount ||
50
+ typeof chunk.data !== 'string' || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(chunk.data)) refuse();
51
+ const bytes = Buffer.from(chunk.data, 'base64');
52
+ const expectedLength = Math.min(CHUNK_BYTES, metadata.byteCount - index * CHUNK_BYTES);
53
+ if (bytes.length !== expectedLength || chunk.byteCount !== bytes.length ||
54
+ bytes.toString('base64') !== chunk.data) refuse();
55
+ parts.push(bytes);
56
+ }
57
+ const bytes = Buffer.concat(parts);
58
+ if (bytes.length !== metadata.byteCount || createHash('sha256').update(bytes).digest('hex') !== metadata.sha256) refuse();
59
+ let bundle;
60
+ try { bundle = JSON.parse(bytes.toString('utf8')); }
61
+ catch { refuse(); }
62
+ if (bundle?.appId !== expectedAppId || bundle?.schema !== 1 ||
63
+ Buffer.from(JSON.stringify(bundle)).compare(bytes) !== 0) refuse();
64
+ const target = resolve(outputPath);
65
+ assertSafePath(target);
66
+ if (!lstatIfPresent(dirname(target))?.isDirectory() || lstatIfPresent(target)) refuse();
67
+ const stage = join(dirname(target), `.${randomUUID()}.tmp`);
68
+ try {
69
+ writeFileSync(stage, bytes, { flag: 'wx', mode: 0o600 });
70
+ linkSync(stage, target);
71
+ } finally {
72
+ if (lstatIfPresent(stage)) unlinkSync(stage);
73
+ }
74
+ return { appId: expectedAppId, byteCount: bytes.length, sha256: metadata.sha256 };
75
+ }
76
+
77
+ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
78
+ try {
79
+ if (process.argv.length !== 6) refuse();
80
+ const [metadataPath, chunkDirectory, outputPath, expectedAppId] = process.argv.slice(2);
81
+ const metadata = readJsonFile(metadataPath, 4096);
82
+ assertSafePath(chunkDirectory);
83
+ if (!lstatIfPresent(chunkDirectory)?.isDirectory()) refuse();
84
+ const names = readdirSync(chunkDirectory);
85
+ if (names.length !== metadata.chunkCount ||
86
+ names.some((name, index) => !names.includes(`${index}.json`))) refuse();
87
+ const files = Array.from({ length: metadata.chunkCount }, (_, index) => join(chunkDirectory, `${index}.json`));
88
+ process.stdout.write(JSON.stringify(assembleCheckout(metadata, files, outputPath, expectedAppId)) + '\n');
89
+ } catch (error) {
90
+ process.stderr.write(`${error.message}\n`);
91
+ process.exitCode = 1;
92
+ }
93
+ }
@@ -0,0 +1,513 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { closeSync, constants, fsyncSync, linkSync, openSync, readdirSync,
3
+ renameSync, unlinkSync, writeFileSync } from 'node:fs';
4
+ import { dirname, join, resolve } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { MANIFEST, PENDING, SAVE_PENDING, SAVE_REQUEST, SAVE_OUTCOME, UUID, SOURCE_PATH,
7
+ assertNoSymlinkAncestors, assertSafeTarget, lstatIfPresent, parseManifest, readSafeFile,
8
+ refuse, sha256, withWorkspaceMutation } from './workspace-state.mjs';
9
+
10
+ const MAX_SOURCE_BYTES = 1024 * 1024;
11
+ const MAX_REQUEST_BYTES = 1200 * 1024;
12
+ const MAX_FILE_CHARACTERS = 300000;
13
+ const MAX_SAVE_FILES = 50;
14
+ const MAX_JSON_BYTES = 8 * 1024 * 1024;
15
+ const SHA256 = /^[a-f0-9]{64}$/;
16
+ const decoder = new TextDecoder('utf-8', { fatal: true });
17
+
18
+ function assertSupportSettled(root) {
19
+ const path = join(root, '.adelin-support.pending.json');
20
+ assertNoSymlinkAncestors(path);
21
+ if (lstatIfPresent(path)) refuse('Settle the pending workspace support refresh with adelin setup first.');
22
+ }
23
+
24
+ function text(bytes, label) {
25
+ try { return decoder.decode(bytes); }
26
+ catch { refuse(`Invalid UTF-8 in ${label}.`); }
27
+ }
28
+
29
+ function exactKeys(value, required) {
30
+ return value && typeof value === 'object' && !Array.isArray(value) &&
31
+ Object.keys(value).length === required.length && required.every(key => Object.hasOwn(value, key));
32
+ }
33
+
34
+ function safeRead(root, name, maxBytes = MAX_JSON_BYTES) {
35
+ return readSafeFile(assertSafeTarget(root, name), maxBytes);
36
+ }
37
+
38
+ function readJson(root, name) {
39
+ try { return JSON.parse(text(safeRead(root, name), name)); }
40
+ catch { refuse(`Invalid ${name}.`); }
41
+ }
42
+
43
+ function writeExclusive(root, name, value, writeFile = writeFileSync) {
44
+ const path = assertSafeTarget(root, name);
45
+ if (lstatIfPresent(path)) refuse(`${name} already exists.`);
46
+ const stage = join(root, `.${randomUUID()}.tmp`);
47
+ try {
48
+ writeFile(stage, value, { flag: 'wx', mode: 0o600 });
49
+ if (sha256(readSafeFile(stage, MAX_JSON_BYTES)) !== sha256(Buffer.from(value)))
50
+ refuse('Staged save file changed.');
51
+ const fd = openSync(stage, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
52
+ try { fsyncSync(fd); }
53
+ finally { closeSync(fd); }
54
+ assertSafeTarget(root, name);
55
+ linkSync(stage, path);
56
+ } finally {
57
+ assertNoSymlinkAncestors(stage);
58
+ if (lstatIfPresent(stage)) unlinkSync(stage);
59
+ }
60
+ }
61
+
62
+ function authoredPaths(root) {
63
+ const paths = [];
64
+ for (const path of ['app.tsx', 'store.tsx', 'theme.ts']) {
65
+ assertSafeTarget(root, path);
66
+ if (lstatIfPresent(join(root, path))) paths.push(path);
67
+ }
68
+ for (const folder of ['screens', 'screens/landscape', 'components', 'locales']) {
69
+ const absolute = join(root, folder);
70
+ assertNoSymlinkAncestors(absolute);
71
+ const stat = lstatIfPresent(absolute);
72
+ if (!stat) continue;
73
+ if (!stat.isDirectory()) refuse('Invalid workspace source directory.');
74
+ for (const name of readdirSync(absolute)) {
75
+ if (folder === 'screens' && name === 'portrait') refuse('Use canonical shared screen paths.');
76
+ if (!name.endsWith(folder === 'locales' ? '.ts' : '.tsx')) continue;
77
+ const path = `${folder}/${name}`;
78
+ if (!SOURCE_PATH.test(path)) refuse('Unsafe source path.');
79
+ assertSafeTarget(root, path);
80
+ paths.push(path);
81
+ }
82
+ }
83
+ return paths.sort();
84
+ }
85
+
86
+ function requestFiles(root, manifest) {
87
+ const files = [];
88
+ let bytesTotal = 0;
89
+ for (const path of authoredPaths(root)) {
90
+ const bytes = safeRead(root, path, MAX_SOURCE_BYTES);
91
+ const hash = sha256(bytes);
92
+ const stamp = manifest.files[path];
93
+ if (stamp && stamp.sha256 === hash) continue;
94
+ const content = text(bytes, path);
95
+ if (content.length > MAX_FILE_CHARACTERS) refuse('Source file exceeds the character limit.');
96
+ bytesTotal += bytes.length;
97
+ if (bytesTotal > MAX_SOURCE_BYTES) refuse('Save source exceeds the 1 MiB limit.');
98
+ files.push({ path, content, baseVersion: stamp?.version ?? 0 });
99
+ if (files.length > MAX_SAVE_FILES) refuse('Save exceeds the 50-file limit.');
100
+ }
101
+ return files;
102
+ }
103
+
104
+ function validateSession(session) {
105
+ if (!exactKeys(session, ['leaseId', 'chatSessionId', 'epoch']) ||
106
+ !UUID.test(session.leaseId) || !UUID.test(session.chatSessionId) ||
107
+ !Number.isSafeInteger(session.epoch) || session.epoch < 1)
108
+ refuse('Invalid edit session tuple.');
109
+ }
110
+
111
+ function journalFor(appId, request) {
112
+ const submitted = request.files.map(({ path, content, baseVersion }) =>
113
+ ({ path, baseVersion, sha256: sha256(Buffer.from(content, 'utf8')) }));
114
+ return { schema: 1, appId, operationId: request.operation_id,
115
+ digest: sha256(Buffer.from(JSON.stringify(request))), request, submitted, terminal: null };
116
+ }
117
+
118
+ function validateJournal(value, appId) {
119
+ if (!exactKeys(value, ['schema', 'appId', 'operationId', 'digest', 'request', 'submitted', 'terminal',
120
+ ...(value?.previous === undefined ? [] : ['previous'])]) ||
121
+ value.schema !== 1 || value.appId !== appId || !UUID.test(value.operationId) ||
122
+ !SHA256.test(value.digest) || !value.request || typeof value.request !== 'object' ||
123
+ Array.isArray(value.request) ||
124
+ !exactKeys(value.request, ['app_id', 'lease_id', 'chat_session_id', 'epoch', 'operation_id', 'files']) ||
125
+ value.request.app_id !== appId ||
126
+ value.request.operation_id !== value.operationId ||
127
+ !UUID.test(value.request.lease_id) || !UUID.test(value.request.chat_session_id) ||
128
+ !Number.isSafeInteger(value.request.epoch) || value.request.epoch < 1 ||
129
+ !Array.isArray(value.request.files) || value.request.files.length < 1 ||
130
+ value.request.files.length > MAX_SAVE_FILES ||
131
+ Buffer.byteLength(JSON.stringify(value.request), 'utf8') > MAX_REQUEST_BYTES ||
132
+ sha256(Buffer.from(JSON.stringify(value.request))) !== value.digest ||
133
+ !Array.isArray(value.submitted) || value.submitted.length !== value.request.files.length)
134
+ refuse('Invalid pending save journal.');
135
+ const seen = new Set();
136
+ let totalBytes = 0;
137
+ for (let index = 0; index < value.request.files.length; index++) {
138
+ const file = value.request.files[index];
139
+ const stamp = value.submitted[index];
140
+ if (!exactKeys(file, ['path', 'content', 'baseVersion']) ||
141
+ !SOURCE_PATH.test(file.path) || seen.has(file.path) ||
142
+ typeof file.content !== 'string' || file.content.length > MAX_FILE_CHARACTERS ||
143
+ !Number.isSafeInteger(file.baseVersion) || file.baseVersion < 0 ||
144
+ !exactKeys(stamp, ['path', 'baseVersion', 'sha256']) || stamp.path !== file.path ||
145
+ stamp.baseVersion !== file.baseVersion || !SHA256.test(stamp.sha256) ||
146
+ sha256(Buffer.from(file.content, 'utf8')) !== stamp.sha256)
147
+ refuse('Invalid pending save journal.');
148
+ totalBytes += Buffer.byteLength(file.content, 'utf8');
149
+ if (totalBytes > MAX_SOURCE_BYTES) refuse('Invalid pending save journal.');
150
+ seen.add(file.path);
151
+ }
152
+ if (value.previous !== undefined) {
153
+ const previous = validateJournal(value.previous, appId);
154
+ if (previous.previous || previous.terminal || previous.operationId === value.operationId ||
155
+ JSON.stringify(previous.request.files) !== JSON.stringify(value.request.files))
156
+ refuse('Invalid retry predecessor.');
157
+ }
158
+ return value;
159
+ }
160
+
161
+ function readJournal(root, appId) {
162
+ return validateJournal(readJson(root, SAVE_PENDING), appId);
163
+ }
164
+
165
+ export function readPendingSave(destination, appId) {
166
+ const root = resolve(destination);
167
+ parseManifest(safeRead(root, MANIFEST), appId);
168
+ return lstatIfPresent(assertSafeTarget(root, SAVE_PENDING)) ? readJournal(root, appId) : null;
169
+ }
170
+
171
+ function readResult(value) {
172
+ if (typeof value !== 'string') return value;
173
+ let parsed;
174
+ try { parsed = JSON.parse(text(readSafeFile(resolve(value), MAX_JSON_BYTES), 'save result')); }
175
+ catch { refuse('Invalid save result file.'); }
176
+ return parsed;
177
+ }
178
+
179
+ function isPreviewUrl(value) {
180
+ if (typeof value !== 'string' || value.length > 200 || !/^https?:\/\/\S+$/.test(value)) return false;
181
+ try { return ['http:', 'https:'].includes(new URL(value).protocol); }
182
+ catch { return false; }
183
+ }
184
+
185
+ function validatedTerminal(value, journal) {
186
+ if (!value || typeof value !== 'object' || Array.isArray(value) ||
187
+ !['committed', 'mixed'].includes(value.state) ||
188
+ value.operationId !== journal.operationId ||
189
+ (value.appId !== undefined && value.appId !== journal.appId) ||
190
+ Object.keys(value).some(key => !['state', 'operationId', 'appId', 'files', 'draftRevision', 'replay', 'previewUrl'].includes(key)) ||
191
+ value.previewUrl !== undefined && !isPreviewUrl(value.previewUrl) ||
192
+ !Array.isArray(value.files) || value.files.length !== journal.submitted.length)
193
+ refuse('Save result does not match the pending operation.');
194
+ const expected = new Map(journal.submitted.map(file => [file.path, file]));
195
+ let bytes = 0;
196
+ for (const file of value.files) {
197
+ if (!file || typeof file !== 'object' || Array.isArray(file) ||
198
+ !SOURCE_PATH.test(file.path) || !expected.delete(file.path) ||
199
+ !['persisted', 'rejected', 'stale'].includes(file.status) ||
200
+ Object.keys(file).some(key => !['path', 'status', 'activated', 'version',
201
+ 'canonicalContent', 'diagnostics', 'headVersion'].includes(key)) ||
202
+ file.diagnostics !== undefined &&
203
+ (typeof file.diagnostics !== 'string' || file.diagnostics.length > 2000) ||
204
+ file.headVersion !== undefined &&
205
+ (!Number.isSafeInteger(file.headVersion) || file.headVersion < 0))
206
+ refuse('Save result has an invalid file outcome.');
207
+ if (file.status === 'persisted') {
208
+ if (file.activated !== true || !Number.isSafeInteger(file.version) || file.version < 1 ||
209
+ typeof file.canonicalContent !== 'string' ||
210
+ file.canonicalContent.length > MAX_FILE_CHARACTERS ||
211
+ Buffer.from(file.canonicalContent, 'utf8').toString('utf8') !== file.canonicalContent)
212
+ refuse('Persisted file lacks activated source proof.');
213
+ bytes += Buffer.byteLength(file.canonicalContent, 'utf8');
214
+ if (bytes > MAX_SOURCE_BYTES) refuse('Save result exceeds the source limit.');
215
+ } else if (file.activated === true || file.canonicalContent !== undefined ||
216
+ file.version !== undefined && (!Number.isSafeInteger(file.version) || file.version < 0))
217
+ refuse('Invalid rejected or stale file outcome.');
218
+ }
219
+ if (expected.size) refuse('Save result omits a submitted path.');
220
+ return value;
221
+ }
222
+
223
+ function writeAtomic(root, name, content) {
224
+ const target = assertSafeTarget(root, name);
225
+ const stage = join(root, `.${randomUUID()}.tmp`);
226
+ try {
227
+ writeFileSync(stage, content, { flag: 'wx', mode: 0o600 });
228
+ if (sha256(readSafeFile(stage, MAX_JSON_BYTES)) !== sha256(Buffer.from(content)))
229
+ refuse('Staged save file changed.');
230
+ const fd = openSync(stage, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
231
+ try { fsyncSync(fd); }
232
+ finally { closeSync(fd); }
233
+ assertSafeTarget(root, name);
234
+ renameSync(stage, target);
235
+ } finally {
236
+ assertNoSymlinkAncestors(stage);
237
+ if (lstatIfPresent(stage)) unlinkSync(stage);
238
+ }
239
+ }
240
+
241
+ function manifestText(manifest) { return JSON.stringify(manifest, null, 2) + '\n'; }
242
+
243
+ function installCanonical(root, path, content, submittedHash, options) {
244
+ const target = assertSafeTarget(root, path);
245
+ if (sha256(safeRead(root, path, MAX_SOURCE_BYTES)) !== submittedHash)
246
+ refuse('Local source changed during save application.');
247
+ const stage = join(dirname(target), `.${randomUUID()}.tmp`);
248
+ try {
249
+ writeFileSync(stage, content, { flag: 'wx', mode: 0o600 });
250
+ if (sha256(readSafeFile(stage, MAX_SOURCE_BYTES)) !== sha256(Buffer.from(content)))
251
+ refuse('Staged canonical source changed.');
252
+ if (sha256(safeRead(root, path, MAX_SOURCE_BYTES)) !== submittedHash)
253
+ refuse('Local source changed during save application.');
254
+ (options.renameFile ?? renameSync)(stage, target);
255
+ } finally {
256
+ assertNoSymlinkAncestors(stage);
257
+ if (lstatIfPresent(stage)) unlinkSync(stage);
258
+ }
259
+ }
260
+
261
+ function retainTerminal(root, journal, terminal) {
262
+ if (journal.terminal && JSON.stringify(journal.terminal) !== JSON.stringify(terminal))
263
+ refuse('Pending save has a different terminal result.');
264
+ if (!journal.terminal) {
265
+ journal.terminal = terminal;
266
+ writeAtomic(root, SAVE_PENDING, JSON.stringify(journal) + '\n');
267
+ }
268
+ }
269
+
270
+ function manualRecovery() {
271
+ return 'Create a fresh clean checkout in a separate workspace, inspect the activated base, then merge the local edit before another save.';
272
+ }
273
+
274
+ /** Snapshot changed source and operation identity before publishing the MCP request. */
275
+ export function prepareSave(destination, appId, session, options = {}) {
276
+ return withWorkspaceMutation(destination, () => prepareSaveLocked(destination, appId, session, options));
277
+ }
278
+
279
+ function prepareSaveLocked(destination, appId, session, options) {
280
+ const root = resolve(destination);
281
+ assertNoSymlinkAncestors(root);
282
+ assertSupportSettled(root);
283
+ if (!UUID.test(appId)) refuse('Invalid app ID.');
284
+ validateSession(session);
285
+ if (lstatIfPresent(assertSafeTarget(root, PENDING))) refuse('Settle the pending checkout first.');
286
+ if (lstatIfPresent(assertSafeTarget(root, SAVE_PENDING))) refuse('A save is already pending.');
287
+ if (lstatIfPresent(assertSafeTarget(root, SAVE_REQUEST))) refuse('A prior save request remains.');
288
+ const manifest = parseManifest(safeRead(root, MANIFEST), appId);
289
+ const files = requestFiles(root, manifest);
290
+ if (files.length === 0) return { state: 'no_changes', appId };
291
+ const operationId = randomUUID();
292
+ const request = { app_id: appId, lease_id: session.leaseId,
293
+ chat_session_id: session.chatSessionId, epoch: session.epoch, operation_id: operationId, files };
294
+ if (Buffer.byteLength(JSON.stringify(request), 'utf8') > MAX_REQUEST_BYTES)
295
+ refuse('Serialized save request exceeds the HTTP body limit.');
296
+ const journal = journalFor(appId, request);
297
+ assertSupportSettled(root);
298
+ writeExclusive(root, SAVE_PENDING, JSON.stringify(journal) + '\n');
299
+ writeExclusive(root, SAVE_REQUEST, JSON.stringify(request) + '\n', options.writeRequest);
300
+ return { state: 'prepared', appId, operationId, requestPath: join(root, SAVE_REQUEST) };
301
+ }
302
+
303
+ function sameAuthority(request, session) {
304
+ return request.lease_id === session.leaseId && request.chat_session_id === session.chatSessionId &&
305
+ request.epoch === session.epoch;
306
+ }
307
+
308
+ function publishRequest(root, journal) {
309
+ assertSupportSettled(root);
310
+ const path = assertSafeTarget(root, SAVE_REQUEST);
311
+ const content = JSON.stringify(journal.request) + '\n';
312
+ if (lstatIfPresent(path)) {
313
+ const saved = safeRead(root, SAVE_REQUEST).toString('utf8');
314
+ if (saved === content) return path;
315
+ if (!journal.previous || saved !== JSON.stringify(journal.previous.request) + '\n')
316
+ refuse('Saved request differs from the pending operation.');
317
+ writeAtomic(root, SAVE_REQUEST, content);
318
+ } else writeExclusive(root, SAVE_REQUEST, content);
319
+ return path;
320
+ }
321
+
322
+ export function retrySave(destination, appId, response, options = {}) {
323
+ return withWorkspaceMutation(destination, () => retrySaveLocked(destination, appId, response, options));
324
+ }
325
+
326
+ function retrySaveLocked(destination, appId, response, options) {
327
+ const root = resolve(destination);
328
+ const manifest = parseManifest(safeRead(root, MANIFEST), appId);
329
+ let journal = readJournal(root, appId);
330
+ const value = readResult(response);
331
+ validateSession(options.session);
332
+ if (journal.terminal) refuse('The save already has a terminal result.');
333
+ const previous = journal.previous?.operationId === value?.operationId ? journal.previous : journal;
334
+ validateReconciliation(value, previous, appId);
335
+ if (lstatIfPresent(assertSafeTarget(root, SAVE_REQUEST))) {
336
+ const saved = safeRead(root, SAVE_REQUEST).toString('utf8');
337
+ if (saved !== JSON.stringify(journal.request) + '\n' &&
338
+ (!journal.previous || saved !== JSON.stringify(journal.previous.request) + '\n'))
339
+ refuse('Saved request differs from the pending operation.');
340
+ }
341
+ if (value.state === 'receipt_absent') {
342
+ if (previous !== journal || !sameAuthority(journal.request, options.session))
343
+ refuse('Exact retry requires the original current authority tuple.');
344
+ } else if (value.state === 'retryable') {
345
+ for (const file of previous.submitted) {
346
+ const head = value.heads.find(item => item.path === file.path);
347
+ const base = manifest.files[file.path];
348
+ if (!head || (file.baseVersion === 0 ? base || head.status !== 'head_missing' :
349
+ !base || base.version !== file.baseVersion || head.version !== file.baseVersion || head.sha256 !== base.sha256))
350
+ refuse('Remote heads conflict with the submitted base. Reconcile in a clean workspace.');
351
+ }
352
+ if (sameAuthority(previous.request, options.session)) refuse('Fenced retry requires fresh current edit authority.');
353
+ if (previous !== journal) {
354
+ if (!sameAuthority(journal.request, options.session)) refuse('Retry journal belongs to a different authority tuple.');
355
+ } else {
356
+ const request = { ...journal.request, lease_id: options.session.leaseId,
357
+ chat_session_id: options.session.chatSessionId, epoch: options.session.epoch, operation_id: randomUUID() };
358
+ const { previous: retired, ...original } = journal;
359
+ const next = { ...journalFor(appId, request), previous: original };
360
+ options.beforeJournal?.();
361
+ writeAtomic(root, SAVE_PENDING, JSON.stringify(next) + '\n');
362
+ journal = next;
363
+ options.afterJournal?.();
364
+ }
365
+ } else refuse('Uncertain recovery cannot create a save.');
366
+ const path = publishRequest(root, journal);
367
+ return { state: 'retry_ready', appId, operationId: journal.operationId, requestPath: path };
368
+ }
369
+
370
+ /** Apply only activated terminal file outcomes against the exact submitted local bytes. */
371
+ export function applySave(destination, appId, response, options = {}) {
372
+ return withWorkspaceMutation(destination, () => applySaveLocked(destination, appId, response, options));
373
+ }
374
+
375
+ function applySaveLocked(destination, appId, response, options) {
376
+ const root = resolve(destination);
377
+ assertNoSymlinkAncestors(root);
378
+ const journal = readJournal(root, appId);
379
+ const value = response === undefined ? journal.terminal : readResult(response);
380
+ if (!value || value.operationId !== journal.operationId ||
381
+ (value.appId !== undefined && value.appId !== appId))
382
+ refuse('Save result does not match the pending operation.');
383
+ if (value.state === 'reconcile_required')
384
+ return { state: 'pending', appId, operationId: journal.operationId,
385
+ nextAction: 'Call reconcile_build before another operation.' };
386
+ const terminal = validatedTerminal(value, journal);
387
+ const manifest = parseManifest(safeRead(root, MANIFEST), appId);
388
+ for (const path of [SAVE_PENDING, SAVE_REQUEST, SAVE_OUTCOME, MANIFEST,
389
+ ...terminal.files.map(file => file.path)]) assertSafeTarget(root, path);
390
+ const { previewUrl, ...retained } = terminal;
391
+ retainTerminal(root, journal, retained);
392
+ const outcomes = [];
393
+ let changedManifest = false;
394
+ for (const file of terminal.files) {
395
+ const submitted = journal.submitted.find(item => item.path === file.path);
396
+ if (file.status !== 'persisted') {
397
+ outcomes.push({ path: file.path, status: file.status,
398
+ ...(file.diagnostics === undefined ? {} : { diagnostics: file.diagnostics }),
399
+ nextAction: file.status === 'stale' ? manualRecovery() : 'Review diagnostics and edit locally.' });
400
+ continue;
401
+ }
402
+ const target = assertSafeTarget(root, file.path);
403
+ const stat = lstatIfPresent(target);
404
+ const old = manifest.files[file.path];
405
+ const canonicalHash = sha256(Buffer.from(file.canonicalContent, 'utf8'));
406
+ const localHash = stat ? sha256(safeRead(root, file.path, MAX_SOURCE_BYTES)) : null;
407
+ if (old?.version === file.version && old.sha256 === canonicalHash && localHash === canonicalHash) {
408
+ outcomes.push({ path: file.path, status: 'persisted', version: file.version });
409
+ continue;
410
+ }
411
+ if (!stat || old && old.version !== submitted.baseVersion ||
412
+ !old && submitted.baseVersion !== 0) {
413
+ outcomes.push({ path: file.path, status: 'LOCAL_CHANGED', nextAction: manualRecovery() });
414
+ continue;
415
+ }
416
+ if (localHash !== submitted.sha256 && localHash !== canonicalHash) {
417
+ outcomes.push({ path: file.path, status: 'LOCAL_CHANGED', nextAction: manualRecovery() });
418
+ continue;
419
+ }
420
+ if (localHash === submitted.sha256 && localHash !== canonicalHash)
421
+ installCanonical(root, file.path, file.canonicalContent, submitted.sha256, options);
422
+ manifest.files[file.path] = { version: file.version, sha256: canonicalHash };
423
+ changedManifest = true;
424
+ outcomes.push({ path: file.path, status: 'persisted', version: file.version });
425
+ }
426
+ if (changedManifest) writeAtomic(root, MANIFEST, manifestText(manifest));
427
+ const report = { schema: 1, appId, operationId: journal.operationId,
428
+ state: 'settled', outcomes, ...(previewUrl === undefined ? {} : { previewUrl }) };
429
+ writeAtomic(root, SAVE_OUTCOME, JSON.stringify(report) + '\n');
430
+ const requestPath = assertSafeTarget(root, SAVE_REQUEST);
431
+ if (lstatIfPresent(requestPath)) {
432
+ if (sha256(safeRead(root, SAVE_REQUEST)) !==
433
+ sha256(Buffer.from(JSON.stringify(journal.request) + '\n')))
434
+ refuse('Saved request differs from the pending operation.');
435
+ unlinkSync(requestPath);
436
+ }
437
+ (options.removeJournal ?? unlinkSync)(assertSafeTarget(root, SAVE_PENDING));
438
+ return report;
439
+ }
440
+
441
+ /** Read a server reconciliation without assigning uncertain heads to the operation. */
442
+ function validateReconciliation(value, journal, appId) {
443
+ if (!value || value.operationId !== journal.operationId ||
444
+ (value.appId !== undefined && value.appId !== appId) || !Array.isArray(value.heads) ||
445
+ value.heads.length > MAX_SAVE_FILES ||
446
+ !['terminal', 'receipt_absent', 'reconcile_required', 'retryable'].includes(value.state))
447
+ refuse('Reconciliation does not match the pending operation.');
448
+ const submitted = new Set(journal.submitted.map(file => file.path));
449
+ const seen = new Set();
450
+ const heads = value.heads.map(head => {
451
+ if (!head || typeof head !== 'object' || !submitted.has(head.path) || seen.has(head.path) ||
452
+ head.version !== undefined && (!Number.isSafeInteger(head.version) || head.version < 0) ||
453
+ head.sha256 !== undefined && !SHA256.test(head.sha256))
454
+ refuse('Invalid reconciliation head.');
455
+ seen.add(head.path);
456
+ return { path: head.path, status: head.status, ...(head.version === undefined ? {} : { version: head.version }),
457
+ ...(head.sha256 === undefined ? {} : { sha256: head.sha256 }) };
458
+ });
459
+ if (journal.terminal && value.state !== 'terminal') refuse('The save already has a terminal result.');
460
+ if (value.state === 'retryable') {
461
+ if (!Array.isArray(value.submitted) || value.submitted.length !== journal.submitted.length ||
462
+ journal.submitted.some(file => !value.submitted.some(item =>
463
+ exactKeys(item, ['path', 'baseVersion', 'hash']) && item.path === file.path &&
464
+ item.baseVersion === file.baseVersion && item.hash === file.sha256)))
465
+ refuse('Recovery submitted identities do not match the pending operation.');
466
+ }
467
+ if (value.state !== 'terminal' && value.receipt !== undefined)
468
+ refuse('Uncertain reconciliation cannot carry a terminal receipt.');
469
+ return heads;
470
+ }
471
+
472
+ export function reconcileSave(destination, appId, response, options = {}) {
473
+ return withWorkspaceMutation(destination, () => reconcileSaveLocked(destination, appId, response, options));
474
+ }
475
+
476
+ function reconcileSaveLocked(destination, appId, response, options) {
477
+ const root = resolve(destination);
478
+ parseManifest(safeRead(root, MANIFEST), appId);
479
+ const journal = readJournal(root, appId);
480
+ const value = readResult(response);
481
+ const heads = validateReconciliation(value, journal, appId);
482
+ if (value.state === 'terminal') {
483
+ if (!value.receipt) refuse('Terminal reconciliation lacks a receipt.');
484
+ return applySave(root, appId, value.receipt, options);
485
+ }
486
+ if (value.receipt !== undefined) refuse('Uncertain reconciliation cannot carry a terminal receipt.');
487
+ return { state: value.state, appId, operationId: journal.operationId,
488
+ heads, nextAction: value.state === 'retryable'
489
+ ? 'Reopen for fresh authority, then retry only if activated bases are unchanged.' : value.state === 'receipt_absent'
490
+ ? 'The original may still arrive. Retry only the exact saved operation ID and payload.'
491
+ : 'Inspect current heads and wait or reconcile again; do not start a new save.' };
492
+ }
493
+
494
+ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
495
+ try {
496
+ const [command, destination, appId, ...args] = process.argv.slice(2);
497
+ let result;
498
+ if (command === 'prepare' && args.length === 3)
499
+ result = prepareSave(destination, appId, { leaseId: args[0], chatSessionId: args[1], epoch: Number(args[2]) });
500
+ else if (command === 'apply' && args.length <= 1)
501
+ result = applySave(destination, appId, args[0]);
502
+ else if (command === 'reconcile' && args.length === 1)
503
+ result = reconcileSave(destination, appId, args[0]);
504
+ else if (command === 'retry' && args.length === 4)
505
+ result = retrySave(destination, appId, args[0], { session: {
506
+ leaseId: args[1], chatSessionId: args[2], epoch: Number(args[3]) } });
507
+ else refuse('Usage: local-save.mjs <prepare|apply|reconcile|retry> <workspace> <app-id> [arguments]');
508
+ process.stdout.write(JSON.stringify(result) + '\n');
509
+ } catch (error) {
510
+ process.stderr.write(`${error.message}\n`);
511
+ process.exitCode = 1;
512
+ }
513
+ }