@indigoai-us/hq-cli 5.345.246 → 5.345.248
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +63 -0
- package/assets/lanes-hooks/hq-lanes-drain.sh +1 -1
- package/contracts/host-canary-release.json +14 -0
- package/dist/command-catalog.generated.d.ts +1116 -3
- package/dist/command-catalog.generated.js +1373 -3
- package/dist/command-registration-plan.d.ts +6 -0
- package/dist/command-registration-plan.js +1 -0
- package/dist/commands/install-global.d.ts +15 -0
- package/dist/commands/install-global.js +98 -4
- package/dist/commands/lanes-hold.js +7 -7
- package/dist/commands/lanes-resume.js +2 -2
- package/dist/commands/lanes-review.js +1 -1
- package/dist/commands/lanes-session-start.d.ts +1 -1
- package/dist/commands/lanes-session-start.js +3 -3
- package/dist/commands/lanes-shared.d.ts +1 -1
- package/dist/commands/lanes.d.ts +2 -2
- package/dist/commands/lanes.js +50 -50
- package/dist/commands/mcp-registration.d.ts +17 -0
- package/dist/commands/mcp-registration.js +119 -0
- package/dist/commands/mesh.d.ts +25 -0
- package/dist/commands/mesh.js +48 -8
- package/dist/commands/ontology-graph.d.ts +62 -0
- package/dist/commands/ontology-graph.js +439 -0
- package/dist/commands/pkg-install.js +1 -1
- package/dist/commands/reindex.js +1 -1
- package/dist/index.js +1 -1
- package/dist/lanes-monitor-check-argv.d.ts +1 -1
- package/dist/lanes-monitor-check-argv.js +1 -1
- package/dist/lanes-monitor-check-fast.d.ts +1 -1
- package/dist/lanes-monitor-check-fast.js +1 -1
- package/dist/lanes-session-start-argv.d.ts +1 -1
- package/dist/lanes-session-start-argv.js +1 -1
- package/dist/lib/capacity/sign-in.d.ts +1 -1
- package/dist/lib/capacity/sign-in.js +1 -1
- package/dist/lib/daemon/hook-requests-conduct-link.js +2 -2
- package/dist/lib/daemon/lanes-monitor-state.d.ts +2 -2
- package/dist/lib/daemon/lanes-monitor-state.js +2 -2
- package/dist/lib/daemon/merge-sections.d.ts +3 -3
- package/dist/lib/daemon/merge-sections.js +7 -7
- package/dist/lib/daemon/remote-control-pools.js +1 -1
- package/dist/lib/daemon/run.js +1 -1
- package/dist/lib/daemon/state-file.d.ts +1 -1
- package/dist/lib/daemon/state-file.js +1 -1
- package/dist/lib/doctor/checks/antigravity-wiring.d.ts +21 -0
- package/dist/lib/doctor/checks/antigravity-wiring.js +75 -0
- package/dist/lib/doctor/checks/anywhere.js +30 -0
- package/dist/lib/doctor/checks/runtime-probe.js +13 -0
- package/dist/lib/doctor/platform.d.ts +1 -1
- package/dist/lib/doctor/platform.js +5 -0
- package/dist/lib/doctor/registry.js +3 -0
- package/dist/lib/flag-snapshot-file.d.ts +2 -0
- package/dist/lib/flag-snapshot-file.js +118 -48
- package/dist/lib/hook-engine/canary-gate.d.ts +57 -3
- package/dist/lib/hook-engine/canary-gate.js +138 -6
- package/dist/lib/hook-engine/coverage.d.ts +91 -0
- package/dist/lib/hook-engine/coverage.js +184 -0
- package/dist/lib/hot-channels/graph-context.d.ts +105 -0
- package/dist/lib/hot-channels/graph-context.js +377 -0
- package/dist/lib/hot-channels/signals-pass.js +27 -1
- package/dist/lib/install/antigravity-targets.d.ts +39 -0
- package/dist/lib/install/antigravity-targets.js +122 -0
- package/dist/lib/lanes/claude-credential.d.ts +1 -1
- package/dist/lib/lanes/claude-credential.js +1 -1
- package/dist/lib/lanes/delivery-core.d.ts +1 -1
- package/dist/lib/lanes/delivery-core.js +1 -1
- package/dist/lib/lanes/delivery.d.ts +10 -10
- package/dist/lib/lanes/delivery.js +8 -8
- package/dist/lib/lanes/dropbox.d.ts +1 -1
- package/dist/lib/lanes/dropbox.js +1 -1
- package/dist/lib/lanes/hooks-install.js +2 -2
- package/dist/lib/lanes/index.d.ts +1 -1
- package/dist/lib/lanes/index.js +1 -1
- package/dist/lib/lanes/monitor.js +1 -1
- package/dist/lib/lanes/quota-notice.js +1 -1
- package/dist/lib/lanes/quota.d.ts +1 -1
- package/dist/lib/lanes/quota.js +1 -1
- package/dist/lib/lanes/repo-merge-hold.d.ts +2 -2
- package/dist/lib/lanes/repo-merge-hold.js +2 -2
- package/dist/lib/lanes/spawn.d.ts +4 -4
- package/dist/lib/lanes/spawn.js +5 -5
- package/dist/lib/mesh/live/company-flag-refresh.d.ts +61 -0
- package/dist/lib/mesh/live/company-flag-refresh.js +159 -0
- package/dist/lib/mesh/live/company-reporting-gaps.d.ts +61 -0
- package/dist/lib/mesh/live/company-reporting-gaps.js +238 -0
- package/dist/lib/mesh/live/daemon/duplicate-unit.d.ts +156 -0
- package/dist/lib/mesh/live/daemon/duplicate-unit.js +616 -0
- package/dist/lib/mesh/live/daemon/run.d.ts +13 -0
- package/dist/lib/mesh/live/daemon/run.js +35 -2
- package/dist/lib/mesh/live/direct-drain.js +1 -1
- package/dist/lib/mesh/live/emit.d.ts +3 -0
- package/dist/lib/mesh/live/emit.js +32 -9
- package/dist/lib/mesh/live/flush.d.ts +3 -0
- package/dist/lib/mesh/live/flush.js +115 -32
- package/dist/lib/mesh/live/liveness-carry.d.ts +1 -1
- package/dist/lib/mesh/live/liveness-carry.js +1 -1
- package/dist/lib/mesh/live/reporting-privacy.d.ts +119 -3
- package/dist/lib/mesh/live/reporting-privacy.js +235 -11
- package/dist/lib/mesh/live/spool.d.ts +17 -2
- package/dist/lib/mesh/live/spool.js +22 -6
- package/dist/lib/ontology-graph/legacy/coverage.d.ts +67 -0
- package/dist/lib/ontology-graph/legacy/coverage.js +192 -0
- package/dist/lib/ontology-graph/legacy/index.d.ts +199 -0
- package/dist/lib/ontology-graph/legacy/index.js +1150 -0
- package/dist/lib/ontology-graph/legacy/parse.d.ts +49 -0
- package/dist/lib/ontology-graph/legacy/parse.js +126 -0
- package/dist/lib/ontology-graph/legacy/report.d.ts +14 -0
- package/dist/lib/ontology-graph/legacy/report.js +254 -0
- package/dist/lib/ontology-graph/legacy/verb-map.d.ts +35 -0
- package/dist/lib/ontology-graph/legacy/verb-map.js +84 -0
- package/dist/lib/ontology-graph/lint/checks.d.ts +140 -0
- package/dist/lib/ontology-graph/lint/checks.js +717 -0
- package/dist/lib/ontology-graph/lint/coverage.d.ts +106 -0
- package/dist/lib/ontology-graph/lint/coverage.js +241 -0
- package/dist/lib/ontology-graph/lint/daily-job.d.ts +259 -0
- package/dist/lib/ontology-graph/lint/daily-job.js +595 -0
- package/dist/lib/ontology-graph/lint/index.d.ts +65 -0
- package/dist/lib/ontology-graph/lint/index.js +176 -0
- package/dist/lib/ontology-graph/model/files.d.ts +20 -0
- package/dist/lib/ontology-graph/model/files.js +89 -0
- package/dist/lib/ontology-graph/model/index.d.ts +65 -0
- package/dist/lib/ontology-graph/model/index.js +100 -0
- package/dist/lib/ontology-graph/model/pass-tasks.d.ts +156 -0
- package/dist/lib/ontology-graph/model/pass-tasks.js +345 -0
- package/dist/lib/ontology-graph/model/pass.d.ts +109 -0
- package/dist/lib/ontology-graph/model/pass.js +958 -0
- package/dist/lib/ontology-graph/model/runner.d.ts +50 -0
- package/dist/lib/ontology-graph/model/runner.js +160 -0
- package/dist/lib/ontology-graph/model/step.d.ts +195 -0
- package/dist/lib/ontology-graph/model/step.js +523 -0
- package/dist/lib/ontology-graph/model/tasks.d.ts +183 -0
- package/dist/lib/ontology-graph/model/tasks.js +349 -0
- package/dist/lib/ontology-graph/not-implemented.d.ts +5 -0
- package/dist/lib/ontology-graph/not-implemented.js +8 -0
- package/dist/lib/ontology-graph/org/compare.d.ts +28 -0
- package/dist/lib/ontology-graph/org/compare.js +239 -0
- package/dist/lib/ontology-graph/org/derive.d.ts +65 -0
- package/dist/lib/ontology-graph/org/derive.js +352 -0
- package/dist/lib/ontology-graph/org/index.d.ts +73 -0
- package/dist/lib/ontology-graph/org/index.js +513 -0
- package/dist/lib/ontology-graph/org/load.d.ts +31 -0
- package/dist/lib/ontology-graph/org/load.js +476 -0
- package/dist/lib/ontology-graph/org/role.d.ts +38 -0
- package/dist/lib/ontology-graph/org/role.js +268 -0
- package/dist/lib/ontology-graph/org/structure.d.ts +63 -0
- package/dist/lib/ontology-graph/org/structure.js +437 -0
- package/dist/lib/ontology-graph/org/text.d.ts +95 -0
- package/dist/lib/ontology-graph/org/text.js +315 -0
- package/dist/lib/ontology-graph/org/types.d.ts +452 -0
- package/dist/lib/ontology-graph/org/types.js +80 -0
- package/dist/lib/ontology-graph/pages/index.d.ts +64 -0
- package/dist/lib/ontology-graph/pages/index.js +193 -0
- package/dist/lib/ontology-graph/pages/render.d.ts +142 -0
- package/dist/lib/ontology-graph/pages/render.js +682 -0
- package/dist/lib/ontology-graph/proposals/apply.d.ts +109 -0
- package/dist/lib/ontology-graph/proposals/apply.js +468 -0
- package/dist/lib/ontology-graph/proposals/group.d.ts +63 -0
- package/dist/lib/ontology-graph/proposals/group.js +232 -0
- package/dist/lib/ontology-graph/proposals/index.d.ts +173 -0
- package/dist/lib/ontology-graph/proposals/index.js +474 -0
- package/dist/lib/ontology-graph/proposals/model.d.ts +162 -0
- package/dist/lib/ontology-graph/proposals/model.js +196 -0
- package/dist/lib/ontology-graph/proposals/org-chart.d.ts +82 -0
- package/dist/lib/ontology-graph/proposals/org-chart.js +340 -0
- package/dist/lib/ontology-graph/read/brief.d.ts +26 -0
- package/dist/lib/ontology-graph/read/brief.js +251 -0
- package/dist/lib/ontology-graph/read/graph-index.d.ts +76 -0
- package/dist/lib/ontology-graph/read/graph-index.js +198 -0
- package/dist/lib/ontology-graph/read/index.d.ts +59 -0
- package/dist/lib/ontology-graph/read/index.js +792 -0
- package/dist/lib/ontology-graph/read/member.d.ts +7 -0
- package/dist/lib/ontology-graph/read/member.js +34 -0
- package/dist/lib/ontology-graph/read/names.d.ts +44 -0
- package/dist/lib/ontology-graph/read/names.js +292 -0
- package/dist/lib/ontology-graph/read/reader-setting.d.ts +19 -0
- package/dist/lib/ontology-graph/read/reader-setting.js +62 -0
- package/dist/lib/ontology-graph/read/test-graph.d.ts +37 -0
- package/dist/lib/ontology-graph/read/test-graph.js +150 -0
- package/dist/lib/ontology-graph/replay/buffered-store.d.ts +33 -0
- package/dist/lib/ontology-graph/replay/buffered-store.js +50 -0
- package/dist/lib/ontology-graph/replay/config.d.ts +41 -0
- package/dist/lib/ontology-graph/replay/config.js +105 -0
- package/dist/lib/ontology-graph/replay/engine.d.ts +100 -0
- package/dist/lib/ontology-graph/replay/engine.js +1174 -0
- package/dist/lib/ontology-graph/replay/extractors.d.ts +59 -0
- package/dist/lib/ontology-graph/replay/extractors.js +1555 -0
- package/dist/lib/ontology-graph/replay/index.d.ts +90 -0
- package/dist/lib/ontology-graph/replay/index.js +220 -0
- package/dist/lib/ontology-graph/replay/listing-manifest.d.ts +66 -0
- package/dist/lib/ontology-graph/replay/listing-manifest.js +242 -0
- package/dist/lib/ontology-graph/replay/member.d.ts +19 -0
- package/dist/lib/ontology-graph/replay/member.js +65 -0
- package/dist/lib/ontology-graph/replay/mentions.d.ts +58 -0
- package/dist/lib/ontology-graph/replay/mentions.js +239 -0
- package/dist/lib/ontology-graph/replay/readers.d.ts +98 -0
- package/dist/lib/ontology-graph/replay/readers.js +1251 -0
- package/dist/lib/ontology-graph/replay/rules.d.ts +127 -0
- package/dist/lib/ontology-graph/replay/rules.js +374 -0
- package/dist/lib/ontology-graph/replay/scope.d.ts +35 -0
- package/dist/lib/ontology-graph/replay/scope.js +115 -0
- package/dist/lib/ontology-graph/replay/transcripts.d.ts +39 -0
- package/dist/lib/ontology-graph/replay/transcripts.js +224 -0
- package/dist/lib/ontology-graph/replay/util.d.ts +55 -0
- package/dist/lib/ontology-graph/replay/util.js +256 -0
- package/dist/lib/ontology-graph/resolve/entity-index.d.ts +159 -0
- package/dist/lib/ontology-graph/resolve/entity-index.js +652 -0
- package/dist/lib/ontology-graph/resolve/index.d.ts +113 -0
- package/dist/lib/ontology-graph/resolve/index.js +214 -0
- package/dist/lib/ontology-graph/resolve/machine.d.ts +34 -0
- package/dist/lib/ontology-graph/resolve/machine.js +95 -0
- package/dist/lib/ontology-graph/resolve/normalize.d.ts +35 -0
- package/dist/lib/ontology-graph/resolve/normalize.js +124 -0
- package/dist/lib/ontology-graph/resolve/org-chart.d.ts +107 -0
- package/dist/lib/ontology-graph/resolve/org-chart.js +578 -0
- package/dist/lib/ontology-graph/resolve/org-layer.d.ts +78 -0
- package/dist/lib/ontology-graph/resolve/org-layer.js +159 -0
- package/dist/lib/ontology-graph/resolve/org-seed.d.ts +141 -0
- package/dist/lib/ontology-graph/resolve/org-seed.js +631 -0
- package/dist/lib/ontology-graph/resolve/org-sources.d.ts +165 -0
- package/dist/lib/ontology-graph/resolve/org-sources.js +634 -0
- package/dist/lib/ontology-graph/resolve/roster.d.ts +76 -0
- package/dist/lib/ontology-graph/resolve/roster.js +226 -0
- package/dist/lib/ontology-graph/resolve/seed.d.ts +267 -0
- package/dist/lib/ontology-graph/resolve/seed.js +1198 -0
- package/dist/lib/ontology-graph/resolve/upsert.d.ts +58 -0
- package/dist/lib/ontology-graph/resolve/upsert.js +139 -0
- package/dist/lib/ontology-graph/resolve/writer.d.ts +128 -0
- package/dist/lib/ontology-graph/resolve/writer.js +351 -0
- package/dist/lib/ontology-graph/schema/authority.d.ts +73 -0
- package/dist/lib/ontology-graph/schema/authority.js +157 -0
- package/dist/lib/ontology-graph/schema/default-schema.d.ts +10 -0
- package/dist/lib/ontology-graph/schema/default-schema.js +242 -0
- package/dist/lib/ontology-graph/schema/grammar.d.ts +57 -0
- package/dist/lib/ontology-graph/schema/grammar.js +409 -0
- package/dist/lib/ontology-graph/schema/index.d.ts +12 -0
- package/dist/lib/ontology-graph/schema/index.js +10 -0
- package/dist/lib/ontology-graph/schema/validate.d.ts +13 -0
- package/dist/lib/ontology-graph/schema/validate.js +132 -0
- package/dist/lib/ontology-graph/store/files.d.ts +34 -0
- package/dist/lib/ontology-graph/store/files.js +207 -0
- package/dist/lib/ontology-graph/store/fs.d.ts +30 -0
- package/dist/lib/ontology-graph/store/fs.js +101 -0
- package/dist/lib/ontology-graph/store/graph-store.d.ts +14 -0
- package/dist/lib/ontology-graph/store/graph-store.js +520 -0
- package/dist/lib/ontology-graph/store/index.d.ts +18 -0
- package/dist/lib/ontology-graph/store/index.js +15 -0
- package/dist/lib/ontology-graph/store/ingest.d.ts +37 -0
- package/dist/lib/ontology-graph/store/ingest.js +323 -0
- package/dist/lib/ontology-graph/store/paths.d.ts +114 -0
- package/dist/lib/ontology-graph/store/paths.js +232 -0
- package/dist/lib/ontology-graph/types.d.ts +1183 -0
- package/dist/lib/ontology-graph/types.js +131 -0
- package/dist/lib/secret-scan/gitleaks-rules.generated.js +1 -1
- package/dist/utils/frontmatter.d.ts +14 -0
- package/dist/utils/frontmatter.js +18 -0
- package/dist/utils/interactive-caller.js +1 -1
- package/package.json +8 -8
|
@@ -0,0 +1,616 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Self-repair for Linux boxes that run Work Mesh from the system unit
|
|
3
|
+
* /etc/systemd/system/hq-mesh-daemon.service and also carry a per-user
|
|
4
|
+
* ~/.config/systemd/user/hq-mesh-daemon.service (written by an older
|
|
5
|
+
* `hq mesh daemon install` without --system-user).
|
|
6
|
+
*
|
|
7
|
+
* The user unit starts a second daemon that cannot take the pid lock, exits,
|
|
8
|
+
* and is restarted by systemd every few seconds. The check runs in
|
|
9
|
+
* `hq mesh daemon run`, so it runs on every box once the CLI is updated: both
|
|
10
|
+
* units restart their daemon after an update.
|
|
11
|
+
*
|
|
12
|
+
* The check runs in both units' processes, and they need different rules:
|
|
13
|
+
*
|
|
14
|
+
* - Only the system unit's daemon ever removes the user unit, and only after
|
|
15
|
+
* it has held this home's pid lock for the settle time with the system unit
|
|
16
|
+
* still active ({@link removeDuplicateUserUnitOnceSettled}). "This home's"
|
|
17
|
+
* lock is the one the user unit's daemon uses: <HOME>/.hq/work-mesh/daemon,
|
|
18
|
+
* or HQ_WORK_MESH_ROOT/daemon, with HOME and HQ_WORK_MESH_ROOT taken from
|
|
19
|
+
* the user unit's environment ({@link userUnitDaemonDir}). A
|
|
20
|
+
* system daemon whose lock sits anywhere else serves another root and
|
|
21
|
+
* removes nothing. The unit file is copied (and fsynced) to
|
|
22
|
+
* <that dir>/hq-mesh-daemon.service.removed.bak first, so the user can put
|
|
23
|
+
* it back without root. If a file cannot be deleted, the result is recorded
|
|
24
|
+
* as partial-removal and the removal is retried.
|
|
25
|
+
* - A process started by the user unit never removes anything. It exits
|
|
26
|
+
* without starting only when the system unit's daemon verifiably runs this
|
|
27
|
+
* home's Work Mesh: the system unit's MainPID is non-zero and is the live
|
|
28
|
+
* owner of this home's pid lock. Otherwise it starts as before. A single
|
|
29
|
+
* "active" reading proves nothing: a crash-looping system unit reads active
|
|
30
|
+
* for a moment on every restart, and a system unit can serve another home.
|
|
31
|
+
* - The system unit's identity comes from systemd itself (`systemctl show`),
|
|
32
|
+
* so every drop-in location and its ordering count. Nothing happens unless
|
|
33
|
+
* its effective User= names this process's user (by name or uid). An empty
|
|
34
|
+
* or unreadable User=, DynamicUser=yes, a masked or missing unit, or an
|
|
35
|
+
* unexpanded specifier in User= also mean "do nothing".
|
|
36
|
+
* - A failed system unit is never restarted here. Restarting it needs root,
|
|
37
|
+
* which belongs to the box's root helper and provisioning. The user unit is
|
|
38
|
+
* kept (it may be the only working daemon) and the reason is recorded.
|
|
39
|
+
* - No system unit, no user unit, not Linux, or a process that belongs to
|
|
40
|
+
* neither unit: do nothing.
|
|
41
|
+
*
|
|
42
|
+
* The role check (cgroup, INVOCATION_ID) is inherited by child processes of
|
|
43
|
+
* either unit. That cannot cause a removal: the user-unit role never removes,
|
|
44
|
+
* and the system-unit role removes only from the process that owns this
|
|
45
|
+
* home's pid lock.
|
|
46
|
+
*/
|
|
47
|
+
import * as fs from "node:fs";
|
|
48
|
+
import * as os from "node:os";
|
|
49
|
+
import * as path from "node:path";
|
|
50
|
+
import { spawnSync } from "node:child_process";
|
|
51
|
+
import { DAEMON_DIRNAME, SYSTEMD_UNIT_NAME, daemonDir, daemonPidPath } from "./paths.js";
|
|
52
|
+
import { readPidLock } from "./pid-lock.js";
|
|
53
|
+
import { SYSTEMD_SYSTEM_UNIT_DIR, describeSystemUnitState, meshSystemUnitPresent, readMeshSystemUnitState, } from "./system-unit.js";
|
|
54
|
+
export const DUPLICATE_UNIT_RECORD = "duplicate-unit.json";
|
|
55
|
+
export const REMOVED_USER_UNIT_BACKUP = `${SYSTEMD_UNIT_NAME}.removed.bak`;
|
|
56
|
+
export const DEFAULT_SETTLE_MS = 30_000;
|
|
57
|
+
export const DEFAULT_RETRY_MS = 5 * 60_000;
|
|
58
|
+
export const DEFAULT_MAX_ATTEMPTS = 12;
|
|
59
|
+
export function meshUserUnitPath(home) {
|
|
60
|
+
return path.join(home, ".config", "systemd", "user", SYSTEMD_UNIT_NAME);
|
|
61
|
+
}
|
|
62
|
+
function userUnitWantsLink(home) {
|
|
63
|
+
return path.join(home, ".config", "systemd", "user", "default.target.wants", SYSTEMD_UNIT_NAME);
|
|
64
|
+
}
|
|
65
|
+
/** Split a systemd Environment= value into its assignments, honouring double quotes. */
|
|
66
|
+
function environmentAssignments(value) {
|
|
67
|
+
const out = [];
|
|
68
|
+
const re = /"((?:[^"\\]|\\.)*)"|(\S+)/g;
|
|
69
|
+
let m;
|
|
70
|
+
while ((m = re.exec(value)) !== null)
|
|
71
|
+
out.push(m[1] !== undefined ? m[1].replace(/\\(.)/g, "$1") : m[2]);
|
|
72
|
+
return out;
|
|
73
|
+
}
|
|
74
|
+
/** The variables that decide which daemon dir `hq mesh daemon run` locks. */
|
|
75
|
+
const DIR_VARS = ["HOME", "HQ_WORK_MESH_ROOT"];
|
|
76
|
+
function applyAssignments(env, value) {
|
|
77
|
+
if (!value.trim()) {
|
|
78
|
+
// An empty Environment= resets every earlier assignment.
|
|
79
|
+
env.clear();
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
for (const assignment of environmentAssignments(value)) {
|
|
83
|
+
const eq = assignment.indexOf("=");
|
|
84
|
+
if (eq > 0)
|
|
85
|
+
env.set(assignment.slice(0, eq), assignment.slice(eq + 1));
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
/** The daemon dir an environment leads to, or null when it cannot be resolved safely. */
|
|
89
|
+
function daemonDirFromEnvironment(home, env) {
|
|
90
|
+
const unsafe = (v) => v.includes("%") || v.includes("$") || !path.isAbsolute(v);
|
|
91
|
+
const root = env.get("HQ_WORK_MESH_ROOT")?.trim();
|
|
92
|
+
if (root)
|
|
93
|
+
return unsafe(root) ? null : path.join(root, DAEMON_DIRNAME);
|
|
94
|
+
const unitHome = env.get("HOME")?.trim();
|
|
95
|
+
if (unitHome && unsafe(unitHome))
|
|
96
|
+
return null;
|
|
97
|
+
return path.join(unitHome || home, ".hq", "work-mesh", DAEMON_DIRNAME);
|
|
98
|
+
}
|
|
99
|
+
function defaultUserEnvironmentSources(home) {
|
|
100
|
+
const unitDirs = [path.join(home, ".config", "systemd", "user"), "/etc/systemd/user", "/run/systemd/user", "/usr/local/lib/systemd/user", "/usr/lib/systemd/user"];
|
|
101
|
+
return {
|
|
102
|
+
dropInDirs: unitDirs.flatMap((dir) => [path.join(dir, `${SYSTEMD_UNIT_NAME}.d`), path.join(dir, "service.d")]),
|
|
103
|
+
environmentDirs: [path.join(home, ".config", "environment.d"), "/etc/environment.d", "/run/environment.d", "/usr/local/lib/environment.d", "/usr/lib/environment.d"],
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
function confFiles(dir) {
|
|
107
|
+
try {
|
|
108
|
+
return fs.readdirSync(dir).filter((name) => name.endsWith(".conf")).map((name) => path.join(dir, name));
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
return [];
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* The user manager's view of the user unit's environment, through the user
|
|
116
|
+
* bus: `show-environment` (environment.d, set-environment) overlaid with the
|
|
117
|
+
* unit's merged Environment= from every drop-in location. Null when the bus
|
|
118
|
+
* cannot answer; "unknown" when the environment comes from an
|
|
119
|
+
* EnvironmentFile= the code does not read.
|
|
120
|
+
*/
|
|
121
|
+
function userManagerUnitEnvironment(run) {
|
|
122
|
+
let managerOut;
|
|
123
|
+
let unitOut;
|
|
124
|
+
try {
|
|
125
|
+
managerOut = run("systemctl", ["--user", "show-environment"]);
|
|
126
|
+
unitOut = run("systemctl", ["--user", "show", "-p", "Environment", "-p", "EnvironmentFiles", SYSTEMD_UNIT_NAME]);
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
return null;
|
|
130
|
+
}
|
|
131
|
+
if (managerOut.status !== 0 || unitOut.status !== 0)
|
|
132
|
+
return null;
|
|
133
|
+
const props = new Map();
|
|
134
|
+
for (const line of unitOut.stdout.split(/\r?\n/)) {
|
|
135
|
+
const eq = line.indexOf("=");
|
|
136
|
+
if (eq > 0)
|
|
137
|
+
props.set(line.slice(0, eq), line.slice(eq + 1));
|
|
138
|
+
}
|
|
139
|
+
if (!props.has("Environment"))
|
|
140
|
+
return null;
|
|
141
|
+
if ((props.get("EnvironmentFiles") ?? "").trim())
|
|
142
|
+
return "unknown";
|
|
143
|
+
const env = new Map();
|
|
144
|
+
for (const line of managerOut.stdout.split(/\r?\n/)) {
|
|
145
|
+
const eq = line.indexOf("=");
|
|
146
|
+
if (eq <= 0)
|
|
147
|
+
continue;
|
|
148
|
+
const key = line.slice(0, eq);
|
|
149
|
+
if (DIR_VARS.includes(key))
|
|
150
|
+
env.set(key, line.slice(eq + 1));
|
|
151
|
+
}
|
|
152
|
+
const unitEnv = new Map();
|
|
153
|
+
applyAssignments(unitEnv, props.get("Environment") ?? "");
|
|
154
|
+
for (const [key, value] of unitEnv)
|
|
155
|
+
env.set(key, value);
|
|
156
|
+
return env;
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* The daemon dir the user unit's daemon locks: HQ_WORK_MESH_ROOT/daemon when
|
|
160
|
+
* its environment sets that, else <HOME>/.hq/work-mesh/daemon, with HOME
|
|
161
|
+
* taken from its environment when set there. The user manager is asked
|
|
162
|
+
* first. When it cannot be reached, the unit file is read, and the answer is
|
|
163
|
+
* null (do nothing) if the environment could also come from somewhere the
|
|
164
|
+
* file does not show: EnvironmentFile=, a drop-in, or an environment.d file
|
|
165
|
+
* that sets HOME or HQ_WORK_MESH_ROOT.
|
|
166
|
+
*/
|
|
167
|
+
export function userUnitDaemonDir(home, run, sources = {}) {
|
|
168
|
+
const unitFile = meshUserUnitPath(home);
|
|
169
|
+
if (run) {
|
|
170
|
+
const managed = userManagerUnitEnvironment(run);
|
|
171
|
+
if (managed === "unknown")
|
|
172
|
+
return null;
|
|
173
|
+
if (managed)
|
|
174
|
+
return daemonDirFromEnvironment(home, managed);
|
|
175
|
+
}
|
|
176
|
+
const defaults = defaultUserEnvironmentSources(home);
|
|
177
|
+
const dropInDirs = [`${unitFile}.d`, ...(sources.dropInDirs ?? defaults.dropInDirs)];
|
|
178
|
+
if (dropInDirs.some((dir) => confFiles(dir).length > 0))
|
|
179
|
+
return null;
|
|
180
|
+
for (const dir of sources.environmentDirs ?? defaults.environmentDirs) {
|
|
181
|
+
for (const file of confFiles(dir)) {
|
|
182
|
+
let text;
|
|
183
|
+
try {
|
|
184
|
+
text = fs.readFileSync(file, "utf8");
|
|
185
|
+
}
|
|
186
|
+
catch {
|
|
187
|
+
return null;
|
|
188
|
+
}
|
|
189
|
+
if (/^\s*(HOME|HQ_WORK_MESH_ROOT)\s*=/m.test(text))
|
|
190
|
+
return null;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
let text;
|
|
194
|
+
try {
|
|
195
|
+
text = fs.readFileSync(unitFile, "utf8");
|
|
196
|
+
}
|
|
197
|
+
catch {
|
|
198
|
+
return null;
|
|
199
|
+
}
|
|
200
|
+
let section = "";
|
|
201
|
+
const env = new Map();
|
|
202
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
203
|
+
const line = raw.trim();
|
|
204
|
+
if (!line || line.startsWith("#") || line.startsWith(";"))
|
|
205
|
+
continue;
|
|
206
|
+
const header = /^\[(.+)\]$/.exec(line);
|
|
207
|
+
if (header) {
|
|
208
|
+
section = header[1];
|
|
209
|
+
continue;
|
|
210
|
+
}
|
|
211
|
+
if (section !== "Service")
|
|
212
|
+
continue;
|
|
213
|
+
if (/^EnvironmentFile\s*=/.test(line))
|
|
214
|
+
return null;
|
|
215
|
+
const assigned = /^Environment\s*=\s*(.*)$/.exec(line);
|
|
216
|
+
if (assigned)
|
|
217
|
+
applyAssignments(env, assigned[1]);
|
|
218
|
+
}
|
|
219
|
+
return daemonDirFromEnvironment(home, env);
|
|
220
|
+
}
|
|
221
|
+
function samePath(a, b) {
|
|
222
|
+
const real = (p) => {
|
|
223
|
+
try {
|
|
224
|
+
return fs.realpathSync(p);
|
|
225
|
+
}
|
|
226
|
+
catch {
|
|
227
|
+
return path.resolve(p);
|
|
228
|
+
}
|
|
229
|
+
};
|
|
230
|
+
return real(a) === real(b);
|
|
231
|
+
}
|
|
232
|
+
function defaultFsyncPath(file) {
|
|
233
|
+
const fd = fs.openSync(file, "r");
|
|
234
|
+
try {
|
|
235
|
+
fs.fsyncSync(fd);
|
|
236
|
+
}
|
|
237
|
+
finally {
|
|
238
|
+
fs.closeSync(fd);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
function pathPresent(file) {
|
|
242
|
+
try {
|
|
243
|
+
fs.lstatSync(file);
|
|
244
|
+
return true;
|
|
245
|
+
}
|
|
246
|
+
catch {
|
|
247
|
+
return false;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
function defaultIsProcessAlive(pid) {
|
|
251
|
+
try {
|
|
252
|
+
process.kill(pid, 0);
|
|
253
|
+
return true;
|
|
254
|
+
}
|
|
255
|
+
catch (err) {
|
|
256
|
+
// EPERM: the process exists but belongs to someone else.
|
|
257
|
+
return err?.code === "EPERM";
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* Runner with the user manager's bus address filled in, so `systemctl --user`
|
|
262
|
+
* reaches it from a system service that runs as the box user.
|
|
263
|
+
*/
|
|
264
|
+
export function defaultDuplicateUnitRun(env = process.env) {
|
|
265
|
+
const uid = process.getuid?.();
|
|
266
|
+
const runtimeDir = env.XDG_RUNTIME_DIR || (typeof uid === "number" ? `/run/user/${uid}` : undefined);
|
|
267
|
+
const childEnv = { ...env };
|
|
268
|
+
if (runtimeDir) {
|
|
269
|
+
childEnv.XDG_RUNTIME_DIR = runtimeDir;
|
|
270
|
+
childEnv.DBUS_SESSION_BUS_ADDRESS ||= `unix:path=${runtimeDir}/bus`;
|
|
271
|
+
}
|
|
272
|
+
return (cmd, args) => {
|
|
273
|
+
const result = spawnSync(cmd, args, { encoding: "utf8", env: childEnv, timeout: 30_000 });
|
|
274
|
+
return {
|
|
275
|
+
status: result.error ? null : result.status,
|
|
276
|
+
stdout: typeof result.stdout === "string" ? result.stdout : "",
|
|
277
|
+
stderr: result.error ? result.error.message : (typeof result.stderr === "string" ? result.stderr : ""),
|
|
278
|
+
};
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
function readProcCgroup() {
|
|
282
|
+
try {
|
|
283
|
+
return fs.readFileSync("/proc/self/cgroup", "utf8");
|
|
284
|
+
}
|
|
285
|
+
catch {
|
|
286
|
+
return null;
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
function cgroupLines(cgroup) {
|
|
290
|
+
return cgroup ? cgroup.split(/\r?\n/).map((line) => line.trimEnd()).filter(Boolean) : [];
|
|
291
|
+
}
|
|
292
|
+
/** True when the cgroup text places this process in a user manager's hq-mesh-daemon.service. */
|
|
293
|
+
export function cgroupIsMeshUserUnit(cgroup) {
|
|
294
|
+
return cgroupLines(cgroup).some((line) => /\/user@\d+\.service\//.test(line) && line.endsWith(`/${SYSTEMD_UNIT_NAME}`));
|
|
295
|
+
}
|
|
296
|
+
/** True when the cgroup text places this process in the system manager's hq-mesh-daemon.service. */
|
|
297
|
+
export function cgroupIsMeshSystemUnit(cgroup) {
|
|
298
|
+
return cgroupLines(cgroup).some((line) => !/\/user@\d+\.service\//.test(line) && line.endsWith(`/system.slice/${SYSTEMD_UNIT_NAME}`));
|
|
299
|
+
}
|
|
300
|
+
/** The system unit's current InvocationID, or null when systemctl cannot say. */
|
|
301
|
+
function systemUnitInvocationId(run) {
|
|
302
|
+
try {
|
|
303
|
+
const result = run("systemctl", ["show", "-p", "InvocationID", "--value", SYSTEMD_UNIT_NAME]);
|
|
304
|
+
if (result.status !== 0)
|
|
305
|
+
return null;
|
|
306
|
+
const id = result.stdout.trim();
|
|
307
|
+
return id || null;
|
|
308
|
+
}
|
|
309
|
+
catch {
|
|
310
|
+
return null;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
/**
|
|
314
|
+
* Which unit started this process: the cgroup first, then systemd's
|
|
315
|
+
* INVOCATION_ID compared with the system unit's own InvocationID.
|
|
316
|
+
*/
|
|
317
|
+
export function meshUnitRole(cgroup, env, run) {
|
|
318
|
+
if (cgroupIsMeshUserUnit(cgroup))
|
|
319
|
+
return "user-unit";
|
|
320
|
+
if (cgroupIsMeshSystemUnit(cgroup))
|
|
321
|
+
return "system-unit";
|
|
322
|
+
const invocation = env.INVOCATION_ID?.trim();
|
|
323
|
+
if (invocation && invocation === systemUnitInvocationId(run))
|
|
324
|
+
return "system-unit";
|
|
325
|
+
return "other";
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* Read the system unit's effective identity from systemd, which has already
|
|
329
|
+
* merged every unit file and drop-in location in its own order. Null when
|
|
330
|
+
* systemctl cannot answer.
|
|
331
|
+
*/
|
|
332
|
+
export function readSystemUnitIdentity(run) {
|
|
333
|
+
let result;
|
|
334
|
+
try {
|
|
335
|
+
result = run("systemctl", ["show", "-p", "User", "-p", "DynamicUser", "-p", "MainPID", "-p", "LoadState", SYSTEMD_UNIT_NAME]);
|
|
336
|
+
}
|
|
337
|
+
catch {
|
|
338
|
+
return null;
|
|
339
|
+
}
|
|
340
|
+
if (result.status !== 0)
|
|
341
|
+
return null;
|
|
342
|
+
const values = new Map();
|
|
343
|
+
for (const line of result.stdout.split(/\r?\n/)) {
|
|
344
|
+
const eq = line.indexOf("=");
|
|
345
|
+
if (eq <= 0)
|
|
346
|
+
continue;
|
|
347
|
+
values.set(line.slice(0, eq).trim(), line.slice(eq + 1).trim());
|
|
348
|
+
}
|
|
349
|
+
if (!values.has("User") || !values.has("LoadState"))
|
|
350
|
+
return null;
|
|
351
|
+
const mainPid = Number.parseInt(values.get("MainPID") ?? "", 10);
|
|
352
|
+
return {
|
|
353
|
+
user: values.get("User") ?? "",
|
|
354
|
+
dynamicUser: values.get("DynamicUser") ?? "",
|
|
355
|
+
mainPid: Number.isFinite(mainPid) && mainPid > 0 ? mainPid : 0,
|
|
356
|
+
loadState: values.get("LoadState") ?? "",
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
/**
|
|
360
|
+
* Null when the system unit runs this user's Work Mesh as far as systemd
|
|
361
|
+
* says; otherwise why it does not (and nothing should happen).
|
|
362
|
+
*/
|
|
363
|
+
export function systemUnitIdentityMismatch(identity, user) {
|
|
364
|
+
if (!identity)
|
|
365
|
+
return "systemctl could not read the system unit's User=";
|
|
366
|
+
if (identity.loadState !== "loaded")
|
|
367
|
+
return `system unit is ${identity.loadState || "not loaded"}`;
|
|
368
|
+
if (/^(yes|true|1|on)$/i.test(identity.dynamicUser))
|
|
369
|
+
return "system unit uses DynamicUser=";
|
|
370
|
+
if (!identity.user)
|
|
371
|
+
return "system unit sets no User=";
|
|
372
|
+
if (identity.user.includes("%"))
|
|
373
|
+
return `system unit User=${identity.user} holds an unexpanded specifier`;
|
|
374
|
+
if (!user)
|
|
375
|
+
return "this process's user is unknown";
|
|
376
|
+
if (identity.user === user.username)
|
|
377
|
+
return null;
|
|
378
|
+
if (/^\d+$/.test(identity.user) && Number(identity.user) === user.uid)
|
|
379
|
+
return null;
|
|
380
|
+
return `system unit runs as ${identity.user}, not ${user.username}`;
|
|
381
|
+
}
|
|
382
|
+
function currentUser() {
|
|
383
|
+
try {
|
|
384
|
+
const info = os.userInfo();
|
|
385
|
+
return { username: info.username, uid: info.uid };
|
|
386
|
+
}
|
|
387
|
+
catch {
|
|
388
|
+
return null;
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
function detail(result) {
|
|
392
|
+
const text = (result.stderr || result.stdout).trim().split(/\r?\n/)[0] ?? "";
|
|
393
|
+
return text ? `: ${text}` : ` (exit ${result.status ?? "signal"})`;
|
|
394
|
+
}
|
|
395
|
+
const FAILED_REASON = "system unit has failed; restarting it needs root and is left to the box's root helper and provisioning";
|
|
396
|
+
/**
|
|
397
|
+
* Copy the user unit aside (flushed to disk), then stop, disable and remove
|
|
398
|
+
* it. Never throws. When the copy fails nothing is removed and `backupError`
|
|
399
|
+
* says why; `remaining` lists files that could not be deleted.
|
|
400
|
+
*/
|
|
401
|
+
function removeUserUnit(home, backupDir, run, ops) {
|
|
402
|
+
const unitFile = meshUserUnitPath(home);
|
|
403
|
+
const backupPath = path.join(backupDir, REMOVED_USER_UNIT_BACKUP);
|
|
404
|
+
if (pathPresent(unitFile)) {
|
|
405
|
+
try {
|
|
406
|
+
fs.mkdirSync(backupDir, { recursive: true, mode: 0o700 });
|
|
407
|
+
fs.copyFileSync(unitFile, backupPath);
|
|
408
|
+
ops.fsyncPath(backupPath);
|
|
409
|
+
ops.fsyncPath(backupDir);
|
|
410
|
+
}
|
|
411
|
+
catch (err) {
|
|
412
|
+
return {
|
|
413
|
+
warnings: [],
|
|
414
|
+
remaining: [],
|
|
415
|
+
backupError: `could not back up ${unitFile} to ${backupPath}: ${err instanceof Error ? err.message : String(err)}`,
|
|
416
|
+
};
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
else if (!pathPresent(backupPath)) {
|
|
420
|
+
return { warnings: [], remaining: [], backupError: `${unitFile} is gone and there is no backup at ${backupPath}` };
|
|
421
|
+
}
|
|
422
|
+
const warnings = [];
|
|
423
|
+
const disable = run("systemctl", ["--user", "disable", SYSTEMD_UNIT_NAME]);
|
|
424
|
+
if (disable.status !== 0)
|
|
425
|
+
warnings.push(`systemctl --user disable failed${detail(disable)}`);
|
|
426
|
+
const remaining = [];
|
|
427
|
+
for (const file of [unitFile, userUnitWantsLink(home)]) {
|
|
428
|
+
if (!pathPresent(file))
|
|
429
|
+
continue;
|
|
430
|
+
try {
|
|
431
|
+
ops.unlink(file);
|
|
432
|
+
}
|
|
433
|
+
catch (err) {
|
|
434
|
+
warnings.push(`could not remove ${file}: ${err instanceof Error ? err.message : String(err)}`);
|
|
435
|
+
}
|
|
436
|
+
if (pathPresent(file))
|
|
437
|
+
remaining.push(file);
|
|
438
|
+
}
|
|
439
|
+
const reload = run("systemctl", ["--user", "daemon-reload"]);
|
|
440
|
+
if (reload.status !== 0)
|
|
441
|
+
warnings.push(`systemctl --user daemon-reload failed${detail(reload)}`);
|
|
442
|
+
const stop = run("systemctl", ["--user", "stop", "--no-block", SYSTEMD_UNIT_NAME]);
|
|
443
|
+
if (stop.status !== 0)
|
|
444
|
+
warnings.push(`systemctl --user stop failed${detail(stop)}`);
|
|
445
|
+
return { warnings, backupPath, remaining };
|
|
446
|
+
}
|
|
447
|
+
function record(home, env, at, result) {
|
|
448
|
+
try {
|
|
449
|
+
const dir = daemonDir(undefined, home, env);
|
|
450
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
451
|
+
fs.writeFileSync(path.join(dir, DUPLICATE_UNIT_RECORD), `${JSON.stringify({ at: at.toISOString(), ...result }, null, 2)}\n`, { mode: 0o600 });
|
|
452
|
+
}
|
|
453
|
+
catch {
|
|
454
|
+
// The journal line is enough when the daemon dir cannot be written.
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
/** Null when there is nothing to reconcile on this machine. */
|
|
458
|
+
function context(deps) {
|
|
459
|
+
const platform = deps.platform ?? process.platform;
|
|
460
|
+
if (platform !== "linux")
|
|
461
|
+
return null;
|
|
462
|
+
const home = deps.home ?? os.homedir();
|
|
463
|
+
const env = deps.env ?? process.env;
|
|
464
|
+
if (!pathPresent(meshUserUnitPath(home)))
|
|
465
|
+
return null;
|
|
466
|
+
if (!meshSystemUnitPresent(deps.systemUnitDir ?? SYSTEMD_SYSTEM_UNIT_DIR))
|
|
467
|
+
return null;
|
|
468
|
+
const run = deps.run ?? defaultDuplicateUnitRun(env);
|
|
469
|
+
const sleep = deps.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
470
|
+
const log = deps.log ?? ((line) => console.error(line));
|
|
471
|
+
const now = deps.now ?? (() => new Date());
|
|
472
|
+
const user = deps.user === undefined ? currentUser() : deps.user;
|
|
473
|
+
const identityMismatch = () => {
|
|
474
|
+
const identity = readSystemUnitIdentity(run);
|
|
475
|
+
return { identity, mismatch: systemUnitIdentityMismatch(identity, user) };
|
|
476
|
+
};
|
|
477
|
+
const finish = (result) => {
|
|
478
|
+
record(home, env, now(), result);
|
|
479
|
+
const why = result.reason ? `: ${result.reason}` : "";
|
|
480
|
+
const warn = result.warnings?.length ? ` (${result.warnings.join("; ")})` : "";
|
|
481
|
+
log(`hq mesh daemon: duplicate user unit ${meshUserUnitPath(home)} ${result.action}${why}${warn}`);
|
|
482
|
+
return result;
|
|
483
|
+
};
|
|
484
|
+
return {
|
|
485
|
+
home,
|
|
486
|
+
env,
|
|
487
|
+
run,
|
|
488
|
+
sleep,
|
|
489
|
+
log,
|
|
490
|
+
now,
|
|
491
|
+
isProcessAlive: deps.isProcessAlive ?? defaultIsProcessAlive,
|
|
492
|
+
identityMismatch,
|
|
493
|
+
finish,
|
|
494
|
+
};
|
|
495
|
+
}
|
|
496
|
+
/**
|
|
497
|
+
* Runs at the start of `hq mesh daemon run`, before the pid lock. Never
|
|
498
|
+
* removes anything. A process started by the system unit gets
|
|
499
|
+
* `removeAfterLock`; a process started by the user unit gets `exitAfter`
|
|
500
|
+
* only when the system unit's daemon holds this home's pid lock.
|
|
501
|
+
*/
|
|
502
|
+
export async function reconcileDuplicateMeshUnit(deps = {}) {
|
|
503
|
+
const ctx = context(deps);
|
|
504
|
+
if (!ctx)
|
|
505
|
+
return { action: "none" };
|
|
506
|
+
const role = meshUnitRole((deps.readCgroup ?? readProcCgroup)(), ctx.env, ctx.run);
|
|
507
|
+
if (role === "other")
|
|
508
|
+
return { action: "none", role };
|
|
509
|
+
const { identity, mismatch } = ctx.identityMismatch();
|
|
510
|
+
if (mismatch)
|
|
511
|
+
return { action: "none", role, reason: mismatch };
|
|
512
|
+
const state = readMeshSystemUnitState(ctx.run);
|
|
513
|
+
if (!state) {
|
|
514
|
+
return ctx.finish({ action: "kept-user-unit", role, reason: "systemctl could not read the system unit's state", systemState: null });
|
|
515
|
+
}
|
|
516
|
+
if (state.activeState === "failed") {
|
|
517
|
+
return ctx.finish({ action: "kept-user-unit", role, reason: FAILED_REASON, systemState: state });
|
|
518
|
+
}
|
|
519
|
+
if (role === "system-unit") {
|
|
520
|
+
ctx.log(`hq mesh daemon: duplicate user unit ${meshUserUnitPath(ctx.home)} found; ` +
|
|
521
|
+
"it is removed only after this daemon has held the pid lock");
|
|
522
|
+
return { action: "deferred-until-lock", role, systemState: state, removeAfterLock: true };
|
|
523
|
+
}
|
|
524
|
+
// The user unit's process: back off only when the system unit's daemon
|
|
525
|
+
// verifiably runs this home's Work Mesh. Never remove anything here.
|
|
526
|
+
const mainPid = identity?.mainPid ?? 0;
|
|
527
|
+
const owner = readPidLock(daemonPidPath(daemonDir(undefined, ctx.home, ctx.env)));
|
|
528
|
+
if (state.activeState === "active" && mainPid > 0 && owner?.pid === mainPid && ctx.isProcessAlive(mainPid)) {
|
|
529
|
+
return ctx.finish({
|
|
530
|
+
action: "deferred-to-system-unit",
|
|
531
|
+
role,
|
|
532
|
+
reason: `the system unit's daemon (pid ${mainPid}) holds this home's pid lock; it removes this unit`,
|
|
533
|
+
systemState: state,
|
|
534
|
+
exitAfter: true,
|
|
535
|
+
});
|
|
536
|
+
}
|
|
537
|
+
const reason = mainPid === 0
|
|
538
|
+
? `system unit has no main process (${describeSystemUnitState(state)})`
|
|
539
|
+
: owner
|
|
540
|
+
? `this home's pid lock is held by pid ${owner.pid}, not the system unit's pid ${mainPid}`
|
|
541
|
+
: `the system unit's daemon (pid ${mainPid}) does not hold this home's pid lock`;
|
|
542
|
+
return ctx.finish({ action: "kept-user-unit", role, reason, systemState: state });
|
|
543
|
+
}
|
|
544
|
+
/**
|
|
545
|
+
* Runs in the system unit's daemon once it holds the pid lock. Waits the
|
|
546
|
+
* settle time, then backs up and removes the user unit only if the system
|
|
547
|
+
* unit still runs as this user, this process still holds the lock, that lock
|
|
548
|
+
* is the user unit's own (same daemon dir), and the system unit is still
|
|
549
|
+
* active. A partial removal is recorded and retried while all of that still
|
|
550
|
+
* holds. Never throws.
|
|
551
|
+
*/
|
|
552
|
+
export async function removeDuplicateUserUnitOnceSettled(deps = {}) {
|
|
553
|
+
const ctx = context(deps);
|
|
554
|
+
if (!ctx)
|
|
555
|
+
return { action: "none" };
|
|
556
|
+
const pid = deps.pid ?? process.pid;
|
|
557
|
+
const lockDir = deps.lockDir ?? daemonDir(undefined, ctx.home, ctx.env);
|
|
558
|
+
const lockPath = daemonPidPath(lockDir);
|
|
559
|
+
const role = "system-unit";
|
|
560
|
+
const maxAttempts = Math.max(1, deps.maxAttempts ?? DEFAULT_MAX_ATTEMPTS);
|
|
561
|
+
const ops = { unlink: deps.unlink ?? ((file) => fs.unlinkSync(file)), fsyncPath: deps.fsyncPath ?? defaultFsyncPath };
|
|
562
|
+
await ctx.sleep(deps.settleMs ?? DEFAULT_SETTLE_MS);
|
|
563
|
+
for (let attempt = 1;; attempt += 1) {
|
|
564
|
+
const { mismatch } = ctx.identityMismatch();
|
|
565
|
+
if (mismatch)
|
|
566
|
+
return { action: "none", role, reason: mismatch };
|
|
567
|
+
// The lock this daemon holds must be the one the user unit's daemon uses.
|
|
568
|
+
const userDir = userUnitDaemonDir(ctx.home, ctx.run, deps.userEnvironmentSources);
|
|
569
|
+
if (!userDir) {
|
|
570
|
+
return { action: "none", role, reason: "the user unit's daemon dir cannot be worked out from its environment" };
|
|
571
|
+
}
|
|
572
|
+
if (!samePath(lockDir, userDir)) {
|
|
573
|
+
return { action: "none", role, reason: `this daemon's lock is in ${lockDir}, not the user unit's ${userDir}` };
|
|
574
|
+
}
|
|
575
|
+
const owner = readPidLock(lockPath);
|
|
576
|
+
if (owner?.pid !== pid) {
|
|
577
|
+
return ctx.finish({
|
|
578
|
+
action: "kept-user-unit",
|
|
579
|
+
role,
|
|
580
|
+
reason: owner ? `pid lock is held by pid ${owner.pid}, not this daemon` : "this daemon no longer holds the pid lock",
|
|
581
|
+
});
|
|
582
|
+
}
|
|
583
|
+
const state = readMeshSystemUnitState(ctx.run);
|
|
584
|
+
if (!state || state.activeState !== "active") {
|
|
585
|
+
return ctx.finish({
|
|
586
|
+
action: "kept-user-unit",
|
|
587
|
+
role,
|
|
588
|
+
reason: state?.activeState === "failed" ? FAILED_REASON : `system unit is ${describeSystemUnitState(state)} after the settle time`,
|
|
589
|
+
systemState: state,
|
|
590
|
+
});
|
|
591
|
+
}
|
|
592
|
+
const removed = removeUserUnit(ctx.home, userDir, ctx.run, ops);
|
|
593
|
+
if (removed.backupError) {
|
|
594
|
+
return ctx.finish({ action: "kept-user-unit", role, reason: removed.backupError, systemState: state });
|
|
595
|
+
}
|
|
596
|
+
const base = {
|
|
597
|
+
role,
|
|
598
|
+
systemState: state,
|
|
599
|
+
...(removed.backupPath ? { backupPath: removed.backupPath } : {}),
|
|
600
|
+
...(removed.warnings.length ? { warnings: removed.warnings } : {}),
|
|
601
|
+
};
|
|
602
|
+
if (removed.remaining.length === 0)
|
|
603
|
+
return ctx.finish({ action: "removed-user-unit", ...base, ...(attempt > 1 ? { attempt } : {}) });
|
|
604
|
+
const partial = ctx.finish({
|
|
605
|
+
action: "partial-removal",
|
|
606
|
+
...base,
|
|
607
|
+
remaining: removed.remaining,
|
|
608
|
+
attempt,
|
|
609
|
+
reason: attempt < maxAttempts ? "some files could not be deleted; retrying" : `some files could not be deleted after ${attempt} attempts`,
|
|
610
|
+
});
|
|
611
|
+
if (attempt >= maxAttempts)
|
|
612
|
+
return partial;
|
|
613
|
+
await ctx.sleep(deps.retryMs ?? DEFAULT_RETRY_MS);
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
//# sourceMappingURL=duplicate-unit.js.map
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type ReportingState } from "../reporting-privacy.js";
|
|
1
2
|
import { type DeliverFn } from "../../../work-context/outbox.js";
|
|
2
3
|
import { type SessionEventsPoster } from "../session-events-client.js";
|
|
3
4
|
import { type FlushSummary } from "../flush.js";
|
|
@@ -9,6 +10,8 @@ import { PresenceClient, type MqttConnectFn } from "./presence.js";
|
|
|
9
10
|
import { TranscriptWatcher, type TranscriptFs } from "./transcript-watch.js";
|
|
10
11
|
import { type MeshEmitMode } from "./mode.js";
|
|
11
12
|
import { type CommandRunner, type LegacyListenPlatform } from "./legacy-listen.js";
|
|
13
|
+
import { type CompanyFlagClient } from "../company-flag-refresh.js";
|
|
14
|
+
import type { FlagClientOptions } from "@indigoai-us/hq-flags-client";
|
|
12
15
|
import { type StartCapacitySchedulerOptions } from "../../../capacity/scheduler.js";
|
|
13
16
|
export declare const SPOOL_DEBOUNCE_MS = 2000;
|
|
14
17
|
/** Direct mode: wait after daemon start before the first spool drain cycle. */
|
|
@@ -80,6 +83,14 @@ export interface DaemonRunDeps {
|
|
|
80
83
|
skipped: number;
|
|
81
84
|
errors: number;
|
|
82
85
|
}>;
|
|
86
|
+
/**
|
|
87
|
+
* Flag client for the company flag snapshot refresh (company-flag-refresh.ts).
|
|
88
|
+
* Defaults to the registry client. A daemon given a test `poster` and no
|
|
89
|
+
* client here makes no flag request, so tests stay off the network.
|
|
90
|
+
*/
|
|
91
|
+
companyFlagClient?: (options: FlagClientOptions) => CompanyFlagClient;
|
|
92
|
+
/** Minimum gap between company flag snapshot refreshes. Default COMPANY_FLAG_REFRESH_INTERVAL_MS. */
|
|
93
|
+
companyFlagRefreshIntervalMs?: number;
|
|
83
94
|
/** When false, skip MQTT (flush-only mode for tests). */
|
|
84
95
|
enablePresence?: boolean;
|
|
85
96
|
/** When false, skip transcript-watch lane (tests). Default true. */
|
|
@@ -115,6 +126,8 @@ export interface DaemonRunDeps {
|
|
|
115
126
|
machineIdentity?: boolean;
|
|
116
127
|
/** Reporting gate (tests). Defaults to one createReportingGate for the daemon's lifetime. */
|
|
117
128
|
reportingAllowed?: () => Promise<boolean>;
|
|
129
|
+
/** Reporting state gate (tests). Defaults to one createReportingStateGate for the daemon's lifetime. */
|
|
130
|
+
reportingState?: () => Promise<ReportingState>;
|
|
118
131
|
/** Test seam immediately before a device-default revocation's guarded commit. */
|
|
119
132
|
beforeDeviceDefaultRevocationCommit?: () => void;
|
|
120
133
|
log?: (dir: string, line: string) => void;
|