@arcfold/dsh 0.0.0-stage → 0.4.0

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 (127) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +8 -2
  3. package/THIRD_PARTY_NOTICES.md +11 -0
  4. package/cordis.patch.yml +138 -0
  5. package/package.json +70 -4
  6. package/patches/deepseek-0.2.2-rc.1-transport.json +65 -0
  7. package/patches/deepseek-0.2.2-rc.1-transport.patch +61 -0
  8. package/presets/arcfold.patch.yml +110 -0
  9. package/runtime/README.md +19 -0
  10. package/runtime/bootstrap.json +15 -0
  11. package/runtime/desktop-python.tar.gz +0 -0
  12. package/runtime/host/package.json +11 -0
  13. package/runtime/host/pnpm-workspace.yaml +9 -0
  14. package/runtime/initial-policy.json +94 -0
  15. package/runtime/profile/pnpm-workspace.yaml +7 -0
  16. package/scripts/exact-package-patch.mjs +106 -0
  17. package/scripts/patch-deepseek-transport.mjs +14 -0
  18. package/src/agent.mjs +56 -0
  19. package/src/browse-scope.mjs +14 -0
  20. package/src/budget.mjs +369 -0
  21. package/src/business.mjs +334 -0
  22. package/src/context-material.mjs +119 -0
  23. package/src/deepseek-budget-plugin.mjs +58 -0
  24. package/src/deepseek-provider.mjs +57 -0
  25. package/src/deepseek-receipt.mjs +97 -0
  26. package/src/deepseek-transport.mjs +97 -0
  27. package/src/desktop/adapter.mjs +16 -0
  28. package/src/desktop/bootstrap.mjs +84 -0
  29. package/src/desktop/configuration.mjs +117 -0
  30. package/src/desktop/provider.mjs +46 -0
  31. package/src/desktop/python-runtime.mjs +105 -0
  32. package/src/desktop/setup-service.mjs +81 -0
  33. package/src/desktop/vendor/LICENSE.deepseek +21 -0
  34. package/src/desktop/vendor/NOTICE.md +5 -0
  35. package/src/desktop/vendor/deepseek-0.2.2-rc.1.mjs +2919 -0
  36. package/src/evidence-ownership.mjs +51 -0
  37. package/src/evidence.mjs +35 -0
  38. package/src/goal-context.mjs +52 -0
  39. package/src/goal-execution-tool.mjs +74 -0
  40. package/src/goal-execution.mjs +333 -0
  41. package/src/goal-tool.mjs +56 -0
  42. package/src/goal-work-control.mjs +63 -0
  43. package/src/goal-work.mjs +257 -0
  44. package/src/goals.mjs +578 -0
  45. package/src/importer.mjs +298 -0
  46. package/src/index.mjs +53 -0
  47. package/src/learning-contracts.mjs +220 -0
  48. package/src/learning-defaults.mjs +98 -0
  49. package/src/learning-goals.mjs +165 -0
  50. package/src/learning-plugin.mjs +28 -0
  51. package/src/learning-runner.mjs +275 -0
  52. package/src/learning.mjs +534 -0
  53. package/src/legacy-export.mjs +332 -0
  54. package/src/legacy-import-source.mjs +356 -0
  55. package/src/metered-provider-host.mjs +101 -0
  56. package/src/metered-transport.mjs +435 -0
  57. package/src/method-context.mjs +57 -0
  58. package/src/method-lifecycle.mjs +34 -0
  59. package/src/method-tool.mjs +61 -0
  60. package/src/methods.mjs +425 -0
  61. package/src/model-selection.mjs +41 -0
  62. package/src/native-context-call.mjs +88 -0
  63. package/src/native-continuation.mjs +217 -0
  64. package/src/native-request-authority.mjs +90 -0
  65. package/src/openai-models.mjs +4 -0
  66. package/src/openai-receipt.mjs +98 -0
  67. package/src/openai-transport.mjs +167 -0
  68. package/src/openai-usage.mjs +194 -0
  69. package/src/opportunities.mjs +295 -0
  70. package/src/preparation-artifacts.mjs +213 -0
  71. package/src/preparation-plugin.mjs +290 -0
  72. package/src/runtime-command.mjs +264 -0
  73. package/src/runtime-config.mjs +417 -0
  74. package/src/runtime-guard.mjs +284 -0
  75. package/src/runtime-host.mjs +212 -0
  76. package/src/runtime-init.mjs +278 -0
  77. package/src/runtime-installation.mjs +518 -0
  78. package/src/runtime-lifecycle.mjs +227 -0
  79. package/src/runtime-model-settings.mjs +111 -0
  80. package/src/runtime-readiness.mjs +285 -0
  81. package/src/runtime-workspace.mjs +18 -0
  82. package/src/session-bridge.mjs +365 -0
  83. package/src/store.mjs +394 -0
  84. package/src/tree/LICENSE +21 -0
  85. package/src/tree/attribution.mjs +120 -0
  86. package/src/tree/clusters.mjs +61 -0
  87. package/src/tree/consolidation.mjs +103 -0
  88. package/src/tree/context.mjs +211 -0
  89. package/src/tree/contracts.mjs +142 -0
  90. package/src/tree/experience.mjs +140 -0
  91. package/src/tree/experiment-budget.mjs +84 -0
  92. package/src/tree/hooks.mjs +254 -0
  93. package/src/tree/host-context.mjs +107 -0
  94. package/src/tree/host-process.mjs +288 -0
  95. package/src/tree/host.mjs +37 -0
  96. package/src/tree/improvement.mjs +106 -0
  97. package/src/tree/items.mjs +294 -0
  98. package/src/tree/jobs.mjs +184 -0
  99. package/src/tree/learning.mjs +202 -0
  100. package/src/tree/metrics.mjs +203 -0
  101. package/src/tree/model-owner.mjs +254 -0
  102. package/src/tree/observations.mjs +73 -0
  103. package/src/tree/prompts.mjs +500 -0
  104. package/src/tree/reports.mjs +67 -0
  105. package/src/tree/repository.mjs +236 -0
  106. package/src/tree/runtime.mjs +745 -0
  107. package/src/tree/script-writer.mjs +149 -0
  108. package/src/tree/scripts.mjs +208 -0
  109. package/src/tree/signals.mjs +118 -0
  110. package/src/tree/snapshots.mjs +379 -0
  111. package/src/tree/token-counter.mjs +75 -0
  112. package/src/tree/token-counter.py +37 -0
  113. package/src/tree/tokenizer-resources/LICENSE +21 -0
  114. package/src/tree/tokenizer-resources/README.md +31 -0
  115. package/src/tree/tokenizer-resources/deepseek_recipe-0.2.0-cp310-abi3-macosx_11_0_arm64.whl +0 -0
  116. package/src/tree/tokenizer-resources/manifest.json +61 -0
  117. package/src/tree/tokenizer-resources/native.pyi +1042 -0
  118. package/src/tree/tokenizer-resources/tokenizer-NOTICE.md +26 -0
  119. package/src/tree/tokenizer-resources/tokenizer-v4-NOTICE.md +27 -0
  120. package/src/tree/tokenizer-resources/tokenizer-v4.json +267359 -0
  121. package/src/tree/tokenizer-resources/tokenizer.json +267359 -0
  122. package/src/tree/tools.mjs +99 -0
  123. package/src/tree/tree.mjs +202 -0
  124. package/src/tree/ui.mjs +285 -0
  125. package/src/tree/verification.mjs +143 -0
  126. package/src/understandings.mjs +309 -0
  127. package/src/web-budget-recovery.mjs +181 -0
