@xmoon76/dsh-pi-tui 0.5.7 → 0.5.9

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 (78) hide show
  1. package/README.en.md +64 -26
  2. package/README.md +64 -26
  3. package/cordis.patch.yml +13 -0
  4. package/dist/acp-stdio.mjs +151 -0
  5. package/dist/{bootstrap-C9nl6e13.mjs → bootstrap-CVyHGQDX.mjs} +22330 -6888
  6. package/dist/browser-CDUSHIIr.mjs +76 -0
  7. package/dist/builtins.mjs +2 -2
  8. package/dist/{client-bootstrap-CGezi85O.mjs → client-bootstrap-4UoeVIHE.mjs} +2407 -1830
  9. package/dist/client-runtime-BHBlVUf5.mjs +1376 -0
  10. package/dist/{daemon-launcher-H_1r5Cqs.mjs → daemon-launcher-DxIgjBHW.mjs} +1551 -57
  11. package/dist/daemon-launcher.d.mts +85 -14
  12. package/dist/daemon-launcher.mjs +2 -2
  13. package/dist/diagnostics-Db5iVcuJ.mjs +123 -0
  14. package/dist/{entry-control-jBfKn1qO.mjs → entry-control-BDLZgg4m.mjs} +1 -1
  15. package/dist/{extensions-6a5vvJUT.mjs → extensions-Dx7ncPNA.mjs} +1 -4
  16. package/dist/extensions.mjs +1 -1
  17. package/dist/handoff-BjoEy3f8.mjs +106 -0
  18. package/dist/history-search-limits-Cx2UvRC2.mjs +16 -0
  19. package/dist/history-search-remote-BHuoellG.mjs +113 -0
  20. package/dist/history-search-remote-BzXdvrxk.mjs +26 -0
  21. package/dist/history-search-seat-BcHJTpeB.mjs +639 -0
  22. package/dist/history-search-seat-rZcq0XV6.mjs +639 -0
  23. package/dist/{host-bootstrap-MVxks641.mjs → host-bootstrap-BfnufpnW.mjs} +37 -72
  24. package/dist/{host-foundation-probe-DK7n5jDu.mjs → host-foundation-probe-DlD8-N_Q.mjs} +2 -2
  25. package/dist/host-runtime.mjs +5611 -290
  26. package/dist/index.d.mts +13 -6
  27. package/dist/index.mjs +22766 -6893
  28. package/dist/installed-dsh-BjUiJSwR.mjs +142 -0
  29. package/dist/interaction-port-D1Yv9zgu.mjs +45 -0
  30. package/dist/local-acp-control-CC5z4Xbq.mjs +304 -0
  31. package/dist/local-acp-endpoint-D1jYdJdv.mjs +41 -0
  32. package/dist/local-acp-listener-Cmgb5M0H.mjs +9493 -0
  33. package/dist/local-acp-status-B_25Q6kU.mjs +101 -0
  34. package/dist/local-client.mjs +719 -93
  35. package/dist/local-daemon-control-BFJAC8Kg.mjs +2199 -0
  36. package/dist/local-daemon-control-Bm3imctD.mjs +2101 -0
  37. package/dist/{local-discovery-BPZw1wEd.mjs → local-discovery-BMhaGIiJ.mjs} +254 -544
  38. package/dist/{local-discovery-BMoNXZjJ.mjs → local-discovery-Ba7_-NNC.mjs} +1 -1
  39. package/dist/{local-discovery-Bq3jLAn1.mjs → local-discovery-QSbFpjK2.mjs} +301 -544
  40. package/dist/local-host.mjs +970 -501
  41. package/dist/local-profile-daemon-admin-otpm69R6.mjs +469 -0
  42. package/dist/{local-scope-DEuGAy8l.mjs → local-scope-5DEKA_lW.mjs} +1075 -31
  43. package/dist/{local-transport-X4ZCe2uE.mjs → local-transport-DeWmdZ5E.mjs} +14 -3
  44. package/dist/{local-web-control-DKWtXIkr.mjs → local-web-control-Dny93N-r.mjs} +10 -7
  45. package/dist/{local-workspace-object-D06GL0UO.mjs → local-workspace-object-D0RVQt8U.mjs} +33 -9
  46. package/dist/model-selection-CYlqg2DV.mjs +83 -0
  47. package/dist/native-client-domains-Dg4srzYt.mjs +2 -0
  48. package/dist/native-client.d.mts +735 -0
  49. package/dist/native-client.mjs +3534 -0
  50. package/dist/{open-CmOBxSjN.mjs → open-QQva8-ar.mjs} +24 -20
  51. package/dist/{pi-tui-remote-contribution-Do8ECrUy.mjs → pi-tui-remote-contribution-565wiLWp.mjs} +741 -150
  52. package/dist/preferences.mjs +1 -1
  53. package/dist/{profile-preferences-migration-CThz4rHH.mjs → profile-preferences-migration-CNOWIdnr.mjs} +1 -1
  54. package/dist/{profile-preferences-migration-BfUGdPZx.mjs → profile-preferences-migration-IrnXcJWK.mjs} +10 -8
  55. package/dist/{prompt-sections-DXmjB58H.mjs → prompt-sections-Bi-9_Gr_.mjs} +28 -10
  56. package/dist/{prompt-sections-DUKmWb8g.mjs → prompt-sections-DFS1dqsY.mjs} +342 -56
  57. package/dist/{dist-BFgC-5tL.mjs → recall-scope-9Nuoto_i.mjs} +353 -1
  58. package/dist/rolldown-runtime-8H4AJuhK.mjs +14 -0
  59. package/dist/schema-CCLvDa7Q.mjs +177 -0
  60. package/dist/{schema-qE_P09zJ.mjs → schema-t97l3aK8.mjs} +56 -3
  61. package/dist/{session-DC0XQr5O.mjs → session-Cs8iLCEx.mjs} +784 -342
  62. package/dist/{session-Cihe8PPS.mjs → session-EBRZF6Ow.mjs} +783 -341
  63. package/dist/session-create-facts-CkfG5DpQ.mjs +20 -0
  64. package/dist/{startup-CarQxWwi.d.mts → startup-Dti3Udne.d.mts} +30 -3
  65. package/dist/{startup-CARqn3kV.mjs → startup-UtFQSDe_.mjs} +90 -15
  66. package/dist/startup.d.mts +2 -2
  67. package/dist/startup.mjs +1 -1
  68. package/dist/task-read-remote-DRtkXDrZ.mjs +1083 -0
  69. package/dist/{terminal-progress-source-D4DHyXDo.mjs → terminal-progress-source-VsczdXA-.mjs} +610 -335
  70. package/dist/{transcript-view-a7cROAaI.mjs → transcript-view-B6vCnukn.mjs} +2284 -1166
  71. package/dist/{transcript-view-hvNVkPtv.mjs → transcript-view-DSSdE2vK.mjs} +2191 -765
  72. package/dist/write-failure-xNKczXH7.mjs +189 -0
  73. package/package.json +25 -8
  74. package/dist/local-acp-listener-CNkguN5-.mjs +0 -2566
  75. package/dist/local-daemon-control-Bg9s2aYi.mjs +0 -1424
  76. package/dist/local-daemon-control-Cu_4FIdd.mjs +0 -1585
  77. package/dist/local-profile-daemon-admin-AXgVH-6y.mjs +0 -91
  78. package/dist/preset-BcWqOtY7.mjs +0 -46
@@ -1,8 +1,8 @@
1
- import { D as sameKernelProcess, E as readProcessStarttime, T as readKernelProcess, b as readInstalledDshVersion, g as computeBuildId, p as LocalScopeError, w as parseProcessStat, y as installedPackageRootFromEntry } from "./daemon-launcher-H_1r5Cqs.mjs";
2
- import { accessSync, closeSync, constants, existsSync, fchmodSync, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeSync } from "node:fs";
1
+ import { D as materializeBuild, E as installedPackageRootFromEntry, G as win32PrivateFileStatus, I as parseProcessStat, L as readKernelProcess, M as scrubProgramResumeEnvironment, R as readProcessStarttime, y as LocalScopeError, z as sameKernelProcess } from "./daemon-launcher-DxIgjBHW.mjs";
2
+ import { closeSync, constants, fchmodSync, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, statSync, unlinkSync, writeSync } from "node:fs";
3
3
  import { userInfo } from "node:os";
4
- import { basename, dirname, isAbsolute, join } from "node:path";
5
- import { createHash, randomUUID } from "node:crypto";
4
+ import { dirname, isAbsolute, join } from "node:path";
5
+ import { randomUUID } from "node:crypto";
6
6
  import { spawn, spawnSync } from "node:child_process";
7
7
  import { pathToFileURL } from "node:url";
8
8
  //#region src/app/remote-process/local-host-launchd.ts
@@ -23,8 +23,10 @@ import { pathToFileURL } from "node:url";
23
23
  * invoked with a fixed argument array through `/bin/launchctl` (no shell).
24
24
  *
25
25
  * The default job does NOT start at login and is NOT restarted automatically:
26
- * `RunAtLoad=false` and `KeepAlive=false` are deliberate. The product does not
27
- * rewrite user runtime directives in an existing same-owner plist.
26
+ * `RunAtLoad=false` and `KeepAlive=false` are deliberate. A FRESH definition
27
+ * created with the explicit `daemon install --autostart` opt-in instead asks
28
+ * launchd to start the Host at login and to restart it after an abnormal exit;
29
+ * the product never rewrites those keys in an existing same-owner plist.
28
30
  *
29
31
  * @module app/remote-process/local-host-launchd
30
32
  */
