@principles/host-runtime 4.3.1 → 4.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -17,11 +17,10 @@
17
17
  * suppresses another workspace on the same installation.
18
18
  */
19
19
  import fs from 'node:fs';
20
- import os from 'node:os';
21
20
  import path from 'node:path';
22
21
  import { fileURLToPath } from 'node:url';
23
22
  import { bucketDateFromTime, buildProductTelemetrySnapshot, deriveDailyTelemetryId, isValidTelemetrySecretHex, } from '@principles/core/runtime';
24
- import { getInstallLayoutPaths, parseInstallManifest, resolveInstallLayout } from '@principles/install-layout';
23
+ import { getInstallLayoutPathsFromPdHome, parseInstallManifest, resolveInstallLayout, resolvePdHome } from '@principles/install-layout';
25
24
  import { loadFeatureFlagFromConfig, loadPdConfigForPlugin } from '../pd-config.js';
26
25
  import { deniedControlState, defaultProductTelemetryControlState, getProductTelemetryStatePath, grantedControlState, pruneWorkspaceExports, readProductTelemetryControlState, resetControlState, withControlStateLock, } from './consent-store.js';
27
26
  import { releaseExclusiveLock, tryAcquireExclusiveLockSync } from './control-state-lock.js';
@@ -96,13 +95,19 @@ function readJsonFile(filePath) {
96
95
  return undefined;
97
96
  }
98
97
  }