@@ -0,0 +1,518 @@
1
+ import assert from 'node:assert/strict';
2
+ import { spawn } from 'node:child_process';
3
+ import { createHash } from 'node:crypto';
4
+ import { constants, closeSync, copyFileSync, cpSync, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, readlinkSync, realpathSync, writeFileSync } from 'node:fs';
5
+ import { createRequire } from 'node:module';
6
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
7
+ import { fileURLToPath, pathToFileURL } from 'node:url';
8
+
9
+ const SELF = fileURLToPath(import.meta.url), HERE = dirname(SELF), CORE = '@arcfold/dsh', UI = '@arcfold/dsh-method-ui';
10
+ const BUNDLES = ['@deepseek-ai/dsh-base', '@deepseek-ai/dsh-web-app', CORE];
11
+ const json = path => JSON.parse(readFileSync(path, 'utf8'));
12
+ const sha = bytes => createHash('sha256').update(bytes).digest('hex');
13
+ const save = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
14
+ const within = (root, path) => path === root || path.startsWith(root + sep);
15
+ const errorData = error => ({ name: error.name, message: error.message, stack: error.stack });
16
+ const safe = path => { assert.ok(typeof path === 'string' && path && !isAbsolute(path) && !path.split(/[\\/]/).some(x => x === '..' || x === '')); return path; };
17
+ const file = path => ({ sha256: sha(readFileSync(path)), bytes: lstatSync(path).size });
18
+ const copy = (from, to) => { mkdirSync(dirname(to), { recursive: true, mode: 0o700 }); copyFileSync(from, to, constants.COPYFILE_EXCL); };
19
+ function newDestination(path, sources) {
20
+ const absolute = resolve(path), destination = join(realpathSync(dirname(absolute)), absolute.slice(dirname(absolute).length + 1));
21
+ for (const source of sources.filter(Boolean)) {
22
+ const root = realpathSync(resolve(source));
23
+ assert.ok(!within(root, destination) && !within(destination, root), 'Installation stage must be separate from its source resources');
24
+ }
25
+ return destination;
26
+ }
27
+
28
+ function checkPlatform(bootstrap) {
29
+ assert.equal(bootstrap.schema, 'arcfold-runtime-bootstrap-v1');
30
+ assert.deepEqual([bootstrap.platform, bootstrap.arch, bootstrap.node, bootstrap.dsh, bootstrap.cordis, bootstrap.pnpm.version],
31
+ ['darwin', 'arm64', '24.15.0', '0.2.2-rc.1', '4.1.0', '11.28.5']);
32
+ assert.equal(bootstrap.pnpm.url, 'https://registry.npmjs.org/pnpm/-/pnpm-11.28.5.tgz');
33
+ assert.equal(bootstrap.pnpm.sha256, '1ef4e447a68713656064f3f174c0f44719960a043a3fe2299169d08cf1dbf8ee');
34
+ assert.equal(bootstrap.pnpm.bytes, 5736887);
35
+ assert.equal(process.platform, bootstrap.platform, 'Unverified installation platform');
36
+ assert.equal(process.arch, bootstrap.arch, 'Unverified installation architecture');
37
+ assert.equal(process.versions.node, bootstrap.node, 'Use the verified Node version');
38
+ }
39
+ function releaseAt(directory) {
40
+ const root = realpathSync(resolve(directory)), manifest = json(join(root, 'manifest.json'));
41
+ assert.equal(manifest.schema, 'arcfold-release-v1');
42
+ assert.match(manifest.source.commit, /^[a-f0-9]{40}$/);
43
+ assert.deepEqual(manifest.packages.map(p => p.name).sort(), [CORE, UI].sort());
44
+ for (const item of manifest.packages) {
45
+ const archive = join(root, safe(item.file)); assert.equal(realpathSync(archive), archive);
46
+ assert.deepEqual(file(archive), { sha256: item.sha256, bytes: item.bytes });
47
+ assert.equal('sha512-' + createHash('sha512').update(readFileSync(archive)).digest('base64'), item.integrity);
48
+ }
49
+ return { root, manifest, manifestSHA: file(join(root, 'manifest.json')).sha256 };
50
+ }
51
+ function inventory(root, skipModules = false) {
52
+ const rows = [];
53
+ function walk(path = '') {
54
+ const full = join(root, path), st = lstatSync(full);
55
+ if (st.isSymbolicLink()) {
56
+ assert.ok(within(root, realpathSync(full)), 'Installed package symlink escapes its root');
57
+ rows.push({ path, link: readlinkSync(full) });
58
+ } else if (st.isDirectory()) for (const name of readdirSync(full).sort()) {
59
+ if (!skipModules || name !== 'node_modules') walk(path ? path + '/' + name : name);
60
+ } else { assert.ok(st.isFile()); rows.push({ path, ...file(full), executable: st.mode & 0o111 }); }
61
+ }
62
+ walk(); return rows;
63
+ }
64
+ function packagesAt(nodeModules) {
65
+ const rows = [];
66
+ function visit(modules) {
67
+ for (const name of readdirSync(modules).sort()) {
68
+ if (name.startsWith('.')) continue;
69
+ const roots = name.startsWith('@') ? readdirSync(join(modules, name)).sort().map(x => join(modules, name, x)) : [join(modules, name)];
70
+ for (const root of roots) {
71
+ assert.equal(lstatSync(root).isSymbolicLink(), false, 'Supply requires the official hoisted layout');
72
+ const pkg = json(join(root, 'package.json')), files = inventory(root, true);
73
+ rows.push({ name: pkg.name, version: pkg.version, location: relative(nodeModules, root), files, payloadSHA: sha(JSON.stringify(files)) });
74
+ if (existsSync(join(root, 'node_modules'))) visit(join(root, 'node_modules'));
75
+ }
76
+ }
77
+ }
78
+ visit(nodeModules); return rows.sort((a, b) => (a.name + '@' + a.version + ':' + a.location).localeCompare(b.name + '@' + b.version + ':' + b.location));
79
+ }
80
+ const packageSet = rows => rows.map(({ name, version, payloadSHA }) => ({ name, version, payloadSHA })).sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)));
81
+ const targetIdentity = row => row && { scope: row.scope, name: row.name, version: row.version, payloadSHA: row.payloadSHA };
82
+ function comparableGraph(graph) {
83
+ // Do not collapse equal package names: every concrete consumer remains an array entry.
84
+ // Physical location may differ; scope, payload, declared edges and multiplicity may not.
85
+ const ordered = rows => rows.sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)));
86
+ const consumers = graph.map(({ owner, requires }) => ({ owner: targetIdentity(owner), requires: requires.map(({ target, ...edge }) => ({ ...edge, target: targetIdentity(target) })) }));
87
+ const sharing = new Map();
88
+ for (const { owner, requires } of graph) for (const { target, ...edge } of requires) if (target) {
89
+ const key = target.scope + '/' + target.location;
90
+ if (!sharing.has(key)) sharing.set(key, { target: targetIdentity(target), consumers: [] });
91
+ sharing.get(key).consumers.push({ owner: targetIdentity(owner), ...edge });
92
+ }
93
+ // Retain which consumers share one actual instance, without requiring that instance's hoist path.
94
+ return { consumers: ordered(consumers), sharedTargets: ordered([...sharing.values()].map(row => ({ ...row, consumers: ordered(row.consumers) }))) };
95
+ }
96
+ function consumerGraph(state, api, requireHost, packages, hostCordis, uiRoot) {
97
+ const instances = new Map();
98
+ for (const scope of ['host', 'profile']) {
99
+ const modules = join(scope === 'host' ? join(state.root, 'host') : state.profileDir, 'node_modules');
100
+ for (const row of packages[scope]) instances.set(realpathSync(join(modules, row.location)), { scope, name: row.name, version: row.version, payloadSHA: row.payloadSHA, location: row.location });
101
+ }
102
+ const target = root => {
103
+ if (!root) return null;
104
+ const item = instances.get(realpathSync(root)); assert.ok(item, 'Official dependency escaped the installed host/profile inventory'); return item;
105
+ };
106
+ let browser;
107
+ function browserReact() {
108
+ if (browser) return browser;
109
+ const webApp = requireHost.resolve('@deepseek-ai/dsh-web-app/package.json');
110
+ const frontendRoot = dirname(createRequire(webApp).resolve('@deepseek-ai/dsh-web-frontend/package.json'));
111
+ const frontend = target(frontendRoot); assert.equal(frontend.scope, 'host');
112
+ const shell = readFileSync(join(frontendRoot, 'dist/assets/index-BgUyXZcc.js'));
113
+ assert.equal(sha(shell), 'c7e9821660f7e0f0524cc7cb1a375a5171eebbe68e167b80d290bd2ea391286d');
114
+ const loader = readFileSync(requireHost.resolve('@deepseek-ai/dsh-client-modules/client'));
115
+ assert.equal(sha(loader), '74e834b85e44f75874198bb0e937de98fd78c2bc0c5145cc14032185f579731f');
116
+ const client = readFileSync(join(uiRoot, 'lib/client.js'), 'utf8');
117
+ assert.deepEqual([...new Set([...client.matchAll(/\brequire\("([^"\n]+)"\)/g)].map(x => x[1]))], ['react']);
118
+ // Fixed official shell seed and loader provide the same browser React 18.3.1 object.
119
+ browser = { scope: 'browser', name: 'react', version: '18.3.1', location: 'official-shell-seed/react',
120
+ payloadSHA: sha(JSON.stringify({ frontend: targetIdentity(frontend), shell: sha(shell), loader: sha(loader), client: sha(client) })) };
121
+ return browser;
122
+ }
123
+ const graph = [];
124
+ for (const [root, owner] of instances) {
125
+ const manifest = json(join(root, 'package.json')), requires = [], parent = pathToFileURL(join(root, 'package.json')).href;
126
+ for (const field of ['dependencies', 'optionalDependencies', 'peerDependencies']) for (const [name, range] of Object.entries(manifest[field] || {}).sort()) {
127
+ const optional = field === 'optionalDependencies' || field === 'peerDependencies' && manifest.peerDependenciesMeta?.[name]?.optional === true;
128
+ const actual = api.packageOf(name, parent); let consumed = target(actual?.dir), supply = 'official-server-resolver';
129
+ if (owner.scope === 'profile' && owner.name === UI && owner.version === '0.1.0' && field === 'peerDependencies' && name === 'react') {
130
+ assert.equal(range, '18.3.1'); consumed = browserReact(); supply = 'official-browser-seed';
131
+ } else if (!optional) assert.ok(consumed, 'Missing required dependency: ' + owner.name + ' -> ' + name);
132
+ if (name === '@deepseek-ai/cordis' && actual) assert.equal(realpathSync(actual.dir), hostCordis, 'A declared Cordis consumer chose another instance');
133
+ requires.push({ field, name, range, optional, supply, target: consumed });
134
+ }
135
+ graph.push({ owner, requires });
136
+ }
137
+ return graph;
138
+ }
139
+
140
+ async function run(state, label, executable, args, cwd = state.root) {
141
+ state.signal?.throwIfAborted();
142
+ const base = join(state.root, 'commands', label), stdout = openSync(base + '.stdout.log', 'wx', 0o600), stderr = openSync(base + '.stderr.log', 'wx', 0o600);
143
+ let child, timer, hardTimer, aborted = false, timedOut = false;
144
+ const kill = signal => { if (!child?.pid) return; try { process.kill(-child.pid, signal); } catch (error) { if (error.code !== 'ESRCH') throw error; } };
145
+ const stop = () => { kill('SIGTERM'); hardTimer ??= setTimeout(() => kill('SIGKILL'), 5000); };
146
+ const abort = () => { aborted = true; stop(); };
147
+ let result;
148
+ try {
149
+ child = spawn(executable, args, { cwd, env: state.env, detached: true, stdio: ['ignore', stdout, stderr] });
150
+ save(base + '.command.json', { executable, args, cwd, environmentKeys: Object.keys(state.env).sort(), pid: child.pid, startedAt: new Date().toISOString() });
151
+ state.signal?.addEventListener('abort', abort, { once: true }); if (state.signal?.aborted) abort();
152
+ timer = setTimeout(() => { timedOut = true; stop(); }, 900000);
153
+ result = await new Promise(done => { child.once('error', error => done({ code: null, error: errorData(error) })); child.once('close', (code, signal) => done({ code, signal })); });
154
+ } finally {
155
+ clearTimeout(timer); clearTimeout(hardTimer); state.signal?.removeEventListener('abort', abort); closeSync(stdout); closeSync(stderr);
156
+ }
157
+ save(base + '.result.json', { ...result, aborted, timedOut, endedAt: new Date().toISOString() });
158
+ assert.ok(!aborted && !timedOut && result.code === 0, `${label} failed; preserved logs: ${base}`);
159
+ }
160
+
161
+ async function initialize(root, bootstrap, offlineStore, signal, ownedCache) {
162
+ checkPlatform(bootstrap); assert.equal(isAbsolute(root), true);
163
+ mkdirSync(root, { mode: 0o700 }); // Existing successful or failed stages are never reused.
164
+ root = realpathSync(root);
165
+ for (const name of ['commands', 'tooling', 'host', 'release', 'bootstrap-home', 'bootstrap-agents', 'config', 'cache', 'store', 'tmp', 'bin']) mkdirSync(join(root, name), { mode: 0o700 });
166
+ // Only a preparation's own private download resources may be reused by its replay.
167
+ // This is not an external-resource escape hatch; public installation has no such option.
168
+ if (ownedCache) {
169
+ assert.equal(root, join(ownedCache.root, 'frozen-replay'));
170
+ assert.deepEqual(offlineStore, { pnpmArchive: join(ownedCache.root, 'tooling/pnpm.tgz'),
171
+ storeDir: join(ownedCache.root, 'store'), cacheDir: join(ownedCache.root, 'cache') });
172
+ }
173
+ const cacheRoot = ownedCache?.root ?? root, config = join(root, 'config');
174
+ for (const name of ['npmrc', 'npm-globalrc']) writeFileSync(join(config, name), '', { flag: 'wx', mode: 0o600 });
175
+ const env = { PATH: join(root, 'bin') + ':' + dirname(process.execPath) + ':/usr/bin:/bin', HOME: join(root, 'bootstrap-home'),
176
+ DSH_HOME: join(root, 'bootstrap-home'), DSH_AGENTS_HOME: join(root, 'bootstrap-agents'), TMPDIR: join(root, 'tmp'),
177
+ XDG_CONFIG_HOME: config, XDG_CACHE_HOME: join(cacheRoot, 'cache'), XDG_STATE_HOME: join(root, 'bootstrap-home'), XDG_DATA_HOME: join(root, 'bootstrap-home'),
178
+ NPM_CONFIG_USERCONFIG: join(config, 'npmrc'), NPM_CONFIG_GLOBALCONFIG: join(config, 'npm-globalrc'),
179
+ NPM_CONFIG_CACHE: join(cacheRoot, 'cache'), CI: '1', LANG: 'en_US.UTF-8', NODE_DISABLE_COMPILE_CACHE: '1' };
180
+ for (const [key, value] of Object.entries({ store_dir: join(cacheRoot, 'store'), cache_dir: join(cacheRoot, 'cache'), config_dir: config,
181
+ state_dir: join(root, 'bootstrap-home'), userconfig: join(config, 'npmrc'), globalconfig: join(config, 'npm-globalrc'),
182
+ ignore_scripts: 'true', ignore_pnpmfile: 'true', package_import_method: 'copy', offline: offlineStore ? 'true' : 'false', registry: 'https://registry.npmjs.org/' })) {
183
+ env['npm_config_' + key] = value; env['pnpm_config_' + key] = value;
184
+ }
185
+ const state = { root, bootstrap, env, signal, profileName: 'arcfold', profileDir: join(root, 'bootstrap-home/profiles/arcfold') };
186
+ save(join(root, 'install-start.json'), { schema: 'arcfold-install-stage-v1', bootstrap, offline: Boolean(offlineStore), cacheOwner: cacheRoot, reusedPrivateCache: Boolean(ownedCache), startedAt: new Date().toISOString() });
187
+ try {
188
+ const archive = join(root, 'tooling/pnpm.tgz');
189
+ if (offlineStore) {
190
+ assert.ok(Object.keys(offlineStore).every(key => ['pnpmArchive', 'storeDir', 'cacheDir'].includes(key)) && offlineStore.pnpmArchive && offlineStore.storeDir);
191
+ copy(realpathSync(resolve(offlineStore.pnpmArchive)), archive);
192
+ for (const [key, destination] of [['storeDir', 'store'], ['cacheDir', 'cache']]) if (offlineStore[key] && !ownedCache) {
193
+ const source = realpathSync(resolve(offlineStore[key]));
194
+ assert.ok(inventory(source).every(row => row.link === undefined), 'Offline resources must not link back into immutable sources');
195
+ cpSync(source, join(root, destination), { recursive: true, dereference: false, errorOnExist: true, force: false });
196
+ }
197
+ } else {
198
+ const response = await fetch(bootstrap.pnpm.url, { redirect: 'error', signal: AbortSignal.any([AbortSignal.timeout(120000), ...(signal ? [signal] : [])]) });
199
+ assert.equal(response.status, 200, 'Pinned pnpm download failed');
200
+ writeFileSync(archive, Buffer.from(await response.arrayBuffer()), { flag: 'wx', mode: 0o600 });
201
+ }
202
+ assert.deepEqual(file(archive), { sha256: bootstrap.pnpm.sha256, bytes: bootstrap.pnpm.bytes });
203
+ assert.equal('sha512-' + createHash('sha512').update(readFileSync(archive)).digest('base64'), bootstrap.pnpm.integrity);
204
+ await run(state, 'extract-pnpm', '/usr/bin/tar', ['-xzf', archive, '-C', join(root, 'tooling')]);
205
+ const pkg = json(join(root, 'tooling/package/package.json')); assert.equal(pkg.name, 'pnpm'); assert.equal(pkg.version, bootstrap.pnpm.version);
206
+ state.pnpm = join(root, 'tooling/package/bin/pnpm.mjs');
207
+ // Official plugin management invokes pnpm by name; this local wrapper never consults a user/global install.
208
+ const quote = text => "'" + text.replaceAll("'", "'\\''") + "'";
209
+ writeFileSync(join(root, 'bin/pnpm'), '#!/bin/sh\nexec ' + quote(process.execPath) + ' ' + quote(state.pnpm) + ' "$@"\n', { flag: 'wx', mode: 0o700 });
210
+ return state;
211
+ } catch (error) { save(join(root, 'failure.json'), { stage: 'bootstrap', ...errorData(error) }); throw error; }
212
+ }
213
+ function copyRelease(state, release) {
214
+ for (const pkg of release.manifest.packages) copy(join(release.root, pkg.file), join(state.root, 'release', pkg.file));
215
+ copy(join(release.root, 'manifest.json'), join(state.root, 'release/manifest.json'));
216
+ }
217
+ async function initializeProfile(state) {
218
+ const requireHost = createRequire(join(state.root, 'host/package.json'));
219
+ state.installAnchor = requireHost.resolve('@deepseek-ai/dsh/package.json');
220
+ state.cliPath = requireHost.resolve('@deepseek-ai/dsh/lib/bin.js');
221
+ assert.equal(json(state.installAnchor).version, state.bootstrap.dsh);
222
+ assert.equal(existsSync(state.profileDir), false);
223
+ await run(state, 'profile-initialize', process.execPath, [state.cliPath, '--profile', state.profileName, '--from-default-profile', 'web', '--dump-config']);
224
+ assert.deepEqual(json(join(state.profileDir, 'package.json')).dsh.profile.bundles, BUNDLES.slice(0, 2));
225
+ const yaml = await import(pathToFileURL(requireHost.resolve('js-yaml')));
226
+ const workspace = yaml.load(readFileSync(join(state.profileDir, 'pnpm-workspace.yaml'), 'utf8'));
227
+ assert.equal(workspace.nodeLinker, 'hoisted'); assert.equal(workspace.autoInstallPeers, false);
228
+ }
229
+ function installFiles(state) {
230
+ const rows = [];
231
+ for (const dir of ['host/node_modules', 'bootstrap-home/profiles/arcfold/node_modules', 'tooling/package'])
232
+ for (const row of inventory(join(state.root, dir))) rows.push({ ...row, path: dir + '/' + row.path });
233
+ for (const name of ['host/package.json', 'host/pnpm-lock.yaml', 'host/pnpm-workspace.yaml',
234
+ 'bootstrap-home/profiles/arcfold/package.json', 'bootstrap-home/profiles/arcfold/pnpm-lock.yaml',
235
+ 'bootstrap-home/profiles/arcfold/pnpm-workspace.yaml', 'bootstrap-home/profiles/arcfold/cordis.patch.yml']) {
236
+ assert.equal(lstatSync(join(state.root, name)).isSymbolicLink(), false);
237
+ rows.push({ path: name, ...file(join(state.root, name)) });
238
+ }
239
+ return rows.sort((a, b) => a.path.localeCompare(b.path));
240
+ }
241
+ const PROVIDERS = [
242
+ { key: 'deepseek-official', package: '@deepseek-ai/dsh-llm-deepseek', wrapper: 'deepseek-provider',
243
+ script: 'patch-deepseek-transport', inspect: 'inspectDeepSeekPatch', apply: 'applyDeepSeekPatch', receipt: 'provider-patch' },
244
+ { key: 'openai', package: '@deepseek-ai/dsh-llm-pi-ai', wrapper: 'openai-provider',
245
+ script: 'patch-pi-ai-transport', inspect: 'inspectPiAiPatch', apply: 'applyPiAiPatch', receipt: 'pi-ai-patch' },
246
+ ];
247
+
248
+ const MODEL_SELECTION = { key: 'modelSelection', package: '@deepseek-ai/dsh-api-session-controller',
249
+ script: 'patch-model-selection', inspect: 'inspectModelSelectionPatch', apply: 'applyModelSelectionPatch', receipt: 'model-selection-patch' };
250
+
251
+ /** The root Include consumes bare controller names from profile/cordis.yml's directory.
252
+ * This is distinct from the two wrappers' own dependency imports. Check all three
253
+ * original targets before any patch writes or module imports. */
254
+ export async function inspectNativeComponents({ api, coreRoot, profileDir, installationDir, profileEntries, patch = false }) {
255
+ const controllers = profileEntries?.filter(entry => entry.id === 'session-controller');
256
+ assert.equal(controllers?.length, 1, 'The actual profile must contain exactly one session controller');
257
+ assert.equal(controllers[0].name, MODEL_SELECTION.package, 'The profile replaced the native session controller');
258
+ assert.notEqual(controllers[0].disabled, true, 'The native session controller must be enabled');
259
+ const targets = [];
260
+ for (const definition of [...PROVIDERS, MODEL_SELECTION]) {
261
+ const parent = definition.wrapper ? pathToFileURL(join(coreRoot, 'src', definition.wrapper + '.mjs')).href
262
+ : new URL('.', pathToFileURL(join(profileDir, 'cordis.yml'))).href;
263
+ const path = api.packageOf(definition.package, parent)?.dir;
264
+ const boundary = definition.wrapper ? profileDir : installationDir;
265
+ assert.ok(path && within(realpathSync(boundary), realpathSync(path)),
266
+ definition.wrapper ? 'Native provider must be consumed from this profile' : 'Native controller must be consumed from this installation');
267
+ assert.equal(realpathSync(createRequire(parent).resolve(definition.package)), join(path, 'lib/index.js'),
268
+ 'Official resolver and actual native consumption differ');
269
+ const patcher = await import(pathToFileURL(join(coreRoot, 'scripts', definition.script + '.mjs')));
270
+ assert.equal(patcher[definition.inspect](path).state, 'original', 'Native component must start from exact original bytes');
271
+ targets.push({ definition, path, patcher });
272
+ }
273
+ // Preserve each receipt even if a later patch or loaded capability fails.
274
+ if (patch) for (const { definition, path, patcher } of targets)
275
+ patcher[definition.apply]({ packageDir: path, receiptDir: join(installationDir, definition.receipt) });
276
+ const components = {};
277
+ for (const { definition, path, patcher } of targets) {
278
+ const entry = { path, patchId: patcher.patchSpec.id };
279
+ if (patch) {
280
+ const loaded = await import(pathToFileURL(join(path, 'lib/index.js')));
281
+ const capability = patcher.patchSpec.runtimeCapability;
282
+ assert.deepEqual(Object.getOwnPropertyDescriptor(loaded[capability.export], capability.property), {
283
+ value: capability.value, writable: false, enumerable: true, configurable: false,
284
+ }, 'The actual loaded native component lacks the frozen capability');
285
+ entry.receipt = join(installationDir, definition.receipt, 'report.json');
286
+ entry.receiptSHA256 = file(entry.receipt).sha256;
287
+ }
288
+ components[definition.key] = entry;
289
+ }
290
+ return { providers: Object.fromEntries(PROVIDERS.map(row => [row.key, components[row.key]])), modelSelection: components.modelSelection };
291
+ }
292
+
293
+ /** Verify the installed implementation without opening any persistent business or ledger file. */
294
+ export async function inspectBusinessSchema(coreRoot) {
295
+ const { Store } = await import(pathToFileURL(join(coreRoot, 'src/store.mjs')));
296
+ const store = new Store(':memory:');
297
+ try {
298
+ assert.equal(store.metaTable, 'business_meta');
299
+ assert.equal(store.db.prepare("SELECT value FROM business_meta WHERE key='schema_version'").get().value, '1');
300
+ assert.equal(store.db.prepare("SELECT name FROM sqlite_schema WHERE name='store_meta'").get(), undefined);
301
+ } finally { store.close(); }
302
+ }
303
+
304
+ async function inspect(state, release, patch, packages, expectedGraph) {
305
+ const requireHost = createRequire(join(state.root, 'host/package.json'));
306
+ const profileRequire = createRequire(join(state.profileDir, 'package.json'));
307
+ const coreRoot = dirname(profileRequire.resolve(CORE + '/package.json')), uiRoot = dirname(profileRequire.resolve(UI + '/package.json'));
308
+ for (const pkg of release.manifest.packages) {
309
+ const root = pkg.name === CORE ? coreRoot : uiRoot; assert.ok(within(state.profileDir, realpathSync(root)));
310
+ for (const item of pkg.files) assert.equal(file(join(root, safe(item.path))).sha256, item.sha256, 'Installed release content differs');
311
+ }
312
+ const { Context } = await import(pathToFileURL(requireHost.resolve('@deepseek-ai/cordis')));
313
+ const { loadProfileDirectory, createRuntimeResolution, PluginPackages, composeEntries } = await import(pathToFileURL(requireHost.resolve('@deepseek-ai/dsh-app-boot')));
314
+ assert.deepEqual(json(join(state.profileDir, 'package.json')).dsh.profile.bundles, BUNDLES);
315
+ const profile = loadProfileDirectory('dsh', state.profileDir, state.installAnchor, { userLayer: false });
316
+ assert.deepEqual(profile.skippedBundles, []); assert.deepEqual(profile.layers.map(row => row.packageName), BUNDLES);
317
+ const resolution = await createRuntimeResolution({ installAnchor: state.installAnchor, profile, home: join(state.root, 'bootstrap-home') });
318
+ const ctx = new Context(); let providers, modelSelection, graph;
319
+ try {
320
+ await ctx.plugin(PluginPackages, { resolution });
321
+ const api = ctx.get('pluginPackages');
322
+ const hostCordis = realpathSync(dirname(requireHost.resolve('@deepseek-ai/cordis/package.json')));
323
+ for (const root of [coreRoot, uiRoot]) assert.equal(realpathSync(api.packageOf('@deepseek-ai/cordis', pathToFileURL(join(root, 'package.json')).href).dir), hostCordis);
324
+ graph = consumerGraph(state, api, requireHost, packages, hostCordis, uiRoot);
325
+ if (expectedGraph) assert.deepEqual(comparableGraph(graph), comparableGraph(expectedGraph), 'Actual installed dependency consumption differs from the frozen supply');
326
+ ({ providers, modelSelection } = await inspectNativeComponents({ api, coreRoot, profileDir: state.profileDir,
327
+ installationDir: state.root, profileEntries: composeEntries(profile.layers.map(layer => layer.patches)), patch }));
328
+ const { SESSION_FORMAT_VERSION } = await import(pathToFileURL(requireHost.resolve('@deepseek-ai/dsh-session')));
329
+ assert.equal(SESSION_FORMAT_VERSION, 4);
330
+ await inspectBusinessSchema(coreRoot);
331
+ } finally { await ctx.fiber.dispose(); }
332
+ return { coreRoot, uiRoot, consumerGraph: graph, provider: providers['deepseek-official'], providers, modelSelection,
333
+ compatibility: { businessSchema: 1, nativeFormat: 4 } };
334
+ }
335
+ function replaceArchiveRoots(text, release, from, to) {
336
+ for (const pkg of release.manifest.packages) text = text.split(join(from, pkg.file)).join(to + '/' + pkg.file);
337
+ return text;
338
+ }
339
+ function supplyAt(path, release) {
340
+ path = realpathSync(resolve(path));
341
+ const root = dirname(path), supply = json(path);
342
+ assert.equal(supply.schema, 'arcfold-runtime-supply-v1'); assert.equal(supply.ready, true);
343
+ assert.equal(supply.releaseManifestSHA, release.manifestSHA); assert.equal(supply.sourceCommit, release.manifest.source.commit);
344
+ checkPlatform(supply.bootstrap);
345
+ assert.deepEqual(supply.files.map(row => row.path).sort(), ['host/package.json', 'host/pnpm-lock.yaml', 'host/pnpm-workspace.yaml',
346
+ 'packages.json', 'profile/package.json', 'profile/pnpm-lock.yaml', 'profile/pnpm-workspace.yaml'].sort());
347
+ for (const row of supply.files) assert.deepEqual(file(join(root, safe(row.path))), { sha256: row.sha256, bytes: row.bytes });
348
+ return { root, path, supply };
349
+ }
350
+
351
+ const FROZEN_INPUTS = ['package.json', 'pnpm-lock.yaml', 'pnpm-workspace.yaml'];
352
+
353
+ // Shared by supply replay and public installation: no installed node_modules are copied.
354
+ export async function materializeFrozenRuntime(state, release, sourceRoot) {
355
+ const inputs = ['host', 'profile'].flatMap(scope => FROZEN_INPUTS.map(name => ({
356
+ path: scope + '/' + name, ...file(join(sourceRoot, scope, name)),
357
+ })));
358
+ copyRelease(state, release);
359
+ for (const name of FROZEN_INPUTS) copy(join(sourceRoot, 'host', name), join(state.root, 'host', name));
360
+ await run(state, 'host-install', process.execPath, [state.pnpm, 'install', '--frozen-lockfile', '--ignore-scripts'], join(state.root, 'host'));
361
+ for (const row of inputs.filter(row => row.path.startsWith('host/')))
362
+ assert.deepEqual(file(join(state.root, row.path)), { sha256: row.sha256, bytes: row.bytes }, 'Frozen host input changed: ' + row.path);
363
+ await initializeProfile(state);
364
+ // Only the just-created empty profile is replaced by the release's actual frozen install inputs.
365
+ const relocation = [];
366
+ for (const name of FROZEN_INPUTS) {
367
+ const original = readFileSync(join(sourceRoot, 'profile', name), 'utf8');
368
+ assert.equal(sha(original), inputs.find(row => row.path === 'profile/' + name).sha256, 'Frozen profile source changed');
369
+ const content = replaceArchiveRoots(original, release, '__ARCFOLD_RELEASE_ROOT__', join(state.root, 'release'));
370
+ assert.equal(content.includes('__ARCFOLD_RELEASE_ROOT__'), false, 'Unexpected profile path placeholder');
371
+ const target = join(state.profileDir, name);
372
+ if (existsSync(target)) assert.ok(name !== 'pnpm-lock.yaml', 'Fresh profile unexpectedly has a lock');
373
+ relocation.push({ file: name, beforeSHA: sha(original), afterSHA: sha(content) });
374
+ writeFileSync(target, content, { mode: 0o600, flag: name === 'pnpm-lock.yaml' ? 'wx' : 'w' });
375
+ }
376
+ save(join(state.root, 'profile-relocation.json'), relocation);
377
+ await run(state, 'profile-install', process.execPath, [state.cliPath, 'plugin', '--profile', state.profileName, 'install', '--frozen-lockfile', '--ignore-scripts']);
378
+ for (const row of relocation) assert.equal(file(join(state.profileDir, row.file)).sha256, row.afterSHA);
379
+ for (const row of inputs) assert.deepEqual(file(join(sourceRoot, row.path)), { sha256: row.sha256, bytes: row.bytes }, 'Frozen source input changed');
380
+ return { host: packagesAt(join(state.root, 'host/node_modules')), profile: packagesAt(join(state.profileDir, 'node_modules')) };
381
+ }
382
+
383
+ /** New version installation only. Neither native user state nor a ledger is opened. */
384
+ export async function installRelease({ releaseDir, installationDir, supplyManifest, offlineStore, signal }) {
385
+ const release = releaseAt(releaseDir), source = supplyAt(supplyManifest ?? join(release.root, 'runtime/supply.json'), release);
386
+ const destination = newDestination(installationDir, [release.root, source.root, offlineStore?.storeDir, offlineStore?.cacheDir, offlineStore?.pnpmArchive]);
387
+ const state = await initialize(destination, source.supply.bootstrap, offlineStore, signal);
388
+ try {
389
+ const actualPackages = await materializeFrozenRuntime(state, release, source.root);
390
+ const expected = json(join(source.root, 'packages.json'));
391
+ for (const scope of ['host', 'profile']) assert.deepEqual(packageSet(actualPackages[scope]), expected[scope], `Actual ${scope} package payloads differ from the prepared supply`);
392
+ assert.ok(Array.isArray(expected.consumerGraph) && expected.consumerGraph.length > 0);
393
+ const { consumerGraph: graph, ...inspected } = await inspect(state, release, true, actualPackages, expected.consumerGraph);
394
+ save(join(state.root, 'dependency-consumers.json'), graph);
395
+ const files = installFiles(state); save(join(state.root, 'installation-files.json'), files);
396
+ const receipt = { schema: 'arcfold-installation-v1', installationDir: state.root, hostRoot: join(state.root, 'host'), installAnchor: state.installAnchor,
397
+ cliPath: state.cliPath, profileDir: state.profileDir, profileName: state.profileName, sourceCommit: release.manifest.source.commit,
398
+ ...inspected, packageManager: { command: process.execPath, args: [state.pnpm] },
399
+ identities: { releaseManifestSHA: release.manifestSHA, supplyManifestSHA: file(source.path).sha256,
400
+ bootstrap: source.supply.bootstrap, node: { path: process.execPath, ...file(process.execPath) },
401
+ consumers: { path: 'dependency-consumers.json', ...file(join(state.root, 'dependency-consumers.json')), count: graph.length },
402
+ fileManifest: { path: 'installation-files.json', ...file(join(state.root, 'installation-files.json')), count: files.length } },
403
+ installedAt: new Date().toISOString(), modelsCalled: 0, hostStarted: false };
404
+ save(join(state.root, 'installation.json'), receipt); return readInstallation(join(state.root, 'installation.json'));
405
+ } catch (error) { if (!existsSync(join(state.root, 'failure.json'))) save(join(state.root, 'failure.json'), { stage: 'installation', ...errorData(error) }); throw error; }
406
+ }
407
+
408
+ /** No directory creation, imports of installed code, configuration writes or service start. */
409
+ export function readInstallation(installationFile) {
410
+ const filename = realpathSync(resolve(installationFile)), receipt = json(filename), root = realpathSync(dirname(filename));
411
+ assert.equal(receipt.schema, 'arcfold-installation-v1'); assert.equal(receipt.installationDir, root);
412
+ assert.equal(receipt.profileName, 'arcfold'); assert.deepEqual(receipt.compatibility, { businessSchema: 1, nativeFormat: 4 });
413
+ checkPlatform(receipt.identities.bootstrap); assert.equal(receipt.identities.node.path, process.execPath);
414
+ assert.deepEqual(file(process.execPath), { sha256: receipt.identities.node.sha256, bytes: receipt.identities.node.bytes });
415
+ for (const path of [receipt.hostRoot, receipt.installAnchor, receipt.cliPath, receipt.profileDir, receipt.coreRoot, receipt.uiRoot, receipt.provider.path, ...receipt.packageManager.args])
416
+ assert.ok(within(root, realpathSync(path)), 'Installation reference escaped its immutable version directory');
417
+ if (receipt.providers !== undefined) {
418
+ assert.deepEqual(Object.keys(receipt.providers).sort(), PROVIDERS.map(row => row.key).sort(), 'Incomplete native provider proof');
419
+ assert.deepEqual(receipt.provider, receipt.providers['deepseek-official'], 'DeepSeek compatibility alias differs');
420
+ for (const definition of PROVIDERS) {
421
+ const entry = receipt.providers[definition.key];
422
+ assert.ok(within(realpathSync(receipt.profileDir), realpathSync(entry.path)), 'Native provider escaped its profile');
423
+ const metadata = json(join(entry.path, 'package.json'));
424
+ assert.equal(metadata.name, definition.package); assert.equal(metadata.version, '0.2.2-rc.1');
425
+ assert.equal(entry.receipt, join(root, definition.receipt, 'report.json'));
426
+ assert.ok(within(root, realpathSync(entry.receipt)), 'Provider receipt escaped its version directory');
427
+ assert.equal(file(entry.receipt).sha256, entry.receiptSHA256, 'Provider patch receipt changed');
428
+ const proof = json(entry.receipt);
429
+ assert.equal(proof.completed, true); assert.equal(proof.after.state, 'patched');
430
+ assert.equal(proof.after.packageDir, entry.path); assert.equal(proof.after.patchId, entry.patchId);
431
+ }
432
+ }
433
+ if (receipt.modelSelection !== undefined) {
434
+ const entry = receipt.modelSelection;
435
+ assert.deepEqual(Object.keys(entry).sort(), ['path', 'patchId', 'receipt', 'receiptSHA256'].sort(), 'Invalid model selection proof');
436
+ assert.ok(within(root, realpathSync(entry.path)), 'Native controller escaped its installation');
437
+ const metadata = json(join(entry.path, 'package.json'));
438
+ assert.equal(metadata.name, MODEL_SELECTION.package); assert.equal(metadata.version, '0.2.2-rc.1');
439
+ const spec = json(join(receipt.coreRoot, 'patches/session-controller-0.2.2-rc.1-model-selection.json'));
440
+ assert.equal(spec.package, MODEL_SELECTION.package); assert.equal(spec.version, metadata.version);
441
+ assert.equal(entry.patchId, spec.id);
442
+ assert.equal(entry.receipt, join(root, MODEL_SELECTION.receipt, 'report.json'));
443
+ assert.ok(within(root, realpathSync(entry.receipt)), 'Controller receipt escaped its version directory');
444
+ assert.equal(file(entry.receipt).sha256, entry.receiptSHA256, 'Controller patch receipt changed');
445
+ const proof = json(entry.receipt);
446
+ assert.equal(proof.completed, true); assert.equal(proof.after.state, 'patched');
447
+ assert.equal(proof.after.packageDir, entry.path); assert.equal(proof.after.patchId, entry.patchId);
448
+ assert.equal(proof.after.patchSpecSha256, file(join(receipt.coreRoot, 'patches/session-controller-0.2.2-rc.1-model-selection.json')).sha256);
449
+ for (const item of spec.files) assert.equal(file(join(entry.path, safe(item.path))).sha256, item.afterSha256, 'Installed controller patch bytes changed');
450
+ }
451
+ assert.equal(receipt.packageManager.command, process.execPath);
452
+ const manifest = receipt.identities.fileManifest, path = join(root, safe(manifest.path));
453
+ assert.deepEqual(file(path), { sha256: manifest.sha256, bytes: manifest.bytes });
454
+ const files = json(path); assert.equal(files.length, manifest.count);
455
+ const consumers = receipt.identities.consumers;
456
+ assert.deepEqual(file(join(root, safe(consumers.path))), { sha256: consumers.sha256, bytes: consumers.bytes });
457
+ assert.equal(json(join(root, consumers.path)).length, consumers.count);
458
+ // Includes additions/removals and links, so a new nested dependency cannot shadow an unchanged recorded file.
459
+ assert.deepEqual(installFiles({ root }), files, 'Installed code or profile assets changed');
460
+ return { ...receipt, installationFile: filename };
461
+ }
462
+
463
+ /** Release-maintenance operation, never invoked by daily start. Output remains outside both tgz archives. */
464
+ export async function prepareRuntimeSupply({ releaseDir, outputDir, offlineStore, signal }) {
465
+ const release = releaseAt(releaseDir), templates = resolve(HERE, '../runtime'), bootstrap = json(join(templates, 'bootstrap.json'));
466
+ const destination = newDestination(outputDir, [release.root, templates, offlineStore?.storeDir, offlineStore?.cacheDir, offlineStore?.pnpmArchive]);
467
+ const state = await initialize(destination, bootstrap, offlineStore, signal);
468
+ try {
469
+ copyRelease(state, release);
470
+ for (const name of ['package.json', 'pnpm-workspace.yaml']) copy(join(templates, 'host', name), join(state.root, 'host', name));
471
+ await run(state, 'host-resolve', process.execPath, [state.pnpm, 'install', '--ignore-scripts'], join(state.root, 'host'));
472
+ await initializeProfile(state);
473
+ writeFileSync(join(state.profileDir, 'pnpm-workspace.yaml'), readFileSync(join(templates, 'profile/pnpm-workspace.yaml')), { mode: 0o600 });
474
+ await run(state, 'profile-add', process.execPath, [state.cliPath, 'plugin', '--profile', state.profileName, 'add',
475
+ ...release.manifest.packages.map(pkg => join(state.root, 'release', pkg.file)), '--ignore-scripts']);
476
+ return await freezeRuntimeSupply(state, release);
477
+ } catch (error) { if (!existsSync(join(state.root, 'failure.json'))) save(join(state.root, 'failure.json'), { stage: 'supply-preparation', ...errorData(error) }); throw error; }
478
+ }
479
+
480
+ // Maintenance boundary: called only after official host resolution and profile add finish.
481
+ export async function freezeRuntimeSupply(state, release) {
482
+ const { bootstrap, signal } = state;
483
+ const target = join(state.root, 'runtime'); mkdirSync(target, { mode: 0o700 });
484
+ for (const scope of ['host', 'profile']) for (const name of FROZEN_INPUTS) {
485
+ const input = join(scope === 'host' ? join(state.root, 'host') : state.profileDir, name), output = join(target, scope, name);
486
+ mkdirSync(dirname(output), { recursive: true, mode: 0o700 });
487
+ const text = readFileSync(input, 'utf8');
488
+ const projected = scope === 'profile' ? replaceArchiveRoots(text, release, join(state.root, 'release'), '__ARCFOLD_RELEASE_ROOT__') : text;
489
+ assert.equal(projected.includes(state.root), false, 'Supply lock leaked an installation-specific path');
490
+ writeFileSync(output, projected, { flag: 'wx', mode: 0o600 });
491
+ }
492
+ // Fresh resolution and frozen install can choose different hoisted instances even
493
+ // with the same final lock. Keep the initial tree, but certify the consumer path.
494
+ const inputs = inventory(target);
495
+ const replay = await initialize(join(state.root, 'frozen-replay'), bootstrap, {
496
+ pnpmArchive: join(state.root, 'tooling/pnpm.tgz'), storeDir: join(state.root, 'store'), cacheDir: join(state.root, 'cache'),
497
+ }, signal, state);
498
+ let packages, inspected;
499
+ try {
500
+ packages = await materializeFrozenRuntime(replay, release, target);
501
+ inspected = await inspect(replay, release, false, packages);
502
+ assert.deepEqual(inventory(target), inputs, 'Frozen supply inputs changed during replay');
503
+ save(join(replay.root, 'replay-inspection.json'), { inputRoot: target, inputs, cacheOwner: state.root,
504
+ storeDir: join(state.root, 'store'), cacheDir: join(state.root, 'cache'), offline: true,
505
+ initialInstallationPreserved: true, installedPackagesCopied: false, patched: false,
506
+ packages: { host: packageSet(packages.host), profile: packageSet(packages.profile) },
507
+ consumerGraph: inspected.consumerGraph });
508
+ } catch (error) {
509
+ if (!existsSync(join(replay.root, 'failure.json'))) save(join(replay.root, 'failure.json'), { stage: 'frozen-replay', ...errorData(error) });
510
+ throw error;
511
+ }
512
+ save(join(target, 'packages.json'), { host: packageSet(packages.host), profile: packageSet(packages.profile), consumerGraph: inspected.consumerGraph });
513
+ const files = inventory(target);
514
+ save(join(target, 'supply.json'), { schema: 'arcfold-runtime-supply-v1', ready: true, bootstrap, sourceCommit: release.manifest.source.commit,
515
+ releaseManifestSHA: release.manifestSHA, files, origin: 'Clean offline frozen host/profile replay of final resolved inputs; initial resolution preserved; not a development or cache seed lock',
516
+ createdAt: new Date().toISOString(), hostStarted: false, modelCalls: 0 });
517
+ return { supplyManifest: join(target, 'supply.json'), outputDir: state.root, sourceCommit: release.manifest.source.commit };
518
+ }