@@ -72,7 +74,8 @@ function encodePlistValue(value, label) {
72
74
  return value.replace(/&/gu, "&amp;").replace(/</gu, "&lt;").replace(/>/gu, "&gt;").replace(/"/gu, "&quot;").replace(/'/gu, "&apos;");
73
75
  }
74
76
  /** Render the complete, fixed LaunchAgent plist for one installed Host. */
75
- function renderLaunchdPlist(facts) {
77
+ function renderLaunchdPlist(facts, options = {}) {
78
+ const autostart = options.autostart === true;
76
79
  const label = buildLaunchdLabel(facts.scopeId);
77
80
  const logs = launchdLogPaths(facts.scopeDir);
78
81
  return [
@@ -90,9 +93,14 @@ function renderLaunchdPlist(facts) {
90
93
  " <key>WorkingDirectory</key>",
91
94
  ` <string>${encodePlistValue(facts.profileRealpath, "WorkingDirectory")}</string>`,
92
95
  " <key>RunAtLoad</key>",
93
- " <false/>",
96
+ ...autostart ? [" <true/>"] : [" <false/>"],
94
97
  " <key>KeepAlive</key>",
95
- " <false/>",
98
+ ...autostart ? [
99
+ " <dict>",
100
+ " <key>SuccessfulExit</key>",
101
+ " <false/>",
102
+ " </dict>"
103
+ ] : [" <false/>"],
96
104
  " <key>StandardOutPath</key>",
97
105
  ` <string>${encodePlistValue(logs.stdout, "StandardOutPath")}</string>`,
98
106
  " <key>StandardErrorPath</key>",
@@ -112,10 +120,6 @@ function renderLaunchdPlist(facts) {
112
120
  ` <string>${encodePlistValue(LAUNCHD_OWNER_MARKER, "owner marker")}</string>`,
113
121
  " <key>X-DshPiTuiScopeId</key>",
114
122
  ` <string>${encodePlistValue(facts.scopeId, "scope id")}</string>`,
115
- " <key>X-DshPiTuiProfileIdentity</key>",
116
- ` <string>${encodePlistValue(facts.profileIdentity, "profile identity")}</string>`,
117
- " <key>X-DshPiTuiInstallBuild</key>",
118
- ` <string>${encodePlistValue(facts.buildId, "install build")}</string>`,
119
123
  "</dict>",
120
124
  "</plist>",
121
125
  ""
@@ -157,10 +161,9 @@ function requirePlistString(root, key) {
157
161
  *
158
162
  * The named path survives an official profile package upgrade (pnpm keeps the
159
163
  * lexical path while the physical payload changes), unlike a versioned store
160
- * path. The caller uses it ONLY when creating a FRESH plist or migrating a
161
- * proven old generated entry; every other command keeps validating the real
162
- * installed entry through `collectUnitFacts()`. The path must resolve to the
163
- * very same physical file the official facts named, and the nearest manifest
164
+ * path. The caller uses it ONLY when creating a FRESH plist; existing plists
165
+ * are never rewritten. The path must resolve to the very same physical file
166
+ * the official facts named, and the nearest manifest
164
167
  * above the named entry must be this installed product package — otherwise the
165
168
  * profile layout does not provide a stable entry and the operation fails closed.
166
169
  */
@@ -190,8 +193,8 @@ function resolveNamedLaunchdEntry(facts) {
190
193
  * The native plist decoder is the authority for the top-level semantics: XML
191
194
  * comments, character references, CDATA and tag whitespace all normalize to the
192
195
  * same keys/values. Only the facts that bind the job to THIS profile are
193
- * checked: the exact `Label` and the three official environment anchors
194
- * (`DSH_HOME`, `SPLIT_PROCESS_DSH_ANCHOR`, `SPLIT_PROCESS_PROFILE`). Every
196
+ * checked: the three official environment anchors (`DSH_HOME`,
197
+ * `SPLIT_PROCESS_DSH_ANCHOR`, `SPLIT_PROCESS_PROFILE`). Every
195
198
  * other runtime directive — `ProgramArguments`, `WorkingDirectory`, log
196
199
  * sinks, `RunAtLoad`, `KeepAlive`, triggers, extra environment keys and
197
200
  * comments — belongs to the user and launchd, and is executed as written; the
@@ -201,14 +204,7 @@ function assertLaunchdProfileAnchors(facts, content) {
201
204
  const reject = (reason) => {
202
205
  throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", `launchd: the profile plist has a changed profile launch anchor (${reason}); refusing to bootstrap it`);
203
206
  };
204
- const root = decodeLaunchdPlist(content);
205
- const text = (key) => {
206
- const value = root[key];
207
- if (typeof value !== "string") return reject(key);
208
- return value;
209
- };
210
- if (text("Label") !== buildLaunchdLabel(facts.scopeId)) reject("Label");
211
- const environment = root.EnvironmentVariables;
207
+ const environment = decodeLaunchdPlist(content).EnvironmentVariables;
212
208
  if (environment === null || typeof environment !== "object" || Array.isArray(environment)) reject("EnvironmentVariables");
213
209
  const env = environment;
214
210
  const expectedEnvironment = {
@@ -218,16 +214,12 @@ function assertLaunchdProfileAnchors(facts, content) {
218
214
  };
219
215
  for (const [key, value] of Object.entries(expectedEnvironment)) if (env[key] !== value) reject(`EnvironmentVariables.${key}`);
220
216
  }
221
- /** The installed plist metadata of one owned unit (native top-level values). */
217
+ /** Verify the native top-level identity of one owned LaunchAgent. */
222
218
  function inspectLaunchdIdentity(content, facts, label) {
223
219
  const root = decodeLaunchdPlist(content);
224
220
  if (requirePlistString(root, "Label") !== label) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the plist Label is not this profile scope");
225
221
  if (requirePlistString(root, "X-DshPiTuiOwner") !== LAUNCHD_OWNER_MARKER) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the plist is not owned by this product");
226
222
  if (requirePlistString(root, "X-DshPiTuiScopeId") !== facts.scopeId) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the plist belongs to another profile scope");
227
- if (requirePlistString(root, "X-DshPiTuiProfileIdentity") !== facts.profileIdentity) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the plist belongs to another canonical profile");
228
- const installBuild = requirePlistString(root, "X-DshPiTuiInstallBuild");
229
- if (!/^[0-9a-f]{64}$/u.test(installBuild)) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the plist has no valid install build identity");
230
- return installBuild;
231
223
  }
232
224
  /** Resolve and prove the OS account home without trusting `$HOME`/`DSH_HOME`. */
233
225
  function resolveAccountHome(deps) {
@@ -357,20 +349,20 @@ function inspectOwnedLaunchdUnit(facts, deps = {}) {
357
349
  }
358
350
  if (!exists) return { kind: "none" };
359
351
  const file = readLaunchdFileIdentity(filePath);
352
+ inspectLaunchdIdentity(file.content, facts, label);
360
353
  return {
361
354
  kind: "owned",
362
355
  unit: {
363
356
  label,
364
357
  filePath,
365
- installBuild: inspectLaunchdIdentity(file.content, facts, label),
366
358
  ...file
367
359
  }
368
360
  };
369
361
  }
370
362
  /** Re-prove one owned plist's captured file identity before a mutation. */
371
- function assertLaunchdFileIdentity(unit, facts, deps) {
372
- const inspected = inspectOwnedLaunchdUnit(facts, deps);
373
- if (inspected.kind !== "owned" || inspected.unit.filePath !== unit.filePath || inspected.unit.resolvedPath !== unit.resolvedPath || inspected.unit.pathDevice !== unit.pathDevice || inspected.unit.pathInode !== unit.pathInode || inspected.unit.device !== unit.device || inspected.unit.inode !== unit.inode || inspected.unit.content !== unit.content) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the profile plist changed during the transition");
363
+ function assertLaunchdFileIdentity(unit) {
364
+ const current = readLaunchdFileIdentity(unit.filePath);
365
+ if (current.resolvedPath !== unit.resolvedPath || current.pathDevice !== unit.pathDevice || current.pathInode !== unit.pathInode || current.device !== unit.device || current.inode !== unit.inode || current.content !== unit.content) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the profile plist changed during the transition");
374
366
  }
375
367
  /**
376
368
  * Run exactly one fixed `launchctl` invocation: `shell: false`, an absolute
@@ -390,6 +382,8 @@ function runLaunchctl(args, options = {}) {
390
382
  };
391
383
  let child;
392
384
  try {
385
+ const env = { ...process.env };
386
+ scrubProgramResumeEnvironment(env);
393
387
  child = spawn(LAUNCHCTL, [...args], {
394
388
  shell: false,
395
389
  stdio: options.discardStdout === true ? [
@@ -401,7 +395,7 @@ function runLaunchctl(args, options = {}) {
401
395
  "pipe",
402
396
  "pipe"
403
397
  ],
404
- env: process.env
398
+ env
405
399
  });
406
400
  } catch (error) {
407
401
  settle({
@@ -478,25 +472,9 @@ function parseLaunchctlPrint(stdout) {
478
472
  const type = readLaunchctlScalar(lines, "type");
479
473
  const path = readLaunchctlScalar(lines, "path");
480
474
  const state = readLaunchctlScalar(lines, "state");
481
- const program = readLaunchctlScalar(lines, "program");
482
- const workingDirectory = readLaunchctlScalar(lines, "working directory");
483
- const stdoutPath = readLaunchctlScalar(lines, "stdout path");
484
- const stderrPath = readLaunchctlScalar(lines, "stderr path");
485
- const argumentLines = readLaunchctlBlock(lines, "arguments");
486
475
  const environmentLines = readLaunchctlBlock(lines, "environment");
487
- if (type === void 0 || path === void 0 || state === void 0 || program === void 0 || argumentLines === void 0 || environmentLines === void 0) return void 0;
488
- if (type !== "LaunchAgent" || !path.startsWith("/") || !program.startsWith("/")) return void 0;
489
- for (const optional of [
490
- workingDirectory,
491
- stdoutPath,
492
- stderrPath
493
- ]) if (optional !== void 0 && !optional.startsWith("/")) return void 0;
494
- const argumentsList = [];
495
- for (const line of argumentLines) {
496
- if (line === "") return void 0;
497
- argumentsList.push(line);
498
- }
499
- if (argumentsList.length === 0) return void 0;
476
+ if (type === void 0 || path === void 0 || state === void 0 || state === "" || environmentLines === void 0) return void 0;
477
+ if (type !== "LaunchAgent" || !path.startsWith("/")) return void 0;
500
478
  const environment = {};
501
479
  for (const line of environmentLines) {
502
480
  const separator = line.indexOf(" => ");
@@ -517,11 +495,6 @@ function parseLaunchctlPrint(stdout) {
517
495
  type,
518
496
  path,
519
497
  state,
520
- program,
521
- arguments: argumentsList,
522
- ...workingDirectory === void 0 ? {} : { workingDirectory },
523
- ...stdoutPath === void 0 ? {} : { stdoutPath },
524
- ...stderrPath === void 0 ? {} : { stderrPath },
525
498
  environment,
526
499
  ...pid === void 0 ? {} : { pid }
527
500
  };
@@ -713,9 +686,12 @@ function rollbackNewLaunchdFile(installed, error) {
713
686
  * job source, then writes the plist atomically. A job loaded from our target
714
687
  * path with no owned file is an unprovable source and is refused rather than
715
688
  * conflated with a new file. It never bootstraps, kickstarts, enables, stops or
716
- * restarts a job and never creates the profile runtime scope.
689
+ * restarts a job and creates no profile runtime scope for a plain install; only
690
+ * a FRESH definition requested with `autostart` prepares the private scope
691
+ * (through the caller's fresh facts supplier) and the default log sinks before
692
+ * the plist is published.
717
693
  */
718
- async function installLaunchdUnit(facts, deps = {}) {
694
+ async function installLaunchdUnit(facts, deps = {}, strictFacts, options = {}) {
719
695
  const accountHome = resolveAccountHome(deps);
720
696
  const label = buildLaunchdLabel(facts.scopeId);
721
697
  await assertLaunchdDomain(deps);
@@ -741,13 +717,17 @@ async function installLaunchdUnit(facts, deps = {}) {
741
717
  filePath: existing.unit.filePath,
742
718
  created: false
743
719
  };
720
+ const full = "nodePath" in facts && "hostEntryPath" in facts ? facts : strictFacts?.();
721
+ if (full === void 0) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: a fresh plist requires the current Node and Host entry facts");
722
+ const content = renderLaunchdPlist({
723
+ ...full,
724
+ hostEntryPath: resolveNamedLaunchdEntry(full)
725
+ }, options);
726
+ if (options.autostart === true) ensureLaunchdLogFiles(full);
744
727
  const installed = installLaunchdFile({
745
728
  dir,
746
729
  label,
747
- content: renderLaunchdPlist({
748
- ...facts,
749
- hostEntryPath: resolveNamedLaunchdEntry(facts)
750
- })
730
+ content
751
731
  });
752
732
  try {
753
733
  const verified = (deps.verifyInstalledUnit ?? ((current) => inspectOwnedLaunchdUnit(current, deps)))(facts);
@@ -769,13 +749,27 @@ async function kickstartLaunchdJob(unit, deps) {
769
749
  if (result.kind !== "exited" || result.code !== 0) throw launchctlFailure(result, "kickstart");
770
750
  }
771
751
  /**
752
+ * Does one loaded observation already satisfy a start REQUEST?
753
+ *
754
+ * A real `pid` or launchd's own `spawn scheduled` transition means the manager
755
+ * has already accepted the launch. Neither is Host readiness — the caller's
756
+ * authenticated wait owns that verdict — so this only prevents a second
757
+ * destructive transition.
758
+ */
759
+ function launchdStartRequested(service) {
760
+ return service.pid !== void 0 || service.state === "spawn scheduled";
761
+ }
762
+ /**
772
763
  * Start the installed job through launchd only: prove the captured file
773
764
  * identity and the profile launch anchors, inspect the current service,
774
765
  * refuse a foreign loaded definition, reload a verified IDLE loaded job from
775
766
  * the current on-disk user plist (launchd's `kickstart` reuses the cached
776
767
  * bootstrap definition, which may predate a user edit), `bootstrap` exactly
777
- * once when the job is not loaded, then `kickstart` exactly once when no
778
- * process is running. The USER-OWNED definition is executed as written:
768
+ * once when the job is not loaded, then `kickstart` exactly once only when the
769
+ * job is still provably idle. A real PID or launchd's own `spawn scheduled`
770
+ * transition is already an accepted start request: the caller waits for the
771
+ * authenticated Host instead of mutating the job again. The USER-OWNED
772
+ * definition is executed as written:
779
773
  * `RunAtLoad`, `KeepAlive`, custom arguments, working directory, triggers and
780
774
  * extra environment keys are legal launchd configuration and are not judged
781
775
  * here; the caller proves the resulting Host through the official
@@ -784,19 +778,17 @@ async function kickstartLaunchdJob(unit, deps) {
784
778
  */
785
779
  async function startLaunchdService(facts, unit, deps = {}) {
786
780
  const uid = effectiveUid(deps);
787
- assertLaunchdFileIdentity(unit, facts, deps);
788
781
  assertLaunchdProfileAnchors(facts, unit.content);
789
782
  let observed = await inspectLaunchdService(unit, deps);
790
783
  if (observed.kind === "unknown") throw new LocalScopeError("HOST_MANAGER_START_FAILED", "launchd: the loaded job state is not recognizable; refusing to start");
791
784
  if (observed.kind === "loaded") {
792
785
  if (!launchdServiceMatches(facts, unit, observed.service)) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the loaded job does not match this profile plist; run daemon uninstall before reinstalling");
793
- if (observed.service.pid !== void 0) return;
786
+ if (launchdStartRequested(observed.service)) return;
794
787
  if (observed.service.state !== "not running") throw new LocalScopeError("HOST_MANAGER_START_FAILED", "launchd: the loaded job is in an unconfirmed state; refusing to start");
795
788
  await stopLaunchdService(facts, unit, deps);
796
- if ((await inspectLaunchdService(unit, deps)).kind !== "not-loaded") throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the idle job could not be confirmed unloaded before the reload");
797
789
  }
798
790
  ensureLaunchdLogFiles(facts);
799
- assertLaunchdFileIdentity(unit, facts, deps);
791
+ assertLaunchdFileIdentity(unit);
800
792
  const bootstrap = await (deps.launchctl ?? runLaunchctl)([
801
793
  "bootstrap",
802
794
  `gui/${String(uid)}`,
@@ -805,15 +797,17 @@ async function startLaunchdService(facts, unit, deps = {}) {
805
797
  if (bootstrap.kind !== "exited" || bootstrap.code !== 0) {
806
798
  const raced = await inspectLaunchdService(unit, deps);
807
799
  if (raced.kind !== "loaded" || !launchdServiceMatches(facts, unit, raced.service)) throw launchctlFailure(bootstrap, "bootstrap");
808
- if (raced.service.pid !== void 0) return;
809
- assertLaunchdFileIdentity(unit, facts, deps);
800
+ if (launchdStartRequested(raced.service)) return;
801
+ if (raced.service.state !== "not running") throw new LocalScopeError("HOST_MANAGER_START_FAILED", "launchd: the bootstrapped job is in an unconfirmed state; refusing to start");
802
+ assertLaunchdFileIdentity(unit);
810
803
  await kickstartLaunchdJob(unit, deps);
811
804
  return;
812
805
  }
813
806
  observed = await inspectLaunchdService(unit, deps);
814
807
  if (observed.kind !== "loaded" || !launchdServiceMatches(facts, unit, observed.service)) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the bootstrapped job is not this profile plist");
815
- if (observed.service.pid !== void 0) return;
816
- assertLaunchdFileIdentity(unit, facts, deps);
808
+ if (launchdStartRequested(observed.service)) return;
809
+ if (observed.service.state !== "not running") throw new LocalScopeError("HOST_MANAGER_START_FAILED", "launchd: the bootstrapped job is in an unconfirmed state; refusing to start");
810
+ assertLaunchdFileIdentity(unit);
817
811
  await kickstartLaunchdJob(unit, deps);
818
812
  }
819
813
  /** Bounded wait until a verified label is genuinely no longer loaded. */
@@ -834,7 +828,6 @@ async function waitForLaunchdJobRemoved(unit, deps) {
834
828
  * match the current profile plist is never booted out.
835
829
  */
836
830
  async function stopLaunchdService(facts, unit, deps = {}, expectedPid) {
837
- assertLaunchdFileIdentity(unit, facts, deps);
838
831
  const observed = await inspectLaunchdService(unit, deps);
839
832
  if (observed.kind === "not-loaded") return { stopped: false };
840
833
  if (observed.kind === "unknown") throw new LocalScopeError("HOST_MANAGER_START_FAILED", "launchd: the loaded job state is not recognizable; refusing to stop");
@@ -848,7 +841,7 @@ async function stopLaunchdService(facts, unit, deps = {}, expectedPid) {
848
841
  if (observed.service.state !== "not running") throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", `launchd: the loaded job is in an unconfirmed state (${observed.service.state === "" ? "unknown" : observed.service.state}); refusing to stop`);
849
842
  }
850
843
  const stopped = observed.service.pid !== void 0;
851
- assertLaunchdFileIdentity(unit, facts, deps);
844
+ assertLaunchdFileIdentity(unit);
852
845
  const uid = effectiveUid(deps);
853
846
  const result = await (deps.launchctl ?? runLaunchctl)(["bootout", `gui/${String(uid)}/${unit.label}`]);
854
847
  if (result.kind !== "exited" || result.code !== 0 && result.code !== 3) throw launchctlFailure(result, "bootout");
@@ -861,234 +854,14 @@ async function stopLaunchdService(facts, unit, deps = {}, expectedPid) {
861
854
  * credentials, `host.log` and the launchd private logs are never removed.
862
855
  */
863
856
  async function uninstallLaunchdUnit(facts, unit, deps = {}, expectedPid) {
864
- assertLaunchdFileIdentity(unit, facts, deps);
865
- const observed = await inspectLaunchdService(unit, deps);
866
- if (observed.kind === "unknown") throw new LocalScopeError("HOST_MANAGER_START_FAILED", "launchd: the loaded job state is not recognizable; refusing to uninstall");
867
- if (observed.kind === "loaded") {
868
- if (!launchdServiceMatches(facts, unit, observed.service)) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the loaded job does not match this profile plist; refusing to remove the job");
869
- await stopLaunchdService(facts, unit, deps, expectedPid);
870
- }
871
- assertLaunchdFileIdentity(unit, facts, deps);
857
+ await stopLaunchdService(facts, unit, deps, expectedPid);
858
+ assertLaunchdFileIdentity(unit);
872
859
  try {
873
860
  unlinkSync(unit.filePath);
874
861
  } catch (error) {
875
862
  if (error.code === "ENOENT") throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the profile plist vanished during uninstall");
876
863
  throw new LocalScopeError("HOST_MANAGER_START_FAILED", "launchd: the profile plist could not be removed", error);
877
864
  }
878
- if (inspectOwnedLaunchdUnit(facts, deps).kind !== "none") throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the profile plist could not be confirmed removed");
879
- }
880
- /** The exact `ProgramArguments` block this product's renderer has always written. */
881
- const GENERATED_PROGRAM_ARGUMENTS_SPAN = {
882
- head: " <key>ProgramArguments</key>\n <array>\n <string>",
883
- tail: "</string>\n </array>\n"
884
- };
885
- /** The exact `X-DshPiTuiInstallBuild` block this product's renderer writes. */
886
- const GENERATED_INSTALL_BUILD_SPAN = {
887
- head: " <key>X-DshPiTuiInstallBuild</key>\n <string>",
888
- tail: "</string>\n"
889
- };
890
- /** The stable product entry suffix shared by every legal package layout. */
891
- const PRODUCT_ENTRY_SUFFIX = "/node_modules/@xmoon76/dsh-pi-tui/dist/local-host.mjs";
892
- /**
893
- * Prove one old `ProgramArguments[1]` was generated by THIS Profile's install.
894
- *
895
- * A matching package name or a pnpm directory spelling only proves a layout,
896
- * not generation provenance. Provenance requires the old package to live under
897
- * THIS Profile's own `node_modules` layout (the real DSH install layout), to be
898
- * readable, to be this product, and to have a computed build identity equal to
899
- * the plist's recorded `X-DshPiTuiInstallBuild`. A pruned old package or any
900
- * user pin outside this Profile (external store, another Profile, global
901
- * install) cannot prove provenance and is preserved as user-managed.
902
- */
903
- function proveGeneratedEntryForProfile(entryValue, facts, recordedBuild) {
904
- if (!entryValue.startsWith(`${facts.profileRealpath}/node_modules/`)) return false;
905
- let packageRoot;
906
- let manifest;
907
- try {
908
- packageRoot = realpathSync(dirname(dirname(entryValue)));
909
- manifest = JSON.parse(readFileSync(join(packageRoot, "package.json"), "utf8"));
910
- } catch {
911
- return false;
912
- }
913
- if (manifest === null || typeof manifest !== "object" || manifest.name !== "@xmoon76/dsh-pi-tui") return false;
914
- try {
915
- return computeBuildId(packageRoot, readInstalledDshVersion(facts.dshAnchor)) === recordedBuild;
916
- } catch {
917
- return false;
918
- }
919
- }
920
- /**
921
- * Locate the product's EXACT generated `ProgramArguments` block: precisely two
922
- * `<string>` children whose first value is the renderer's node executable form
923
- * and whose second value is an accepted product Host entry path. The lexical
924
- * span must equal the renderer's exact bytes; any reordering, binary plist,
925
- * wrapper, extra argument or another program is not our generated block and
926
- * returns `undefined`.
927
- */
928
- function locateGeneratedProgramArguments(content, facts) {
929
- const decoded = decodeLaunchdPlist(content);
930
- const argv = decoded.ProgramArguments;
931
- if (!Array.isArray(argv) || argv.length !== 2 || argv.some((value) => typeof value !== "string")) return void 0;
932
- const [nodeValue, entryValue] = argv;
933
- if (nodeValue !== facts.nodePath) return void 0;
934
- if (!entryValue.endsWith(PRODUCT_ENTRY_SUFFIX)) return void 0;
935
- const recordedBuild = decoded["X-DshPiTuiInstallBuild"];
936
- if (typeof recordedBuild !== "string" || !/^[0-9a-f]{64}$/u.test(recordedBuild)) return void 0;
937
- const entryStart = content.indexOf(GENERATED_PROGRAM_ARGUMENTS_SPAN.head);
938
- if (entryStart < 0) return void 0;
939
- const valueStart = entryStart + GENERATED_PROGRAM_ARGUMENTS_SPAN.head.length;
940
- const firstTail = content.indexOf("</string>\n <string>", valueStart);
941
- if (firstTail < 0) return void 0;
942
- const secondStart = firstTail + 22;
943
- const tailStart = content.indexOf(GENERATED_PROGRAM_ARGUMENTS_SPAN.tail, secondStart);
944
- if (tailStart < 0) return void 0;
945
- const end = tailStart + GENERATED_PROGRAM_ARGUMENTS_SPAN.tail.length;
946
- if (content.slice(entryStart, end) !== ` <key>ProgramArguments</key>\n <array>\n <string>${nodeValue}</string>\n <string>${entryValue}</string>\n </array>\n`) return void 0;
947
- if (content.indexOf(" <key>ProgramArguments</key>", entryStart + 1) >= 0) return void 0;
948
- return {
949
- oldEntry: entryValue,
950
- recordedBuild,
951
- start: entryStart,
952
- end
953
- };
954
- }
955
- /** Locate the product's exact generated `X-DshPiTuiInstallBuild` block. */
956
- function locateGeneratedInstallBuild(content) {
957
- const start = content.indexOf(GENERATED_INSTALL_BUILD_SPAN.head);
958
- if (start < 0) return void 0;
959
- const valueStart = start + GENERATED_INSTALL_BUILD_SPAN.head.length;
960
- const tailStart = content.indexOf(GENERATED_INSTALL_BUILD_SPAN.tail, valueStart);
961
- if (tailStart < 0) return void 0;
962
- const end = tailStart + GENERATED_INSTALL_BUILD_SPAN.tail.length;
963
- const block = content.slice(start, end);
964
- const value = block.slice(GENERATED_INSTALL_BUILD_SPAN.head.length, block.length - GENERATED_INSTALL_BUILD_SPAN.tail.length);
965
- if (!/^[0-9a-f]{64}$/u.test(value)) return void 0;
966
- if (content.indexOf(GENERATED_INSTALL_BUILD_SPAN.head, start + 1) >= 0) return void 0;
967
- return {
968
- start,
969
- end
970
- };
971
- }
972
- /**
973
- * The ONE bounded migration of an old PRODUCT-GENERATED plist fragment to the
974
- * current install. `inspect` is read-only and may run before a stop; `apply`
975
- * performs the atomic in-place replacement and is legal ONLY after the old
976
- * Host kernel identity is proven gone and the loaded job is proven booted out.
977
- *
978
- * The ONLY bytes ever modified are a PROVEN generated `ProgramArguments[1]`
979
- * (old installed entry -> the current stable named entry) and, when the
980
- * arguments actually migrate, the adjacent generated `X-DshPiTuiInstallBuild`
981
- * value. Provenance requires the old package to live under THIS Profile's own
982
- * `node_modules` layout and the recorded install-build identity to equal its
983
- * computed build identity. A user-customized argv, an external pin to another
984
- * Profile/store/build, a pruned old package,
985
- * a restructured XML, a binary plist or any other unrecognized shape is
986
- * preserved byte-for-byte and reported `user-managed`: the plist is then
987
- * executed exactly as the user wrote it and the resulting Host is authenticated
988
- * (or truthfully reported `other-build`).
989
- */
990
- function prepareOwnedLaunchdForCurrentInstall(facts, unit, deps, mode) {
991
- assertLaunchdFileIdentity(unit, facts, deps);
992
- assertLaunchdProfileAnchors(facts, unit.content);
993
- const generated = locateGeneratedProgramArguments(unit.content, facts);
994
- if (generated === void 0) return { plan: {
995
- kind: "no-op",
996
- reason: "user-managed"
997
- } };
998
- const namedEntry = resolveNamedLaunchdEntry(facts);
999
- if (generated.oldEntry === namedEntry) return { plan: {
1000
- kind: "no-op",
1001
- reason: "current"
1002
- } };
1003
- if (!proveGeneratedEntryForProfile(generated.oldEntry, facts, generated.recordedBuild)) return { plan: {
1004
- kind: "no-op",
1005
- reason: "user-managed"
1006
- } };
1007
- const plan = {
1008
- kind: "migrate",
1009
- namedEntry
1010
- };
1011
- if (mode === "inspect") return { plan };
1012
- const current = inspectOwnedLaunchdUnit(facts, deps);
1013
- if (current.kind !== "owned" || current.unit.filePath !== unit.filePath || current.unit.content !== unit.content || current.unit.device !== unit.device || current.unit.inode !== unit.inode) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the profile plist changed before the migration was applied");
1014
- const reGenerated = locateGeneratedProgramArguments(current.unit.content, facts);
1015
- if (reGenerated === void 0 || reGenerated.oldEntry !== generated.oldEntry) return { plan: {
1016
- kind: "no-op",
1017
- reason: "user-managed"
1018
- } };
1019
- let next = spliceString(current.unit.content, generated.start, generated.end, [
1020
- " <key>ProgramArguments</key>\n <array>\n <string>",
1021
- encodePlistValue(facts.nodePath, "node path"),
1022
- "</string>\n <string>",
1023
- encodePlistValue(namedEntry, "Host entry path"),
1024
- "</string>\n </array>\n"
1025
- ].join(""));
1026
- const buildSpan = locateGeneratedInstallBuild(next);
1027
- if (buildSpan !== void 0) next = spliceString(next, buildSpan.start, buildSpan.end, [
1028
- " <key>X-DshPiTuiInstallBuild</key>\n <string>",
1029
- encodePlistValue(facts.buildId, "install build"),
1030
- "</string>\n"
1031
- ].join(""));
1032
- decodeLaunchdPlist(next);
1033
- const written = replacePlistAtomic(current.unit.filePath, next);
1034
- const verified = inspectOwnedLaunchdUnit(facts, deps);
1035
- if (verified.kind !== "owned" || verified.unit.content !== written) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the migrated plist could not be confirmed after the replacement");
1036
- const argv = decodeLaunchdPlist(verified.unit.content).ProgramArguments;
1037
- if (!Array.isArray(argv) || argv.length !== 2 || argv[1] !== namedEntry) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the migrated plist does not decode to the stable named entry");
1038
- return {
1039
- plan,
1040
- unit: verified.unit
1041
- };
1042
- }
1043
- /** Replace an exact byte span of one string. */
1044
- function spliceString(content, start, end, replacement) {
1045
- return content.slice(0, start) + replacement + content.slice(end);
1046
- }
1047
- /**
1048
- * Atomically replace one owned plist file in its own directory with the
1049
- * original file mode, through a same-directory temp file, native `plutil`
1050
- * validation, `fsync` and `rename`. The target must still be a regular
1051
- * non-symlink file; a replaced or vanished target is a hard refusal (never a
1052
- * blind overwrite).
1053
- */
1054
- function replacePlistAtomic(filePath, content) {
1055
- let originalMode;
1056
- try {
1057
- const info = lstatSync(filePath);
1058
- if (!info.isFile() || info.isSymbolicLink()) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the profile plist is not a regular file for an in-place migration");
1059
- originalMode = info.mode & 511;
1060
- } catch (error) {
1061
- if (error instanceof LocalScopeError) throw error;
1062
- throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the profile plist could not be re-read before the migration", error);
1063
- }
1064
- const tempPath = join(dirname(filePath), `.${basename(filePath)}.${String(process.pid)}.${randomUUID()}.tmp`);
1065
- let fd;
1066
- try {
1067
- fd = openSync(tempPath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, originalMode);
1068
- fchmodSync(fd, originalMode);
1069
- const buffer = Buffer.from(content, "utf8");
1070
- let offset = 0;
1071
- while (offset < buffer.length) offset += writeSync(fd, buffer, offset, buffer.length - offset);
1072
- fsyncSync(fd);
1073
- closeSync(fd);
1074
- fd = void 0;
1075
- const lint = spawnSync("/usr/bin/plutil", [
1076
- "-lint",
1077
- "-s",
1078
- "--",
1079
- tempPath
1080
- ], { timeout: 5e3 });
1081
- if (lint.error !== void 0 || lint.status !== 0) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the migrated plist failed the native lint before publication");
1082
- renameSync(tempPath, filePath);
1083
- } catch (error) {
1084
- if (fd !== void 0) closeSync(fd);
1085
- try {
1086
- unlinkSync(tempPath);
1087
- } catch {}
1088
- if (error instanceof LocalScopeError) throw error;
1089
- throw new LocalScopeError("HOST_MANAGER_START_FAILED", "launchd: the migrated plist could not be installed atomically", error);
1090
- }
1091
- return content;
1092
865
  }
1093
866
  //#endregion
1094
867
  //#region src/app/remote-process/local-host-manager.ts
@@ -1103,11 +876,8 @@ function replacePlistAtomic(filePath, content) {
1103
876
  * start`. On macOS no plist keeps the same detached path; an owned plist means
1104
877
  * one verified launchd bootstrap/kickstart through the Darwin adapter. The
1105
878
  * Linux `installProfileHostUnit()` and macOS `installLaunchdUnit()` are the ONLY
1106
- * paths that create a service definition; the ONE bounded exception is
1107
- * `prepareOwnedProfileUnitForCurrentInstall()`, which an EXPLICIT CLI
1108
- * `start`/`restart` uses to migrate a recognized pre-existing generated unit
1109
- * field pair to the stable Profile entry. None of them starts, stops, enables,
1110
- * auto-restarts or migrates a Host.
879
+ * paths that create a service definition. They never start, stop, enable or
880
+ * auto-restart a Host, and never rewrite an existing definition.
1111
881
  *
1112
882
  * `systemctl`/`journalctl` and `/bin/launchctl` are invoked through fixed
1113
883
  * argument arrays. A missing command can only affect the explicit service-
@@ -1156,11 +926,11 @@ function selectRuntimeDir(uid) {
1156
926
  if (ambient !== void 0 && ambient !== "") return ambient;
1157
927
  }
1158
928
  function systemctlEnv(runtimeDir) {
1159
- if (runtimeDir === void 0) return { ...process.env };
1160
- return {
1161
- ...process.env,
1162
- XDG_RUNTIME_DIR: runtimeDir
1163
- };
929
+ const env = { ...process.env };
930
+ scrubProgramResumeEnvironment(env);
931
+ if (runtimeDir === void 0) return env;
932
+ env.XDG_RUNTIME_DIR = runtimeDir;
933
+ return env;
1164
934
  }
1165
935
  /**
1166
936
  * Run exactly one fixed `systemctl` invocation: `shell: false`, an absolute
@@ -1298,10 +1068,6 @@ function encodeUnitPath(value, label) {
1298
1068
  function encodeEnvironment(key, value) {
1299
1069
  return `Environment=${encodeUnitValue(`${key}=${value}`, `environment ${key}`, false)}`;
1300
1070
  }
1301
- /** The deterministic profile-identity digest stored in the unit owner metadata. */
1302
- function profileIdentityDigest(profileRealpath) {
1303
- return createHash("sha256").update(`dsh-pi-tui/profile-identity/1\0${profileRealpath}`).digest("hex");
1304
- }
1305
1071
  /**
1306
1072
  * Build the readable, ASCII-safe profile slug used ONLY in the unit file name.
1307
1073
  * Full scopeId ownership is always validated separately; the slug never grants
@@ -1327,8 +1093,6 @@ function renderUnitContent(facts) {
1327
1093
  "Description=dsh-pi-tui local Host (profile-scoped)",
1328
1094
  `X-DshPiTuiOwner=${UNIT_OWNER_MARKER}`,
1329
1095
  `X-DshPiTuiScopeId=${facts.scopeId}`,
1330
- `X-DshPiTuiProfileIdentity=${profileIdentityDigest(facts.profileRealpath)}`,
1331
- `X-DshPiTuiInstallBuild=${facts.buildId}`,
1332
1096
  "StartLimitIntervalSec=60s",
1333
1097
  "StartLimitBurst=3",
1334
1098
  "",
@@ -1345,6 +1109,9 @@ function renderUnitContent(facts) {
1345
1109
  "KillMode=control-group",
1346
1110
  "StandardOutput=journal",
1347
1111
  "StandardError=journal",
1112
+ "",
1113
+ "[Install]",
1114
+ "WantedBy=default.target",
1348
1115
  ""
1349
1116
  ].join("\n");
1350
1117
  }
@@ -1410,13 +1177,9 @@ function inspectTrustedDshAnchor(path) {
1410
1177
  if (!lstatSync(real).isFile()) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the DSH anchor must be a regular file");
1411
1178
  return real;
1412
1179
  }
1413
- /** Collect and validate the exact installed facts one service definition is rendered from. */
1414
- function collectUnitFacts(options) {
1415
- const nodePath = inspectTrustedExecutable(process.execPath, "node executable");
1416
- if (!isAbsolute(options.hostEntryPath)) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the Host entry path must be absolute");
1417
- inspectOwnedRegular(options.hostEntryPath, "Host entry");
1418
- assertEntrySelfLocation(options.hostEntryPath, "HOST_MANAGER_UNIT_CONFLICT", "Host entry");
1419
- const dshAnchor = inspectTrustedDshAnchor(options.dshAnchor);
1180
+ /** Validate the DSH install anchor and its exact runtime version once. */
1181
+ function readVerifiedDshAnchor(path, dshVersion) {
1182
+ const dshAnchor = inspectTrustedDshAnchor(path);
1420
1183
  let manifest;
1421
1184
  try {
1422
1185
  manifest = JSON.parse(readFileSync(dshAnchor, "utf8"));
@@ -1424,13 +1187,21 @@ function collectUnitFacts(options) {
1424
1187
  throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the DSH anchor manifest is unreadable", error);
1425
1188
  }
1426
1189
  if (manifest === null || typeof manifest !== "object" || manifest.name !== "@deepseek-ai/dsh") throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the DSH anchor is not @deepseek-ai/dsh");
1427
- if (manifest.version !== options.scope.dshVersion) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the DSH anchor version does not match the installed runtime pin");
1190
+ if (manifest.version !== dshVersion) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the DSH anchor version does not match the installed runtime pin");
1191
+ return dshAnchor;
1192
+ }
1193
+ /** Collect and validate the exact installed facts one service definition is rendered from. */
1194
+ function collectUnitFacts(options) {
1195
+ const nodePath = inspectTrustedExecutable(process.execPath, "node executable");
1196
+ if (!isAbsolute(options.hostEntryPath)) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the Host entry path must be absolute");
1197
+ inspectOwnedRegular(options.hostEntryPath, "Host entry");
1198
+ assertEntrySelfLocation(options.hostEntryPath, "HOST_MANAGER_UNIT_CONFLICT", "Host entry");
1199
+ const dshAnchor = readVerifiedDshAnchor(options.dshAnchor, options.scope.dshVersion);
1428
1200
  return {
1429
1201
  dshHome: options.scope.dshHome,
1430
1202
  profileRealpath: options.scope.profileRealpath,
1431
1203
  profile: options.profile,
1432
1204
  scopeId: options.scope.scopeId,
1433
- buildId: options.scope.buildId,
1434
1205
  nodePath,
1435
1206
  hostEntryPath: options.hostEntryPath,
1436
1207
  dshAnchor
@@ -1696,15 +1467,11 @@ function readUnitFileIdentity(filePath) {
1696
1467
  throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the unit configuration could not be read", error);
1697
1468
  }
1698
1469
  }
1699
- /** Runtime directives belong to the user and systemd; only metadata proves scope. */
1470
+ /** Runtime directives belong to the user and systemd; only owner and full scope prove identity. */
1700
1471
  function inspectUnitIdentity(content, scope) {
1701
1472
  const lines = content.split("\n");
1702
1473
  if (readUnitMetadata(lines, "X-DshPiTuiOwner") !== UNIT_OWNER_MARKER) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the unit is not owned by this product");
1703
1474
  if (readUnitMetadata(lines, "X-DshPiTuiScopeId") !== scope.scopeId) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the unit belongs to another profile scope");
1704
- if (readUnitMetadata(lines, "X-DshPiTuiProfileIdentity") !== profileIdentityDigest(scope.profileRealpath)) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the unit belongs to another canonical profile");
1705
- const installBuild = readUnitMetadata(lines, "X-DshPiTuiInstallBuild");
1706
- if (!/^[0-9a-f]{64}$/u.test(installBuild)) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the unit has no valid install build identity");
1707
- return installBuild;
1708
1475
  }
1709
1476
  /** Compare this operation's observation, never the generated default template. */
1710
1477
  function assertUnitFileIdentity(unit) {
@@ -1724,12 +1491,12 @@ function inspectOwnedProfileUnit(scope, profile, unitDir) {
1724
1491
  throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the profile unit path is not accessible", error);
1725
1492
  }
1726
1493
  const file = readUnitFileIdentity(filePath);
1494
+ inspectUnitIdentity(file.content, scope);
1727
1495
  return {
1728
1496
  kind: "owned",
1729
1497
  unitName,
1730
1498
  unitDir: dir,
1731
1499
  filePath,
1732
- installBuild: inspectUnitIdentity(file.content, scope),
1733
1500
  ...file
1734
1501
  };
1735
1502
  }
@@ -1800,9 +1567,7 @@ async function stopOwnedProfileUnit(unit, runtimeDir, systemctl, timeoutMs = UNI
1800
1567
  * independent Host is not unit-supervised and is never stopped by uninstall. The
1801
1568
  * caller owns the `daemon-reload` that follows.
1802
1569
  */
1803
- function uninstallOwnedProfileUnit(unit, scope, profile) {
1804
- const current = inspectOwnedProfileUnit(scope, profile, unit.unitDir);
1805
- if (current.kind !== "owned" || current.filePath !== unit.filePath || current.device !== unit.device || current.inode !== unit.inode) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the profile unit file changed during the transition");
1570
+ function uninstallOwnedProfileUnit(unit) {
1806
1571
  assertUnitFileIdentity(unit);
1807
1572
  try {
1808
1573
  unlinkSync(unit.filePath);
@@ -1812,6 +1577,23 @@ function uninstallOwnedProfileUnit(unit, scope, profile) {
1812
1577
  }
1813
1578
  }
1814
1579
  /**
1580
+ * Submit ONE native `systemctl --user enable|disable <unit>` for an already
1581
+ * verified owned profile unit. Enablement, install links and the manager's
1582
+ * reload are systemd's responsibility: this adapter never parses Install
1583
+ * directives, edits user configuration, retries or reports a Host transition.
1584
+ */
1585
+ async function setOwnedProfileUnitEnablement(unit, verb, runtimeDir, systemctl) {
1586
+ assertUnitFileIdentity(unit);
1587
+ const result = await systemctl([
1588
+ "--user",
1589
+ "--no-pager",
1590
+ "--no-ask-password",
1591
+ verb,
1592
+ unit.unitName
1593
+ ], runtimeDir);
1594
+ if (result.kind !== "exited" || result.code !== 0) throw new LocalScopeError("HOST_MANAGER_ERROR", `managed Host: systemctl could not ${verb} the unit`);
1595
+ }
1596
+ /**
1815
1597
  * Prove the manager does not already run THIS unit name from another source
1816
1598
  * before a fresh high-priority unit file may shadow it. A loaded definition
1817
1599
  * with a different FragmentPath is either a foreign service (must be refused,
@@ -1853,7 +1635,7 @@ function requireLinuxUid() {
1853
1635
  * path that writes a unit: it proves the user manager is reachable before any
1854
1636
  * write (an empty target directory is legitimately absent from `UnitPath`),
1855
1637
  * installs the rendered file atomically (never overwriting user content),
1856
- * re-verifies the same-profile metadata/build identity and reloads/verifies the
1638
+ * re-verifies the same-profile owner/scope identity and reloads/verifies the
1857
1639
  * manager's real `LoadState`/`FragmentPath`. It never starts, stops,
1858
1640
  * enables or restarts a unit and never creates a Client/Host.
1859
1641
  */
@@ -1958,195 +1740,12 @@ function rollbackFreshUnit(unit) {
1958
1740
  return error instanceof Error ? error : new Error(String(error));
1959
1741
  }
1960
1742
  }
1961
- /** Decode ONE canonical `encodeUnitValue(..., commandLine: true)` double-quoted token. */
1962
- function decodeCommandToken(text, start) {
1963
- if (text[start] !== "\"") return void 0;
1964
- let value = "";
1965
- let index = start + 1;
1966
- for (; index < text.length; index += 1) {
1967
- const character = text[index];
1968
- if (character === "\"") return {
1969
- raw: text.slice(start, index + 1),
1970
- value,
1971
- end: index + 1
1972
- };
1973
- if (character === "\\") {
1974
- const escaped = text[index + 1];
1975
- if (escaped !== "\\" && escaped !== "\"") return void 0;
1976
- value += escaped;
1977
- index += 1;
1978
- continue;
1979
- }
1980
- if (character === "%" || character === "$") {
1981
- if (text[index + 1] !== character) return void 0;
1982
- value += character;
1983
- index += 1;
1984
- continue;
1985
- }
1986
- value += character;
1987
- }
1988
- }
1989
- /**
1990
- * Recognize the ONE generated command line: exactly two canonical encoded
1991
- * tokens (absolute Node executable and a physical PiTui `local-host.mjs`). The
1992
- * historical root may already be gone; then only the recognizable published
1993
- * layout is required. A root that is still accessible must declare this exact
1994
- * package. Anything else is user configuration and returns `undefined`.
1995
- */
1996
- function parseGeneratedExecStart(value) {
1997
- const node = decodeCommandToken(value, 0);
1998
- if (node === void 0 || value[node.end] !== " ") return void 0;
1999
- const host = decodeCommandToken(value, node.end + 1);
2000
- if (host === void 0 || host.end !== value.length) return void 0;
2001
- if (!isAbsolute(node.value) || !isAbsolute(host.value)) return void 0;
2002
- if (!host.value.endsWith("/node_modules/@xmoon76/dsh-pi-tui/dist/local-host.mjs")) return void 0;
2003
- if (existsSync(host.value)) try {
2004
- installedPackageRootFromEntry(pathToFileURL(host.value).href);
2005
- } catch {
2006
- return;
2007
- }
2008
- return {
2009
- line: `ExecStart=${value}`,
2010
- nodeToken: node.raw,
2011
- hostEntryPath: host.value
2012
- };
2013
- }
2014
- /** Find the single PiTui-generated `ExecStart=` of one unit, if it is recognized. */
2015
- function inspectGeneratedExecStart(content) {
2016
- let section = "";
2017
- let found;
2018
- let count = 0;
2019
- for (const line of content.split("\n")) {
2020
- const sectionMatch = /^\[([^\]]+)\]$/u.exec(line);
2021
- if (sectionMatch !== null) {
2022
- section = sectionMatch[1];
2023
- continue;
2024
- }
2025
- if (!/^\s*ExecStart\s*=/u.test(line)) continue;
2026
- count += 1;
2027
- if (count > 1 || section !== "Service" || !line.startsWith("ExecStart=")) return void 0;
2028
- found = {
2029
- line,
2030
- value: line.slice(10)
2031
- };
2032
- }
2033
- if (found === void 0) return void 0;
2034
- return parseGeneratedExecStart(found.value);
2035
- }
2036
- /** The current user may replace this regular main unit file in place. */
2037
- function inspectMigrationWriteAdmission(unit, uid) {
2038
- let info;
2039
- try {
2040
- info = lstatSync(unit.filePath);
2041
- } catch (error) {
2042
- throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the profile unit changed during the migration plan", error);
2043
- }
2044
- if (info.isSymbolicLink()) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the profile unit is a user-managed symlink; its configuration source is never rewritten");
2045
- if (!info.isFile()) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the profile unit is not a regular file");
2046
- if (info.uid !== uid) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the profile unit is not owned by the current user");
2047
- if ((info.mode & 128) === 0) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the profile unit is not writable by the current user");
2048
- try {
2049
- accessSync(unit.unitDir, constants.W_OK);
2050
- } catch (error) {
2051
- throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the user unit directory is not writable", error);
2052
- }
2053
- return info.mode & 511;
2054
- }
2055
- /** Rewrite exactly the two generated fields; every other byte is preserved. */
2056
- function migrateGeneratedUnitContent(content, generated, namedEntry, buildId) {
2057
- const execStart = `ExecStart=${generated.nodeToken} ${encodeUnitValue(namedEntry, "Host entry path", true)}`;
2058
- let execStartReplaced = false;
2059
- let buildReplaced = false;
2060
- const migrated = content.split("\n").map((line) => {
2061
- if (line === generated.line) {
2062
- execStartReplaced = true;
2063
- return execStart;
2064
- }
2065
- if (line.startsWith("X-DshPiTuiInstallBuild=")) {
2066
- buildReplaced = true;
2067
- return `X-DshPiTuiInstallBuild=${buildId}`;
2068
- }
2069
- return line;
2070
- });
2071
- if (!execStartReplaced || !buildReplaced) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the generated unit fields are not the planned shape");
2072
- return migrated.join("\n");
2073
- }
2074
- /** Atomically replace the OWNED main unit file, preserving its original mode. */
2075
- function replaceOwnedUnitFile(unit, content, mode) {
2076
- const tempPath = join(unit.unitDir, `.${unit.unitName}.${String(process.pid)}.${randomUUID()}.tmp`);
2077
- let fd;
2078
- try {
2079
- fd = openSync(tempPath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, mode);
2080
- fchmodSync(fd, mode);
2081
- const buffer = Buffer.from(content, "utf8");
2082
- let offset = 0;
2083
- while (offset < buffer.length) offset += writeSync(fd, buffer, offset, buffer.length - offset);
2084
- fsyncSync(fd);
2085
- closeSync(fd);
2086
- fd = void 0;
2087
- assertUnitFileIdentity(unit);
2088
- renameSync(tempPath, unit.filePath);
2089
- } catch (error) {
2090
- if (fd !== void 0) closeSync(fd);
2091
- try {
2092
- unlinkSync(tempPath);
2093
- } catch {}
2094
- if (error instanceof LocalScopeError) throw error;
2095
- throw new LocalScopeError("HOST_MANAGER_START_FAILED", "managed Host: the migrated unit could not be written", error);
2096
- } finally {
2097
- try {
2098
- unlinkSync(tempPath);
2099
- } catch {}
2100
- }
2101
- }
2102
- /**
2103
- * Prepare the Profile unit for the CURRENT installed package, for the explicit
2104
- * CLI `start`/`restart` paths only. `inspect` never writes and proves whether the
2105
- * `apply` rewrite is possible before a Host is stopped; `apply` performs the one
2106
- * bounded atomic rewrite plus manager reload and re-verifies the manager source.
2107
- * A user-custom `ExecStart` and a unit already pointing at the stable entry are
2108
- * byte-preserved no-ops. There is no upgrade state, parser or manager here.
2109
- */
2110
- async function prepareOwnedProfileUnitForCurrentInstall(options, deps = {}) {
2111
- const uid = requireLinuxUid();
2112
- const unitDir = deps.unitDir !== void 0 ? deps.unitDir(uid) : inspectExistingUserUnitDir();
2113
- if (unitDir === void 0) return { kind: "none" };
2114
- const inspected = inspectOwnedProfileUnit(options.scope, options.profile, unitDir);
2115
- if (inspected.kind === "none") return { kind: "none" };
2116
- const systemctl = deps.systemctl ?? runSystemctl;
2117
- const runtimeDir = selectRuntimeDir(uid);
2118
- if ((await queryOwnedProfileUnit(inspected, runtimeDir, systemctl)).loadState === "not-found") return { kind: "not-loaded" };
2119
- const generated = inspectGeneratedExecStart(inspected.content);
2120
- if (generated === void 0) return { kind: "unchanged" };
2121
- if (generated.hostEntryPath === stableProfileHostEntry(options.scope)) return { kind: "unchanged" };
2122
- const namedEntry = resolveStableProfileHostEntry(options.scope, options.hostEntryPath);
2123
- const mode = inspectMigrationWriteAdmission(inspected, uid);
2124
- if (options.mode === "inspect") return { kind: "migration-required" };
2125
- const content = migrateGeneratedUnitContent(inspected.content, generated, namedEntry, options.scope.buildId);
2126
- assertUnitFileIdentity(inspected);
2127
- const beforeWrite = await queryOwnedProfileUnit(inspected, runtimeDir, systemctl);
2128
- if (beforeWrite.loadState === "not-found") throw new LocalScopeError("HOST_MANAGER_START_FAILED", "managed Host: the installed unit is not loaded by the manager");
2129
- if (beforeWrite.activeState !== "inactive" && beforeWrite.activeState !== "failed") throw new LocalScopeError("HOST_MANAGER_START_FAILED", "managed Host: the profile unit is not stopped; refusing to rewrite its command while it may start a Host");
2130
- replaceOwnedUnitFile(inspected, content, mode);
2131
- const reload = await systemctl([
2132
- "--user",
2133
- "--no-pager",
2134
- "--no-ask-password",
2135
- "daemon-reload"
2136
- ], runtimeDir);
2137
- if (reload.kind !== "exited" || reload.code !== 0) throw new LocalScopeError("HOST_MANAGER_START_FAILED", "managed Host: the migrated unit was written but systemctl daemon-reload failed; the manager load state is unconfirmed");
2138
- const refreshed = inspectOwnedProfileUnit(options.scope, options.profile, unitDir);
2139
- if (refreshed.kind !== "owned" || refreshed.filePath !== inspected.filePath || refreshed.content !== content) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the migrated unit could not be confirmed");
2140
- if ((await queryOwnedProfileUnit(refreshed, runtimeDir, systemctl)).loadState === "not-found") throw new LocalScopeError("HOST_MANAGER_START_FAILED", "managed Host: the migrated unit is not loaded by the manager");
2141
- return { kind: "migrated" };
2142
- }
2143
1743
  /**
2144
1744
  * Start the public daemon Host candidate. The ONE decision input is the
2145
1745
  * installed unit fact: no unit means the basic detached Host immediately, with
2146
1746
  * no user-manager probe and no systemctl call; an installed unit must be loaded
2147
1747
  * by the real manager with a matching FragmentPath, and is then started through
2148
- * exactly one `systemctl --user start`. A different installed build is a
2149
- * diagnostic fact, never an ownership verdict. A manager failure or unit
1748
+ * exactly one `systemctl --user start`. A manager failure or unit
2150
1749
  * conflict is thrown and NEVER degrades to a detached process; this function
2151
1750
  * never writes a unit.
2152
1751
  */
@@ -2171,14 +1770,25 @@ async function startPublicHostCandidate(options, deps = {}) {
2171
1770
  return () => void 0;
2172
1771
  }
2173
1772
  /**
2174
- * Collect the same validated installed facts for BOTH manager renderers; the
2175
- * profile identity digest is the shared canonical-profile owner.
1773
+ * Validate only the canonical DSH anchor and profile facts needed to read an
1774
+ * installed LaunchAgent. This deliberately does not validate the current Node,
1775
+ * Host entry or build.
2176
1776
  */
1777
+ function collectLaunchdProfileFacts(scope, profile, dshAnchor) {
1778
+ return {
1779
+ dshHome: scope.dshHome,
1780
+ scopeDir: scope.dir,
1781
+ profileRealpath: scope.profileRealpath,
1782
+ profile,
1783
+ scopeId: scope.scopeId,
1784
+ dshAnchor: readVerifiedDshAnchor(dshAnchor, scope.dshVersion)
1785
+ };
1786
+ }
1787
+ /** Collect the validated installed facts needed to render a new LaunchAgent. */
2177
1788
  function collectLaunchdUnitFacts(options) {
2178
1789
  return {
2179
1790
  ...collectUnitFacts(options),
2180
- scopeDir: options.scope.dir,
2181
- profileIdentity: profileIdentityDigest(options.scope.profileRealpath)
1791
+ scopeDir: options.scope.dir
2182
1792
  };
2183
1793
  }
2184
1794
  /**
@@ -2192,10 +1802,11 @@ function collectLaunchdUnitFacts(options) {
2192
1802
  * qualification/peer/manual/reexec policies never consider a manager job.
2193
1803
  */
2194
1804
  async function startManagedHostCandidate(options, deps = {}) {
1805
+ if (process.platform === "win32") return spawnHostCandidate(options);
2195
1806
  if (process.platform === "darwin") {
2196
1807
  if (options.hostStartPolicy !== "public") return spawnHostCandidate(options);
2197
1808
  const launchdDeps = deps.launchd ?? {};
2198
- const facts = collectLaunchdUnitFacts(options);
1809
+ const facts = collectLaunchdProfileFacts(options.scope, options.profile, options.dshAnchor);
2199
1810
  const inspected = inspectOwnedLaunchdUnit(facts, launchdDeps);
2200
1811
  if (inspected.kind === "none") return spawnHostCandidate(options);
2201
1812
  await startLaunchdService(facts, inspected.unit, launchdDeps);
@@ -2204,6 +1815,24 @@ async function startManagedHostCandidate(options, deps = {}) {
2204
1815
  return startPublicHostCandidate(options, deps);
2205
1816
  }
2206
1817
  /**
1818
+ * The exact environment of one detached Host candidate. The Host is never an
1819
+ * OSC 7577 reporter: the protocol capability and its private handoff are
1820
+ * removed even if an older caller left them ambient.
1821
+ */
1822
+ function hostCandidateEnvironment(options, source = process.env) {
1823
+ const env = {
1824
+ ...source,
1825
+ SPLIT_PROCESS_DSH_ANCHOR: options.dshAnchor,
1826
+ SPLIT_PROCESS_PROFILE: options.profile
1827
+ };
1828
+ scrubProgramResumeEnvironment(env);
1829
+ delete env.SPLIT_PROCESS_EXTRA_PATCH;
1830
+ delete env.DSH_PI_TUI_ROLE;
1831
+ delete env.DSH_PI_TUI_HOST_ENTRY;
1832
+ delete env.DSH_PI_TUI_BACKEND;
1833
+ return env;
1834
+ }
1835
+ /**
2207
1836
  * Start one Host candidate as a detached OS process: the default basic daemon
2208
1837
  * whenever no profile unit is installed, and the internal qualification/peer/
2209
1838
  * manual path. It opens/creates the scope `host.log` (a NEW file is 0600; an
@@ -2222,21 +1851,22 @@ function spawnHostCandidate(options) {
2222
1851
  }
2223
1852
  if (!lstatSync(realEntry).isFile()) throw new LocalScopeError("HOST_START_FAILED", "managed Host: the installed Host entry must be a regular file");
2224
1853
  assertEntrySelfLocation(options.hostEntryPath, "HOST_START_FAILED", "installed Host entry");
2225
- const logPath = join(options.scope.dir, "host.log");
1854
+ const scope = "buildId" in options.scope ? options.scope : materializeBuild(options.scope, installedPackageRootFromEntry(pathToFileURL(options.hostEntryPath).href));
1855
+ const logPath = join(scope.dir, "host.log");
2226
1856
  let fd;
2227
1857
  try {
2228
- fd = openSync(logPath, constants.O_WRONLY | constants.O_CREAT | constants.O_APPEND | constants.O_NOFOLLOW, 384);
2229
- const env = {
2230
- ...process.env,
2231
- SPLIT_PROCESS_DSH_ANCHOR: options.dshAnchor,
2232
- SPLIT_PROCESS_PROFILE: options.profile
2233
- };
2234
- delete env.SPLIT_PROCESS_EXTRA_PATCH;
2235
- delete env.DSH_PI_TUI_ROLE;
2236
- delete env.DSH_PI_TUI_HOST_ENTRY;
2237
- delete env.DSH_PI_TUI_BACKEND;
1858
+ let logFlags = constants.O_WRONLY | constants.O_CREAT | constants.O_APPEND;
1859
+ let win32LogMissing = false;
1860
+ if (process.platform === "win32") {
1861
+ const status = win32PrivateFileStatus(logPath);
1862
+ if (status === "unsafe") throw new LocalScopeError("LOCAL_FILE_UNSAFE", "managed Host: the existing Host log is not a private regular file");
1863
+ win32LogMissing = status === "missing";
1864
+ } else logFlags |= constants.O_NOFOLLOW;
1865
+ fd = openSync(logPath, logFlags, 384);
1866
+ if (win32LogMissing && win32PrivateFileStatus(logPath) !== "private") throw new LocalScopeError("LOCAL_FILE_UNSAFE", "managed Host: the Host log did not inherit a private boundary");
1867
+ const env = hostCandidateEnvironment(options);
2238
1868
  const child = spawn(process.execPath, [options.hostEntryPath], {
2239
- cwd: options.scope.profileRealpath,
1869
+ cwd: scope.profileRealpath,
2240
1870
  detached: true,
2241
1871
  stdio: [
2242
1872
  "ignore",
@@ -2318,6 +1948,27 @@ const DARWIN_IDENTITY_KEYS = [
2318
1948
  "uid",
2319
1949
  "state"
2320
1950
  ];
1951
+ /** Exact Win32 registry keys; `hostKernelIdentity` replaces `hostStarttime`. */
1952
+ const WIN32_RECORD_KEYS = [
1953
+ "schema",
1954
+ "scopeId",
1955
+ "profileRealpath",
1956
+ "instanceId",
1957
+ "hostPid",
1958
+ "hostKernelIdentity",
1959
+ "origin",
1960
+ "protocol",
1961
+ "bundleVersion",
1962
+ "dshVersion",
1963
+ "buildId"
1964
+ ];
1965
+ /** Exact Win32 kernel-identity keys. */
1966
+ const WIN32_IDENTITY_KEYS = [
1967
+ "platform",
1968
+ "pid",
1969
+ "ownerSid",
1970
+ "creationFiletime"
1971
+ ];
2321
1972
  /** Exact launch-material keys. */
2322
1973
  const LAUNCH_KEYS = [
2323
1974
  "schema",
@@ -2391,6 +2042,24 @@ function parseDarwinKernelIdentity(value, hostPid) {
2391
2042
  state: requireDecimalInteger(identity, "state", "registry.hostKernelIdentity")
2392
2043
  };
2393
2044
  }
2045
+ /** Parse the complete Win32 kernel identity. `ownerSid` is canonical SID text
2046
+ * and `creationFiletime` is an exact unsigned 64-bit decimal string. */
2047
+ function parseWin32KernelIdentity(value, hostPid) {
2048
+ const identity = assertExactObject(value, WIN32_IDENTITY_KEYS, "registry.hostKernelIdentity");
2049
+ if (identity.platform !== "win32") throw new LocalScopeError("LOCAL_FILE_UNSAFE", "local discovery: registry.hostKernelIdentity.platform must be win32");
2050
+ const pid = requirePositiveInteger(identity, "pid", "registry.hostKernelIdentity");
2051
+ if (pid !== hostPid) throw new LocalScopeError("LOCAL_FILE_UNSAFE", "local discovery: registry.hostKernelIdentity.pid must equal registry.hostPid");
2052
+ const ownerSid = requireString(identity, "ownerSid", "registry.hostKernelIdentity");
2053
+ if (!/^S-\d+-\d+(?:-\d+)+$/u.test(ownerSid)) throw new LocalScopeError("LOCAL_FILE_UNSAFE", "local discovery: registry.hostKernelIdentity.ownerSid must be a canonical SID");
2054
+ const creationFiletime = requireDecimal(identity, "creationFiletime", "registry.hostKernelIdentity");
2055
+ if (BigInt(creationFiletime) > 18446744073709551615n) throw new LocalScopeError("LOCAL_FILE_UNSAFE", "local discovery: registry.hostKernelIdentity.creationFiletime exceeds uint64");
2056
+ return {
2057
+ platform: "win32",
2058
+ pid,
2059
+ ownerSid,
2060
+ creationFiletime
2061
+ };
2062
+ }
2394
2063
  function requireDecimalInteger(record, key, label) {
2395
2064
  const value = record[key];
2396
2065
  if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new LocalScopeError("LOCAL_FILE_UNSAFE", `local discovery: ${label}.${key} must be a non-negative integer`);
@@ -2446,6 +2115,23 @@ function parseRecord(value, scope) {
2446
2115
  buildId: shared.buildId
2447
2116
  };
2448
2117
  }
2118
+ if (schema === 3) {
2119
+ const record = assertExactObject(value, WIN32_RECORD_KEYS, "registry");
2120
+ const shared = parseSharedRecord(record, scope);
2121
+ return {
2122
+ schema: 3,
2123
+ scopeId: shared.scopeId,
2124
+ profileRealpath: shared.profileRealpath,
2125
+ instanceId: shared.instanceId,
2126
+ hostPid: shared.hostPid,
2127
+ hostKernelIdentity: parseWin32KernelIdentity(record.hostKernelIdentity, shared.hostPid),
2128
+ origin: shared.origin,
2129
+ protocol: shared.protocol,
2130
+ bundleVersion: shared.bundleVersion,
2131
+ dshVersion: shared.dshVersion,
2132
+ buildId: shared.buildId
2133
+ };
2134
+ }
2449
2135
  if (schema === 2) {
2450
2136
  const record = assertExactObject(value, DARWIN_RECORD_KEYS, "registry");
2451
2137
  const shared = parseSharedRecord(record, scope);
@@ -2468,9 +2154,10 @@ function parseRecord(value, scope) {
2468
2154
  /** Reject a schema that cannot belong to the running local platform. A Linux
2469
2155
  * schema1 record on macOS (or the reverse) is not a candidate this process may
2470
2156
  * authenticate, spawn around or treat as a readiness proof. */
2471
- function assertRecordSchemaPlatform(record) {
2472
- if (record.schema === 1 && process.platform !== "linux") throw new LocalScopeError("HOST_PROTOCOL_INCOMPATIBLE", "local discovery: schema 1 is a Linux Host publication");
2473
- if (record.schema === 2 && process.platform !== "darwin") throw new LocalScopeError("HOST_PROTOCOL_INCOMPATIBLE", "local discovery: schema 2 is a macOS Host publication");
2157
+ function assertRecordSchemaPlatform(record, platform = process.platform) {
2158
+ if (record.schema === 1 && platform !== "linux") throw new LocalScopeError("HOST_PROTOCOL_INCOMPATIBLE", "local discovery: schema 1 is a Linux Host publication");
2159
+ if (record.schema === 2 && platform !== "darwin") throw new LocalScopeError("HOST_PROTOCOL_INCOMPATIBLE", "local discovery: schema 2 is a macOS Host publication");
2160
+ if (record.schema === 3 && platform !== "win32") throw new LocalScopeError("HOST_PROTOCOL_INCOMPATIBLE", "local discovery: schema 3 is a Windows Host publication");
2474
2161
  }
2475
2162
  /** The ONE record equality used by authentication and transport currentness:
2476
2163
  * the shared fields plus the schema-specific kernel identity. */
@@ -2482,6 +2169,11 @@ function sameLocalInstanceRecord(left, right) {
2482
2169
  const b = right.hostKernelIdentity;
2483
2170
  return a.platform === b.platform && a.pid === b.pid && a.bootUUID === b.bootUUID && a.uniqueId === b.uniqueId && a.parentUniqueId === b.parentUniqueId && a.processUUID === b.processUUID && a.startSec === b.startSec && a.startUsec === b.startUsec && a.ppid === b.ppid && a.pgid === b.pgid && a.sid === b.sid && a.uid === b.uid && a.state === b.state;
2484
2171
  }
2172
+ if (left.schema === 3 && right.schema === 3) {
2173
+ const a = left.hostKernelIdentity;
2174
+ const b = right.hostKernelIdentity;
2175
+ return a.platform === b.platform && a.pid === b.pid && a.ownerSid === b.ownerSid && a.creationFiletime === b.creationFiletime;
2176
+ }
2485
2177
  return false;
2486
2178
  }
2487
2179
  /** Can this Client speak the live Host's required local wire contract? */
@@ -2496,6 +2188,24 @@ function assertClientHostCompatible(record, scope) {
2496
2188
  * failure.
2497
2189
  */
2498
2190
  function readPrivateJsonFile(path, maxBytes, label) {
2191
+ if (process.platform === "win32") {
2192
+ const status = win32PrivateFileStatus(path);
2193
+ if (status === "missing") return void 0;
2194
+ if (status !== "private") throw new LocalScopeError("LOCAL_FILE_UNSAFE", `local discovery: ${label} must be a private regular file`);
2195
+ let info;
2196
+ try {
2197
+ info = lstatSync(path);
2198
+ } catch (error) {
2199
+ throw new LocalScopeError("LOCAL_FILE_UNSAFE", `local discovery: ${label} is not readable`, error);
2200
+ }
2201
+ if (info.size > maxBytes) throw new LocalScopeError("LOCAL_FILE_UNSAFE", `local discovery: ${label} exceeds ${String(maxBytes)} bytes`);
2202
+ const text = readFileSync(path, "utf8");
2203
+ try {
2204
+ return JSON.parse(text);
2205
+ } catch (error) {
2206
+ throw new LocalScopeError("LOCAL_FILE_UNSAFE", `local discovery: ${label} is not valid JSON`, error);
2207
+ }
2208
+ }
2499
2209
  let fd;
2500
2210
  try {
2501
2211
  fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
@@ -2562,7 +2272,7 @@ function assertConnectUrl(connectUrl, record) {
2562
2272
  */
2563
2273
  function inspectHostProcess(record, procRoot = "/proc", readKernel = readKernelProcess) {
2564
2274
  assertRecordSchemaPlatform(record);
2565
- if (record.schema === 2) {
2275
+ if (record.schema === 2 || record.schema === 3) {
2566
2276
  const observed = readKernel(record.hostPid);
2567
2277
  if (observed.kind === "unknown") throw new LocalScopeError("PROCESS_STARTTIME_UNAVAILABLE", `local discovery: the kernel identity of Host pid ${String(record.hostPid)} is unavailable`);
2568
2278
  return sameKernelProcess(record.hostKernelIdentity, observed) === "same" ? "alive" : "dead";
@@ -2694,9 +2404,9 @@ async function readAuthenticatedIdentity(record, cookie, signal) {
2694
2404
  * complete PR-1 identity. `unknown` is always `PROCESS_STARTTIME_UNAVAILABLE`;
2695
2405
  * a different/absent process is `HOST_IDENTITY_MISMATCH` (never a kill permit).
2696
2406
  */
2697
- function assertRecordedHostKernelIdentityCurrent(record, readKernel = readKernelProcess) {
2698
- assertRecordSchemaPlatform(record);
2699
- if (record.schema === 2) {
2407
+ function assertRecordedHostKernelIdentityCurrent(record, readKernel = readKernelProcess, platform = process.platform) {
2408
+ assertRecordSchemaPlatform(record, platform);
2409
+ if (record.schema === 2 || record.schema === 3) {
2700
2410
  const observed = readKernel(record.hostPid);
2701
2411
  if (observed.kind === "unknown") throw new LocalScopeError("PROCESS_STARTTIME_UNAVAILABLE", "local discovery: the Host kernel identity is unavailable");
2702
2412
  if (sameKernelProcess(record.hostKernelIdentity, observed) !== "same") throw new LocalScopeError("HOST_IDENTITY_MISMATCH", "local discovery: the Host PID is no longer the recorded process");
@@ -2761,4 +2471,4 @@ async function ensureLocalHost(options) {
2761
2471
  throw new LocalScopeError("HOST_START_TIMEOUT", `local discovery: no ready Host registry appeared within ${String(REGISTRY_WAIT_TIMEOUT_MS / 1e3)}s`);
2762
2472
  }
2763
2473
  //#endregion
2764
- export { prepareOwnedLaunchdForCurrentInstall as C, launchdServiceMatches as S, uninstallLaunchdUnit as T, uninstallOwnedProfileUnit as _, inspectHostProcess as a, installLaunchdUnit as b, collectUnitFacts as c, prepareOwnedProfileUnitForCurrentInstall as d, profileIdentityDigest as f, stopOwnedProfileUnit as g, selectRuntimeDir as h, ensureLocalHost as i, inspectOwnedProfileUnit as l, runSystemctl as m, assertRecordedHostKernelIdentityCurrent as n, readLocalRecord as o, queryOwnedProfileUnit as p, authenticateLocalHost as r, sameLocalInstanceRecord as s, assertClientHostCompatible as t, installProfileHostUnit as u, inspectLaunchdService as v, stopLaunchdService as w, launchdLogPaths as x, inspectOwnedLaunchdUnit as y };
2474
+ export { launchdServiceMatches as C, launchdLogPaths as S, uninstallLaunchdUnit as T, stopOwnedProfileUnit as _, inspectHostProcess as a, inspectOwnedLaunchdUnit as b, buildUnitName as c, inspectOwnedProfileUnit as d, installProfileHostUnit as f, setOwnedProfileUnitEnablement as g, selectRuntimeDir as h, ensureLocalHost as i, collectLaunchdProfileFacts as l, runSystemctl as m, assertRecordedHostKernelIdentityCurrent as n, readLocalRecord as o, queryOwnedProfileUnit as p, authenticateLocalHost as r, sameLocalInstanceRecord as s, assertClientHostCompatible as t, collectLaunchdUnitFacts as u, uninstallOwnedProfileUnit as v, stopLaunchdService as w, installLaunchdUnit as x, inspectLaunchdService as y };