99
- function resolveInstallContext(homeDir) {
100
- const paths = getInstallLayoutPaths(homeDir);
98
+ function resolveInstallContext(homePaths) {
99
+ const paths = getInstallLayoutPathsFromPdHome(homePaths);
101
100
  const manifestParsed = parseInstallManifest(readJsonFile(paths.manifest));
102
101
  const manifest = manifestParsed.manifest;
103
102
  const canonicalRuntimeExists = fs.existsSync(paths.hostRuntimeDir);
104
103
  const legacyExtensionExists = fs.existsSync(paths.openClawExtensionDir);
105
- const layout = resolveInstallLayout({ homeDir, manifest, canonicalRuntimeExists, legacyExtensionExists });
104
+ const layout = resolveInstallLayout({
105
+ homeDir: homePaths.homeDir,
106
+ homePaths,
107
+ manifest,
108
+ canonicalRuntimeExists,
109
+ legacyExtensionExists,
110
+ });
106
111
  let hostKind = 'other';
107
112
  if (manifest && manifest.hosts.length === 1 && (manifest.hosts[0] === 'codex' || manifest.hosts[0] === 'openclaw' || manifest.hosts[0] === 'workbuddy')) {
108
113
  [hostKind] = manifest.hosts;
@@ -125,25 +130,69 @@ function workspaceEnvironmentOf(workspaceDir) {
125
130
  return environment ?? 'unknown';
126
131
  }
127
132
  export function createProductTelemetryService(deps = {}) {
128
- const homeDir = () => path.resolve(deps.homeDir ?? os.homedir());
129
- const env = () => deps.env ?? process.env;
133
+ // §6: ONE environment snapshot, fixed at service creation. The suppression
134
+ // gate below and the PD Home resolution MUST read the SAME env — gating on
135
+ // deps.env while resolving PD Home from process.env would let an experiment
136
+ // instance write production consent state (review N3J).
137
+ const resolvedEnv = deps.env ?? process.env;
138
+ // Telemetry control state (consent ledger, export lock) is an Owner
139
+ // governance fact living under the PD Home. The default follows the shared
140
+ // resolution (fed with the SAME snapshot) so an experiment console keeps its
141
+ // state inside the lab; a refused resolution fails loud instead of silently
142
+ // writing production state.
143
+ //
144
+ // ONE resolution, memoized for the service lifetime (§6: no re-parse, no
145
+ // env drift mid-life): feeding the experiment root back into a second
146
+ // getInstallLayoutPaths parse re-derives "production home" from it and the
147
+ // disjointness check then refuses the lab against its own .pd. The
148
+ // already-validated PdHomePaths is passed down instead
149
+ // (getInstallLayoutPathsFromPdHome / resolveInstallLayout({ homePaths })).
150
+ let cachedHomeResolution;
151
+ const homeResolution = () => {
152
+ if (cachedHomeResolution === undefined) {
153
+ cachedHomeResolution = deps.homeDir !== undefined
154
+ ? resolvePdHome({ env: resolvedEnv, homeDir: path.resolve(deps.homeDir) })
155
+ : resolvePdHome({ env: resolvedEnv });
156
+ }
157
+ return cachedHomeResolution;
158
+ };
159
+ const homeDir = () => {
160
+ const resolution = homeResolution();
161
+ if (!resolution.ok) {
162
+ throw new Error(`PD home resolution refused (${resolution.reason}): ${resolution.message} Next action: ${resolution.nextAction}`);
163
+ }
164
+ return path.resolve(resolution.homeDir);
165
+ };
166
+ /** Null-safe form for never-throw callers (maybeExportDaily, getStatus). */
167
+ const homePathsOrNull = () => {
168
+ const resolution = homeResolution();
169
+ return resolution.ok ? resolution : null;
170
+ };
171
+ /** Validated paths for layout consumers — reuses the ONE resolution (no re-parse). */
172
+ const requireHomePaths = () => {
173
+ const resolution = homeResolution();
174
+ if (!resolution.ok) {
175
+ throw new Error(`PD home resolution refused (${resolution.reason}): ${resolution.message} Next action: ${resolution.nextAction}`);
176
+ }
177
+ return resolution;
178
+ };
130
179
  const moduleDir = () => path.resolve(deps.moduleDir ?? DEFAULT_MODULE_DIR);
131
180
  const now = () => (deps.now ?? Date.now)();
132
181
  const logger = deps.logger ?? {};
133
- function environmentResult(workspaceDir) {
182
+ function environmentResult(workspaceDir, homePaths) {
134
183
  return computeTelemetryEnvironment({
135
184
  env: {
136
- killSwitch: env()[PD_TELEMETRY_DISABLED_ENV],
137
- ci: env().CI,
138
- vitest: env().VITEST,
139
- e2eMode: env().PD_E2E_MODE,
185
+ killSwitch: resolvedEnv[PD_TELEMETRY_DISABLED_ENV],
186
+ ci: resolvedEnv.CI,
187
+ vitest: resolvedEnv.VITEST,
188
+ e2eMode: resolvedEnv.PD_E2E_MODE,
140
189
  },
141
190
  workspaceEnvironment: workspaceEnvironmentOf(workspaceDir),
142
- installMode: resolveInstallContext(homeDir()).installMode,
191
+ installMode: resolveInstallContext(homePaths).installMode,
143
192
  moduleDir: moduleDir(),
144
193
  });
145
194
  }
146
- function gatesFor(state, workspaceDir) {
195
+ function gatesFor(state, workspaceDir, homePaths) {
147
196
  let flagEnabled = null;
148
197
  let flagSource = null;
149
198
  if (workspaceDir) {
@@ -151,7 +200,7 @@ export function createProductTelemetryService(deps = {}) {
151
200
  flagEnabled = flag.enabled;
152
201
  flagSource = flag.source;
153
202
  }
154
- const environment = environmentResult(workspaceDir);
203
+ const environment = environmentResult(workspaceDir, homePaths);
155
204
  const blockers = [];
156
205
  if (flagEnabled === null)
157
206
  blockers.push('feature_flag_unresolved');
@@ -186,10 +235,19 @@ export function createProductTelemetryService(deps = {}) {
186
235
  return {
187
236
  /** Status for `pd telemetry status`. Never exposes the secret. */
188
237
  getStatus(workspaceDir) {
238
+ const homePaths = homePathsOrNull();
239
+ if (homePaths === null) {
240
+ const refused = homeResolution();
241
+ return {
242
+ ok: false,
243
+ reason: `pd_home_unresolved:${refused.ok === false ? refused.reason : 'unknown'}`,
244
+ nextAction: refused.ok ? 'Resolve the PD home environment and re-run.' : `${refused.message} Next action: ${refused.nextAction}`,
245
+ };
246
+ }
189
247
  const read = readProductTelemetryControlState(homeDir());
190
248
  if (!read.ok)
191
249
  return read;
192
- const gates = gatesFor(read.state, workspaceDir);
250
+ const gates = gatesFor(read.state, workspaceDir, homePaths);
193
251
  // Export bookkeeping is workspace-scoped: show this workspace's entry
194
252
  // (when a workspace was given and its scope can be derived).
195
253
  let workspaceEntry;
@@ -215,7 +273,7 @@ export function createProductTelemetryService(deps = {}) {
215
273
  preview(workspaceDir) {
216
274
  const read = readProductTelemetryControlState(homeDir());
217
275
  const state = read.ok ? read.state : defaultProductTelemetryControlState();
218
- const gates = gatesFor(state, workspaceDir);
276
+ const gates = gatesFor(state, workspaceDir, requireHomePaths());
219
277
  const timestamp = now();
220
278
  const bucketDate = bucketDateFromTime(timestamp);
221
279
  const secretEphemeral = !isValidTelemetrySecretHex(state.telemetrySecret);
@@ -224,7 +282,7 @@ export function createProductTelemetryService(deps = {}) {
224
282
  // the ID would differ after enable.
225
283
  const secret = state.telemetrySecret ?? '0'.repeat(64);
226
284
  const scopeKey = workspaceScopeIdFor(secret, workspaceDir);
227
- const install = resolveInstallContext(homeDir());
285
+ const install = resolveInstallContext(requireHomePaths());
228
286
  const { facts, notes } = readMilestoneFacts(workspaceDir);
229
287
  const snapshot = buildProductTelemetrySnapshot({
230
288
  dailyTelemetryId: deriveDailyTelemetryId(secret, scopeKey, bucketDate),
@@ -324,13 +382,21 @@ export function createProductTelemetryService(deps = {}) {
324
382
  * EXPORT_LOCK_STALE_MS.
325
383
  */
326
384
  async maybeExportDaily(workspaceDir) {
385
+ // §6 never-throws contract: a refused PD Home is a STRUCTURED skip, not
386
+ // a throw — and never a fallback to the production home.
387
+ const homePaths = homePathsOrNull();
388
+ if (homePaths === null) {
389
+ const refused = homeResolution();
390
+ logger.warn?.(`[PD:Telemetry] Export skipped: PD home resolution refused (${refused.ok === false ? refused.reason : 'unknown'}).`);
391
+ return { attempted: false, skipReason: `pd_home_unresolved:${refused.ok === false ? refused.reason : 'unknown'}` };
392
+ }
327
393
  const read = readProductTelemetryControlState(homeDir());
328
394
  if (!read.ok) {
329
395
  logger.warn?.(`[PD:Telemetry] Export skipped: ${read.reason}`);
330
396
  return { attempted: false, skipReason: 'control_state_unreadable' };
331
397
  }
332
398
  const { state } = read;
333
- const gates = gatesFor(state, workspaceDir);
399
+ const gates = gatesFor(state, workspaceDir, homePaths);
334
400
  if (!gates.flagEnabled)
335
401
  return { attempted: false, skipReason: 'feature_flag_disabled' };
336
402
  if (state.consent !== 'granted')
@@ -383,7 +449,7 @@ export function createProductTelemetryService(deps = {}) {
383
449
  return { attempted: false, skipReason: 'already_succeeded_today' };
384
450
  }
385
451
  }
386
- const install = resolveInstallContext(homeDir());
452
+ const install = resolveInstallContext(requireHomePaths());
387
453
  const { facts } = readMilestoneFacts(workspaceDir);
388
454
  const snapshot = buildProductTelemetrySnapshot({
389
455
  dailyTelemetryId: deriveDailyTelemetryId(secret, scopeKey, bucketDate),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@principles/host-runtime",
3
- "version": "4.3.1",
3
+ "version": "4.5.0",
4
4
  "description": "Shared host-neutral orchestration for Principles Disciple MVP-Core hook paths.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -35,8 +35,8 @@
35
35
  "lint": "eslint \"src/**/*.ts\""
36
36
  },
37
37
  "dependencies": {
38
- "@principles/core": "^7.10.0",
39
- "@principles/install-layout": "^0.8.2",
38
+ "@principles/core": "^8.0.0",
39
+ "@principles/install-layout": "^0.9.0",
40
40
  "better-sqlite3": "^13.0.3",
41
41
  "js-yaml": "^5.4.3"
42
42
  },
@@ -53,5 +53,5 @@
53
53
  "url": "git+https://github.com/csuzngjh/principles.git"
54
54
  },
55
55
  "license": "Apache-2.0",
56
- "gitHead": "5ebfebcc384368a6f68f62fdd539507a03fd1d4a"
56
+ "gitHead": "95de4c633aedd4d588286c665baf3af816f6250a"
57
57
  }