create-principles-disciple 1.147.14 → 1.147.17

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 (82) hide show
  1. package/_release/product-identity.json +2 -2
  2. package/codex-adapter/package.json +1 -1
  3. package/console/dist/server/models/ActivationsConsoleModel.js +9 -3
  4. package/console/dist/server/models/ApprovalsConsoleModel.js +35 -6
  5. package/console/dist/server/models/ApprovalsGroupedConsoleModel.js +42 -2
  6. package/console/dist/shared/prompt-injection-contract.d.ts +31 -4
  7. package/console/dist/web/assets/app.css +4 -0
  8. package/console/dist/web/assets/app.js +25 -25
  9. package/core/dist/runtime/activation/index.d.ts +1 -1
  10. package/core/dist/runtime/activation/index.d.ts.map +1 -1
  11. package/core/dist/runtime/activation/index.js +4 -1
  12. package/core/dist/runtime/activation/index.js.map +1 -1
  13. package/core/dist/runtime/activation/prompt-activation-reader-contract.d.ts +20 -0
  14. package/core/dist/runtime/activation/prompt-activation-reader-contract.d.ts.map +1 -1
  15. package/core/dist/runtime/activation/prompt-activation-reader-contract.js +86 -27
  16. package/core/dist/runtime/activation/prompt-activation-reader-contract.js.map +1 -1
  17. package/core/dist/runtime/feature-flags/feature-flag-contract.d.ts.map +1 -1
  18. package/core/dist/runtime/feature-flags/feature-flag-contract.js +6 -1
  19. package/core/dist/runtime/feature-flags/feature-flag-contract.js.map +1 -1
  20. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.d.ts.map +1 -1
  21. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js +0 -8
  22. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js.map +1 -1
  23. package/core/dist/runtime/index.d.ts +3 -3
  24. package/core/dist/runtime/index.d.ts.map +1 -1
  25. package/core/dist/runtime/index.js +4 -2
  26. package/core/dist/runtime/index.js.map +1 -1
  27. package/core/dist/runtime/types/event-types.d.ts +62 -3
  28. package/core/dist/runtime/types/event-types.d.ts.map +1 -1
  29. package/core/dist/runtime/types/event-types.js +43 -0
  30. package/core/dist/runtime/types/event-types.js.map +1 -1
  31. package/core/package.json +1 -1
  32. package/dist/mvp-config.d.ts +4 -0
  33. package/dist/mvp-config.d.ts.map +1 -1
  34. package/dist/mvp-config.js +4 -0
  35. package/dist/mvp-config.js.map +1 -1
  36. package/host-runtime/dist/active-principle-prompt.d.ts +111 -2
  37. package/host-runtime/dist/active-principle-prompt.js +168 -41
  38. package/host-runtime/dist/adaptive-principle-revalidation.js +1 -1
  39. package/host-runtime/dist/index.d.ts +10 -0
  40. package/host-runtime/dist/index.js +31 -13
  41. package/host-runtime/dist/product-telemetry/consent-store.d.ts +112 -14
  42. package/host-runtime/dist/product-telemetry/consent-store.js +343 -132
  43. package/host-runtime/dist/product-telemetry/control-state-lock.d.ts +99 -0
  44. package/host-runtime/dist/product-telemetry/control-state-lock.js +320 -0
  45. package/host-runtime/dist/product-telemetry/service.d.ts +26 -9
  46. package/host-runtime/dist/product-telemetry/service.js +90 -150
  47. package/host-runtime/dist/prompt-activation-deliverability.d.ts +25 -15
  48. package/host-runtime/dist/prompt-activation-deliverability.js +60 -30
  49. package/host-runtime/dist/prompt-injection-projection.d.ts +105 -48
  50. package/host-runtime/dist/prompt-injection-projection.js +190 -212
  51. package/host-runtime/dist/prompt-injection-status.js +16 -7
  52. package/host-runtime/dist/signal-stage2-cycle.js +8 -1
  53. package/host-runtime/package.json +1 -1
  54. package/package.json +3 -3
  55. package/pd-cli/dist/commands/runtime-activation.d.ts.map +1 -1
  56. package/pd-cli/dist/commands/runtime-activation.js +4 -0
  57. package/pd-cli/dist/commands/runtime-activation.js.map +1 -1
  58. package/pd-cli/dist/commands/telemetry.d.ts.map +1 -1
  59. package/pd-cli/dist/commands/telemetry.js +3 -1
  60. package/pd-cli/dist/commands/telemetry.js.map +1 -1
  61. package/pd-cli/package.json +1 -1
  62. package/plugin/dist/bundle.js +487 -490
  63. package/plugin/dist/core/event-log.d.ts +8 -1
  64. package/plugin/dist/core/signal-collector-host.d.ts +27 -7
  65. package/plugin/dist/governance-audit.js +2 -2
  66. package/plugin/dist/hooks/llm-input-presence.d.ts +42 -0
  67. package/plugin/dist/hooks/prompt-presence-expectations.d.ts +74 -0
  68. package/plugin/dist/hooks/prompt-presence-lite.d.ts +53 -0
  69. package/plugin/dist/hooks/prompt-presence-measure.d.mts +1 -0
  70. package/plugin/dist/hooks/prompt-presence-registry.d.ts +150 -0
  71. package/plugin/dist/hooks/prompt.d.ts +40 -0
  72. package/plugin/dist/host-runtime/openclaw-host-runtime.d.ts +24 -1
  73. package/plugin/dist/index.d.ts +16 -9
  74. package/plugin/dist/openclaw-sdk.d.ts +33 -0
  75. package/plugin/dist/openclaw.plugin.json +1 -1
  76. package/plugin/dist/types/event-types.d.ts +1 -1
  77. package/plugin/openclaw.plugin.json +1 -1
  78. package/plugin/package.json +1 -1
  79. package/release-manager/dist/mvp-config.js +4 -0
  80. package/release-manager/package.json +1 -1
  81. package/workbuddy-adapter/package.json +1 -1
  82. package/workbuddy-adapter/plugin/.codebuddy-plugin/plugin.json +1 -1
@@ -14,18 +14,41 @@
14
14
  * (HMAC(secret, canonical workspace path); never uploaded). One
15
15
  * workspace succeeding must never suppress another workspace's export.
16
16
  *
17
- * Migration from schema v1: consent, consentVersion, and telemetrySecret are
18
- * preserved; legacy machine-global export bookkeeping (lastSucceededAt,
19
- * retry state, attempt counters) is DISCARDED — it cannot be attributed to a
20
- * workspace, and it is operational state, not a governance fact. Dropping it
21
- * can cause at most one extra same-day snapshot per installation.
17
+ * Single-format contract (PRI-1138, 6th dual-track convergence):
18
+ * - The ONLY writable/persisted format is the current schema version.
19
+ * writeProductTelemetryControlState refuses every state whose
20
+ * schemaVersion is not current, so no code path can persist or
21
+ * regenerate a legacy v1 file.
22
+ * - Legacy v1 files remain readable through migrateLegacyConsentFile — a
23
+ * one-way, read-only migrator (legacy reader / one-way migrator, never a
24
+ * writer). A read parses a v1 file in memory (identity preserved) but
25
+ * NEVER writes; persistence of the migration happens exclusively inside
26
+ * withControlStateLock transactions (PRI-1151): the legacy v1→v2
27
+ * migration write-back, enable/disable/reset, and workspace export
28
+ * bookkeeping merges all serialize on the same cross-process
29
+ * `<state>.state-lock`, so no writer can build its write from a stale
30
+ * read or overwrite a completed authorization change.
31
+ * - Migration from schema v1: consent, consentVersion, and telemetrySecret
32
+ * are preserved verbatim; legacy machine-global export bookkeeping
33
+ * (lastSucceededAt, retry state, attempt counters) is DISCARDED — it
34
+ * cannot be attributed to a workspace, and it is operational state, not a
35
+ * governance fact. Dropping it can cause at most one extra same-day
36
+ * snapshot per eligible workspace on the machine (each workspace re-exports
37
+ * once before its own fresh bookkeeping exists).
22
38
  */
23
39
  import fs from 'node:fs';
24
40
  import path from 'node:path';
25
41
  import { generateTelemetrySecretHex, isValidBucketDate, isValidTelemetrySecretHex, PRODUCT_TELEMETRY_CONSENT_VERSION, } from '@principles/core/runtime';
42
+ import { acquireExclusiveLock, ownsExclusiveLock, releaseExclusiveLock } from './control-state-lock.js';
26
43
  export const PRODUCT_TELEMETRY_STATE_FILENAME = 'product-telemetry.json';
44
+ /** The ONE writable schema version (single-format contract, PRI-1138). */
27
45
  export const PRODUCT_TELEMETRY_CONTROL_SCHEMA_VERSION = '2';
28
- /** v1 files are still read (then migrated in memory and rewritten as v2). */
46
+ /**
47
+ * Legacy schema v1 — LEGACY-READER SEMANTICS ONLY (PRI-1138): this constant
48
+ * exists solely so the one-way migrator can recognize historical files. It
49
+ * is never a writable target; writeProductTelemetryControlState refuses
50
+ * every state whose schemaVersion is not PRODUCT_TELEMETRY_CONTROL_SCHEMA_VERSION.
51
+ */
29
52
  export const PRODUCT_TELEMETRY_LEGACY_CONTROL_SCHEMA_VERSION = '1';
30
53
  /** Hard bound on tracked workspaces so the file cannot grow unboundedly. */
31
54
  export const MAX_WORKSPACE_EXPORT_ENTRIES = 200;
@@ -92,17 +115,219 @@ function workspaceExportErrors(entry, prefix) {
92
115
  function isPlainRecord(value) {
93
116
  return typeof value === 'object' && value !== null && !Array.isArray(value);
94
117
  }
118
+ /** The single field whitelist of the current persisted format. */
119
+ const CURRENT_ALLOWED_KEYS = ['consent', 'consentVersion', 'telemetrySecret', 'workspaceExports', 'schemaVersion'];
120
+ /**
121
+ * Field whitelist of the LEGACY v1 reader only: identity fields plus the
122
+ * retired machine-global export bookkeeping names. Used exclusively inside
123
+ * the legacy branch of parseConsentState to recognize historical files —
124
+ * never for the current format, and never a write shape (those top-level
125
+ * bookkeeping fields are discarded by migrateLegacyConsentFile; no
126
+ * production logic reads them).
127
+ */
128
+ const LEGACY_V1_ALLOWED_KEYS = [
129
+ 'consent',
130
+ 'consentVersion',
131
+ 'telemetrySecret',
132
+ 'lastAttemptedAt',
133
+ 'lastSucceededAt',
134
+ 'lastFailureCode',
135
+ 'nextRetryAt',
136
+ 'dailyAttemptCount',
137
+ 'attemptBucketDate',
138
+ 'schemaVersion',
139
+ ];
140
+ /**
141
+ * One-way migrator for legacy schema-v1 control files — legacy reader /
142
+ * one-way migrator, never a writer (PRI-1138). Accepts only objects already
143
+ * validated against LEGACY_V1_ALLOWED_KEYS by parseConsentState. The
144
+ * historical authorization identity is carried over VERBATIM — consent,
145
+ * consentVersion, and telemetrySecret are never reset, regenerated, or
146
+ * fabricated — while the retired machine-global export bookkeeping is
147
+ * dropped (it cannot be attributed to a workspace; operational state, not a
148
+ * governance fact). This function never touches the filesystem and never
149
+ * logs the secret; persisting its result happens exclusively through
150
+ * writeProductTelemetryControlState (the normal atomic write).
151
+ */
152
+ function migrateLegacyConsentFile(parsed) {
153
+ // Post-validation reconstruction from guard-narrowed fields — no `as` on
154
+ // the untrusted parsed object (rc-2). The ternary fallbacks are
155
+ // unreachable after parseConsentState's validation and mirror the
156
+ // defensive reconstruction style of the current-format path.
157
+ return {
158
+ consent: isConsent(parsed.consent) ? parsed.consent : 'unset',
159
+ consentVersion: typeof parsed.consentVersion === 'string' ? parsed.consentVersion : PRODUCT_TELEMETRY_CONSENT_VERSION,
160
+ ...(isValidTelemetrySecretHex(parsed.telemetrySecret) ? { telemetrySecret: parsed.telemetrySecret } : {}),
161
+ schemaVersion: PRODUCT_TELEMETRY_CONTROL_SCHEMA_VERSION,
162
+ };
163
+ }
164
+ /**
165
+ * Reconstruct the current-format state from guard-narrowed fields — no `as`
166
+ * on the untrusted parsed object (rc-2). isConsent is a type guard; the
167
+ * optional-field spreads carry only guard-passing values.
168
+ */
169
+ function reconstructCurrentState(obj) {
170
+ const state = {
171
+ consent: isConsent(obj.consent) ? obj.consent : 'unset',
172
+ consentVersion: typeof obj.consentVersion === 'string' ? obj.consentVersion : PRODUCT_TELEMETRY_CONSENT_VERSION,
173
+ ...(isValidTelemetrySecretHex(obj.telemetrySecret) ? { telemetrySecret: obj.telemetrySecret } : {}),
174
+ ...(isPlainRecord(obj.workspaceExports)
175
+ ? {
176
+ workspaceExports: Object.fromEntries(Object.entries(obj.workspaceExports)
177
+ .filter(([scopeKey, entry]) => isScopeKey(scopeKey) && isPlainRecord(entry))
178
+ .map(([scopeKey, entry]) => {
179
+ const record = entry;
180
+ return [
181
+ scopeKey,
182
+ {
183
+ ...(isOptionalIsoString(record.lastAttemptedAt) && record.lastAttemptedAt !== undefined ? { lastAttemptedAt: record.lastAttemptedAt } : {}),
184
+ ...(isOptionalIsoString(record.lastSucceededAt) && record.lastSucceededAt !== undefined ? { lastSucceededAt: record.lastSucceededAt } : {}),
185
+ ...(isOptionalIsoString(record.nextRetryAt) && record.nextRetryAt !== undefined ? { nextRetryAt: record.nextRetryAt } : {}),
186
+ ...(isOptionalFailureCode(record.lastFailureCode) && record.lastFailureCode !== undefined ? { lastFailureCode: record.lastFailureCode } : {}),
187
+ ...(isOptionalAttemptCount(record.dailyAttemptCount) && record.dailyAttemptCount !== undefined ? { dailyAttemptCount: record.dailyAttemptCount } : {}),
188
+ ...(isOptionalAttemptBucketDate(record.attemptBucketDate) && record.attemptBucketDate !== undefined ? { attemptBucketDate: record.attemptBucketDate } : {}),
189
+ },
190
+ ];
191
+ })),
192
+ }
193
+ : {}),
194
+ schemaVersion: PRODUCT_TELEMETRY_CONTROL_SCHEMA_VERSION,
195
+ };
196
+ if (state.workspaceExports !== undefined && Object.keys(state.workspaceExports).length === 0) {
197
+ delete state.workspaceExports;
198
+ }
199
+ return state;
200
+ }
95
201
  /**
96
- * Read and validate the control state. A missing file is the normal
97
- * never-configured case (defaults, existed=false). A malformed file is a
98
- * loud failure — silently treating it as "unset" could re-prompt or re-export
99
- * against the user's recorded decision (rc-3/rc-9).
202
+ * parseConsentState — the ONE parse entry for the persisted control state
203
+ * (PRI-1138). Current-format files validate against the single current
204
+ * whitelist; legacy v1 files go through the one-way migrator path and are
205
+ * flagged migratedFromLegacy so the caller persists the migration exactly
206
+ * once. Every other shape — missing, malformed, or future schemaVersion —
207
+ * fails loud: versions are never guessed and invalid data is never silently
208
+ * treated as an empty/default consent state.
209
+ */
210
+ function parseConsentState(parsed) {
211
+ if (!isPlainRecord(parsed)) {
212
+ return { ok: false, errors: ['state must be a JSON object'] };
213
+ }
214
+ const obj = parsed;
215
+ const { schemaVersion } = obj;
216
+ const isLegacyV1 = schemaVersion === PRODUCT_TELEMETRY_LEGACY_CONTROL_SCHEMA_VERSION;
217
+ const isCurrent = schemaVersion === PRODUCT_TELEMETRY_CONTROL_SCHEMA_VERSION;
218
+ if (!isLegacyV1 && !isCurrent) {
219
+ return {
220
+ ok: false,
221
+ errors: [
222
+ `schemaVersion must be '${PRODUCT_TELEMETRY_CONTROL_SCHEMA_VERSION}' or legacy '${PRODUCT_TELEMETRY_LEGACY_CONTROL_SCHEMA_VERSION}'`,
223
+ ],
224
+ };
225
+ }
226
+ const allowedKeys = isLegacyV1 ? LEGACY_V1_ALLOWED_KEYS : CURRENT_ALLOWED_KEYS;
227
+ const errors = [];
228
+ for (const key of Object.keys(obj)) {
229
+ if (!allowedKeys.includes(key)) {
230
+ errors.push(`unknown field '${key}'`);
231
+ }
232
+ }
233
+ if (!isConsent(obj.consent))
234
+ errors.push('consent must be unset|granted|denied');
235
+ if (typeof obj.consentVersion !== 'string' || obj.consentVersion.length === 0 || obj.consentVersion.length > 8)
236
+ errors.push('consentVersion must be a short non-empty string');
237
+ if (!isValidTelemetrySecretHex(obj.telemetrySecret) && obj.telemetrySecret !== undefined)
238
+ errors.push('telemetrySecret must be 64 hex chars when present');
239
+ if (isLegacyV1) {
240
+ // Legacy machine-global export fields are migrated by DISCARDING them —
241
+ // validating values that are about to be dropped would only turn a
242
+ // smooth migration into a hard failure (the identity fields carry the
243
+ // user's decision). Only the field-NAME allowlist above still applies to
244
+ // legacy files.
245
+ if (errors.length > 0)
246
+ return { ok: false, errors };
247
+ return { ok: true, state: migrateLegacyConsentFile(obj), migratedFromLegacy: true };
248
+ }
249
+ if (obj.workspaceExports !== undefined) {
250
+ if (typeof obj.workspaceExports !== 'object' || obj.workspaceExports === null || Array.isArray(obj.workspaceExports)) {
251
+ errors.push('workspaceExports must be an object');
252
+ }
253
+ else {
254
+ const entries = obj.workspaceExports;
255
+ const scopeKeys = Object.keys(entries);
256
+ if (scopeKeys.length > MAX_WORKSPACE_EXPORT_ENTRIES) {
257
+ errors.push(`workspaceExports must track at most ${MAX_WORKSPACE_EXPORT_ENTRIES} workspaces`);
258
+ }
259
+ for (const scopeKey of scopeKeys) {
260
+ if (!isScopeKey(scopeKey)) {
261
+ errors.push(`workspaceExports key '${scopeKey}' must be 4–32 hex chars`);
262
+ continue;
263
+ }
264
+ const entry = entries[scopeKey];
265
+ if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {
266
+ errors.push(`workspaceExports['${scopeKey}'] must be an object`);
267
+ continue;
268
+ }
269
+ errors.push(...workspaceExportErrors(entry, `workspaceExports['${scopeKey}']`));
270
+ }
271
+ }
272
+ }
273
+ if (errors.length > 0)
274
+ return { ok: false, errors };
275
+ return { ok: true, state: reconstructCurrentState(obj), migratedFromLegacy: false };
276
+ }
277
+ /**
278
+ * Atomic write (temp file + rename) so a crash never truncates the state.
100
279
  *
101
- * v1 files are migrated in memory (export bookkeeping dropped, consent
102
- * identity preserved); the migration is persisted on the next write.
280
+ * Single-format contract (PRI-1138): ONLY the current schema version is
281
+ * writable. This is the structural guarantee that no code path can persist
282
+ * or regenerate a legacy v1 file — a state carrying any other schemaVersion
283
+ * is refused loud and the file on disk is left untouched.
284
+ *
285
+ * Concurrency convention (PRI-1151): production read-modify-write callers
286
+ * must run inside withControlStateLock (tx.write) so their write is built
287
+ * from a read taken under the same cross-process mutex as every other
288
+ * writer; calling this function directly is for lock-held transaction
289
+ * internals and single-writer utilities.
103
290
  */
104
- export function readProductTelemetryControlState(homeDir) {
291
+ export function writeProductTelemetryControlState(homeDir, state) {
292
+ if (state.schemaVersion !== PRODUCT_TELEMETRY_CONTROL_SCHEMA_VERSION) {
293
+ return {
294
+ ok: false,
295
+ reason: `product_telemetry_state_write_refused: only schemaVersion '${PRODUCT_TELEMETRY_CONTROL_SCHEMA_VERSION}' is writable, got '${String(state.schemaVersion).slice(0, 16)}'`,
296
+ nextAction: 'Build states via defaultProductTelemetryControlState / grantedControlState / deniedControlState / resetControlState (schemaVersion is not a free choice)',
297
+ };
298
+ }
105
299
  const filePath = getProductTelemetryStatePath(homeDir);
300
+ const dir = path.dirname(filePath);
301
+ const tmpPath = `${filePath}.tmp-${process.pid}-${Date.now()}`;
302
+ try {
303
+ fs.mkdirSync(dir, { recursive: true });
304
+ fs.writeFileSync(tmpPath, `${JSON.stringify(state, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
305
+ fs.renameSync(tmpPath, filePath);
306
+ return { ok: true };
307
+ }
308
+ catch (error) {
309
+ const message = error instanceof Error ? error.message : String(error);
310
+ try {
311
+ fs.rmSync(tmpPath, { force: true });
312
+ }
313
+ catch {
314
+ // best-effort cleanup; the write failure below is the loud signal
315
+ }
316
+ return {
317
+ ok: false,
318
+ reason: `product_telemetry_state_write_failed: ${message}`,
319
+ nextAction: `Check permissions on ${dir}`,
320
+ };
321
+ }
322
+ }
323
+ /**
324
+ * Read the raw bytes from disk and parse them — pure, no write, no lock.
325
+ * A missing file is the normal never-configured case (defaults,
326
+ * existed=false, diskSchemaVersion '2'). A malformed file is a loud failure
327
+ * — silently treating it as "unset" could re-prompt or re-export against the
328
+ * user's recorded decision (rc-3/rc-9).
329
+ */
330
+ function loadControlStateFromDisk(filePath) {
106
331
  let raw;
107
332
  try {
108
333
  raw = fs.readFileSync(filePath, 'utf8');
@@ -115,7 +340,7 @@ export function readProductTelemetryControlState(homeDir) {
115
340
  : undefined;
116
341
  const code = typeof codeValue === 'string' ? codeValue : undefined;
117
342
  if (code === 'ENOENT') {
118
- return { ok: true, state: defaultProductTelemetryControlState(), existed: false };
343
+ return { ok: true, state: defaultProductTelemetryControlState(), existed: false, diskSchemaVersion: PRODUCT_TELEMETRY_CONTROL_SCHEMA_VERSION };
119
344
  }
120
345
  return {
121
346
  ok: false,
@@ -134,114 +359,126 @@ export function readProductTelemetryControlState(homeDir) {
134
359
  nextAction: `Fix or delete ${filePath} (delete = consent returns to unset)`,
135
360
  };
136
361
  }
137
- if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
362
+ const result = parseConsentState(parsed);
363
+ if (!result.ok) {
138
364
  return {
139
365
  ok: false,
140
- reason: 'product_telemetry_state_malformed_shape',
366
+ reason: `product_telemetry_state_malformed: ${result.errors.join('; ')}`,
141
367
  nextAction: `Fix or delete ${filePath} (delete = consent returns to unset)`,
142
368
  };
143
369
  }
144
- const obj = parsed;
145
- const { schemaVersion } = obj;
146
- const isV1 = schemaVersion === PRODUCT_TELEMETRY_LEGACY_CONTROL_SCHEMA_VERSION;
147
- const isV2 = schemaVersion === PRODUCT_TELEMETRY_CONTROL_SCHEMA_VERSION;
148
- if (!isV1 && !isV2) {
370
+ return {
371
+ ok: true,
372
+ state: result.state,
373
+ existed: true,
374
+ diskSchemaVersion: result.migratedFromLegacy
375
+ ? PRODUCT_TELEMETRY_LEGACY_CONTROL_SCHEMA_VERSION
376
+ : PRODUCT_TELEMETRY_CONTROL_SCHEMA_VERSION,
377
+ };
378
+ }
379
+ /**
380
+ * Read and validate the control state — PURE READ, never writes (PRI-1151).
381
+ * A legacy v1 file is parsed in memory (identity preserved, bookkeeping
382
+ * dropped) so callers observe the migrated semantics, but persisting the
383
+ * migration happens exclusively inside withControlStateLock transactions;
384
+ * a read-only caller (status/preview) can therefore never race a concurrent
385
+ * authorization change.
386
+ */
387
+ export function readProductTelemetryControlState(homeDir) {
388
+ const loaded = loadControlStateFromDisk(getProductTelemetryStatePath(homeDir));
389
+ if (!loaded.ok)
390
+ return loaded;
391
+ return { ok: true, state: loaded.state, existed: loaded.existed };
392
+ }
393
+ /**
394
+ * withControlStateLock — the ONE cross-process transaction entry for the
395
+ * control state (PRI-1151): acquire `<state>.state-lock` → run the body with
396
+ * lock-held readLatest/write primitives → release. Every control-state
397
+ * writer (legacy migration write-back, enable/disable/reset, workspace
398
+ * bookkeeping merge) goes through here, so each write is built from a read
399
+ * taken under the same mutex that serializes every other writer — a stale
400
+ * read can no longer overwrite a completed authorization change (e.g. a
401
+ * concurrent disable).
402
+ *
403
+ * Failure semantics: lock acquisition is bounded and CONTENTION (timeout) is
404
+ * distinguished from a FILESYSTEM failure (e.g. unwritable directory); on
405
+ * either failure nothing was written (no lock-free degradation). A body that
406
+ * runs longer than the lock's stale threshold may find its lock taken over
407
+ * by another process — tx.write then refuses (lock_lost) instead of
408
+ * committing without the mutex. A throwing body releases the lock and
409
+ * returns a structured failure — this function never throws.
410
+ */
411
+ export async function withControlStateLock(homeDir, body, options) {
412
+ const stateFilePath = getProductTelemetryStatePath(homeDir);
413
+ const acquired = await acquireExclusiveLock(stateFilePath, options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : undefined);
414
+ if (!acquired.ok) {
415
+ if (acquired.kind === 'timeout') {
416
+ return {
417
+ ok: false,
418
+ reason: 'product_telemetry_state_lock_timeout: another process holds the control-state lock',
419
+ nextAction: 'Retry the operation; if it keeps failing, check for a stuck PD process before touching ~/.pd/product-telemetry.json.state-lock',
420
+ };
421
+ }
149
422
  return {
150
423
  ok: false,
151
- reason: `product_telemetry_state_malformed: schemaVersion must be '${PRODUCT_TELEMETRY_CONTROL_SCHEMA_VERSION}' or legacy '${PRODUCT_TELEMETRY_LEGACY_CONTROL_SCHEMA_VERSION}'`,
152
- nextAction: `Fix or delete ${filePath} (delete = consent returns to unset)`,
424
+ reason: `product_telemetry_state_lock_unwritable: ${acquired.detail}`,
425
+ nextAction: `Check permissions on ${path.dirname(stateFilePath)}`,
153
426
  };
154
427
  }
155
- // v1 machine-global export fields exist only in v1 files; v2 files carry
156
- // workspaceExports instead. Unknown keys are rejected per shape.
157
- const allowedKeys = isV1
158
- ? ['consent', 'consentVersion', 'telemetrySecret', 'lastAttemptedAt', 'lastSucceededAt', 'lastFailureCode', 'nextRetryAt', 'dailyAttemptCount', 'attemptBucketDate', 'schemaVersion']
159
- : ['consent', 'consentVersion', 'telemetrySecret', 'workspaceExports', 'schemaVersion'];
160
- const errors = [];
161
- for (const key of Object.keys(obj)) {
162
- if (!allowedKeys.includes(key)) {
163
- errors.push(`unknown field '${key}'`);
164
- }
165
- }
166
- if (!isConsent(obj.consent))
167
- errors.push('consent must be unset|granted|denied');
168
- if (typeof obj.consentVersion !== 'string' || obj.consentVersion.length === 0 || obj.consentVersion.length > 8)
169
- errors.push('consentVersion must be a short non-empty string');
170
- if (!isValidTelemetrySecretHex(obj.telemetrySecret) && obj.telemetrySecret !== undefined)
171
- errors.push('telemetrySecret must be 64 hex chars when present');
172
- if (isV1) {
173
- // v1 legacy export fields are migrated by DISCARDING them — validating
174
- // values that are about to be dropped would only turn a smooth migration
175
- // into a hard failure (the identity fields carry the user's decision).
176
- // Only the field-NAME allowlist above still applies to v1 files.
177
- }
178
- else {
179
- if (obj.workspaceExports !== undefined) {
180
- if (typeof obj.workspaceExports !== 'object' || obj.workspaceExports === null || Array.isArray(obj.workspaceExports)) {
181
- errors.push('workspaceExports must be an object');
182
- }
183
- else {
184
- const entries = obj.workspaceExports;
185
- const scopeKeys = Object.keys(entries);
186
- if (scopeKeys.length > MAX_WORKSPACE_EXPORT_ENTRIES) {
187
- errors.push(`workspaceExports must track at most ${MAX_WORKSPACE_EXPORT_ENTRIES} workspaces`);
188
- }
189
- for (const scopeKey of scopeKeys) {
190
- if (!isScopeKey(scopeKey)) {
191
- errors.push(`workspaceExports key '${scopeKey}' must be 4–32 hex chars`);
192
- continue;
193
- }
194
- const entry = entries[scopeKey];
195
- if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {
196
- errors.push(`workspaceExports['${scopeKey}'] must be an object`);
197
- continue;
198
- }
199
- errors.push(...workspaceExportErrors(entry, `workspaceExports['${scopeKey}']`));
428
+ const lock = acquired.handle;
429
+ try {
430
+ const tx = {
431
+ readLatest: () => loadControlStateFromDisk(stateFilePath),
432
+ write: (state) => {
433
+ // Ownership re-verify before committing: a body that outlived the
434
+ // stale threshold may have had its lock taken over — refuse instead
435
+ // of writing without the mutex (review round 2).
436
+ if (!ownsExclusiveLock(lock)) {
437
+ return {
438
+ ok: false,
439
+ reason: 'product_telemetry_state_lock_lost: another process took over the lock during this transaction; nothing was written',
440
+ nextAction: 'Retry the operation',
441
+ };
200
442
  }
201
- }
202
- }
443
+ return writeProductTelemetryControlState(homeDir, state);
444
+ },
445
+ };
446
+ const value = await body(tx);
447
+ return { ok: true, value };
203
448
  }
204
- if (errors.length > 0) {
449
+ catch (error) {
450
+ const message = error instanceof Error ? error.message : String(error);
205
451
  return {
206
452
  ok: false,
207
- reason: `product_telemetry_state_malformed: ${errors.join('; ')}`,
208
- nextAction: `Fix or delete ${filePath} (delete = consent returns to unset)`,
453
+ reason: `product_telemetry_state_transaction_error: ${message}`,
454
+ nextAction: 'Retry the operation; the control state on disk was not left half-written (atomic temp+rename)',
209
455
  };
210
456
  }
211
- // Post-validation reconstruction from guard-narrowed fields — no `as` on
212
- // the untrusted parsed object (rc-2). isConsent is a type guard; the
213
- // optional-field spreads carry only guard-passing values. v1 export
214
- // bookkeeping is deliberately NOT carried over (see module doc).
215
- const state = {
216
- consent: isConsent(obj.consent) ? obj.consent : 'unset',
217
- consentVersion: typeof obj.consentVersion === 'string' ? obj.consentVersion : PRODUCT_TELEMETRY_CONSENT_VERSION,
218
- ...(isValidTelemetrySecretHex(obj.telemetrySecret) ? { telemetrySecret: obj.telemetrySecret } : {}),
219
- ...(isV2 && isPlainRecord(obj.workspaceExports)
220
- ? {
221
- workspaceExports: Object.fromEntries(Object.entries(obj.workspaceExports)
222
- .filter(([scopeKey, entry]) => isScopeKey(scopeKey) && isPlainRecord(entry))
223
- .map(([scopeKey, entry]) => {
224
- const record = entry;
225
- return [
226
- scopeKey,
227
- {
228
- ...(isOptionalIsoString(record.lastAttemptedAt) && record.lastAttemptedAt !== undefined ? { lastAttemptedAt: record.lastAttemptedAt } : {}),
229
- ...(isOptionalIsoString(record.lastSucceededAt) && record.lastSucceededAt !== undefined ? { lastSucceededAt: record.lastSucceededAt } : {}),
230
- ...(isOptionalIsoString(record.nextRetryAt) && record.nextRetryAt !== undefined ? { nextRetryAt: record.nextRetryAt } : {}),
231
- ...(isOptionalFailureCode(record.lastFailureCode) && record.lastFailureCode !== undefined ? { lastFailureCode: record.lastFailureCode } : {}),
232
- ...(isOptionalAttemptCount(record.dailyAttemptCount) && record.dailyAttemptCount !== undefined ? { dailyAttemptCount: record.dailyAttemptCount } : {}),
233
- ...(isOptionalAttemptBucketDate(record.attemptBucketDate) && record.attemptBucketDate !== undefined ? { attemptBucketDate: record.attemptBucketDate } : {}),
234
- },
235
- ];
236
- })),
237
- }
238
- : {}),
239
- schemaVersion: PRODUCT_TELEMETRY_CONTROL_SCHEMA_VERSION,
240
- };
241
- if (state.workspaceExports !== undefined && Object.keys(state.workspaceExports).length === 0) {
242
- delete state.workspaceExports;
457
+ finally {
458
+ releaseExclusiveLock(lock);
243
459
  }
244
- return { ok: true, state, existed: true };
460
+ }
461
+ /**
462
+ * One-way legacy v1→v2 migration as a locked transaction (PRI-1151): read
463
+ * the CURRENT disk state under the lock; if it is still v1, persist the
464
+ * migrated state (identity preserved) through the normal atomic write; if it
465
+ * is already the current format, do nothing (idempotent — no rewrite). A
466
+ * concurrent disable/reset/enable serializes on the same lock, so this can
467
+ * never overwrite a completed authorization change.
468
+ */
469
+ export async function migrateLegacyControlState(homeDir) {
470
+ const outcome = await withControlStateLock(homeDir, (tx) => {
471
+ const latest = tx.readLatest();
472
+ if (!latest.ok)
473
+ return latest;
474
+ if (latest.diskSchemaVersion !== PRODUCT_TELEMETRY_LEGACY_CONTROL_SCHEMA_VERSION) {
475
+ return { ok: true };
476
+ }
477
+ return tx.write(latest.state);
478
+ });
479
+ if (!outcome.ok)
480
+ return outcome;
481
+ return outcome.value;
245
482
  }
246
483
  /**
247
484
  * Drop `workspaceExports` entries whose most recent activity (attempt or
@@ -268,32 +505,6 @@ export function pruneWorkspaceExports(state, nowMs) {
268
505
  delete next.workspaceExports;
269
506
  return next;
270
507
  }
271
- /** Atomic write (temp file + rename) so a crash never truncates the state. */
272
- export function writeProductTelemetryControlState(homeDir, state) {
273
- const filePath = getProductTelemetryStatePath(homeDir);
274
- const dir = path.dirname(filePath);
275
- const tmpPath = `${filePath}.tmp-${process.pid}-${Date.now()}`;
276
- try {
277
- fs.mkdirSync(dir, { recursive: true });
278
- fs.writeFileSync(tmpPath, `${JSON.stringify(state, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
279
- fs.renameSync(tmpPath, filePath);
280
- return { ok: true };
281
- }
282
- catch (error) {
283
- const message = error instanceof Error ? error.message : String(error);
284
- try {
285
- fs.rmSync(tmpPath, { force: true });
286
- }
287
- catch {
288
- // best-effort cleanup; the write failure below is the loud signal
289
- }
290
- return {
291
- ok: false,
292
- reason: `product_telemetry_state_write_failed: ${message}`,
293
- nextAction: `Check permissions on ${dir}`,
294
- };
295
- }
296
- }
297
508
  /** State after `pd telemetry enable`: explicit granted consent + secret. */
298
509
  export function grantedControlState(previous) {
299
510
  return {
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Cross-process exclusive lock for product-telemetry control-state
3
+ * read-modify-write transactions (PRI-1151).
4
+ *
5
+ * ONE lock file — `<state>.state-lock` — serializes every writer of
6
+ * `~/.pd/product-telemetry.json`: the legacy v1→v2 migration write-back,
7
+ * `pd telemetry enable/disable/reset`, and workspace export bookkeeping
8
+ * merges (see consent-store.withControlStateLock and the service layer).
9
+ *
10
+ * Protocol (ownership-checked, crash-recoverable, bounded wait):
11
+ *
12
+ * - Acquire = `open(path, 'wx')` with an owner body
13
+ * `<pid> <token> <createdAtISO>`; 'wx' creation is atomic, so exactly one
14
+ * of N simultaneous contenders wins. A create failure other than
15
+ * EEXIST (e.g. EACCES on an unwritable directory) is reported immediately
16
+ * as `unwritable` — never misreported as lock contention and never spun
17
+ * against until the timeout. If the body write/close fails after creation,
18
+ * the freshly created file (which no other process can have taken over —
19
+ * it is younger than the stale threshold) is removed before failing.
20
+ * - Stale takeover (crashed holder): only when the lock's mtime AND the
21
+ * renamed file's content match what we first observed as stale. The
22
+ * takeover itself is an atomic RENAME (claim), never a blind unlink — a
23
+ * lock that was replaced meanwhile (fresh mtime) is restored, so
24
+ * contenders can never delete a live holder's lock.
25
+ * - Release is ownership-checked the same way: rename the lock aside, delete
26
+ * it only if its body is still OURS; otherwise restore it. A late release
27
+ * by an already-taken-over (stale) holder therefore cannot delete the new
28
+ * holder's lock.
29
+ * - Ownership can be re-verified mid-transaction (ownsExclusiveLock): a
30
+ * transaction whose body ran longer than the stale threshold may find its
31
+ * lock taken over — its write must be refused (lock_lost) instead of
32
+ * committing without the mutex.
33
+ * - Acquisition waits asynchronously with a bounded deadline and returns a
34
+ * definitive failure result; it never degrades into lock-free writing.
35
+ * - Orphaned takeover/release sidecars (`.take-*` / `.rel-*`, left behind by
36
+ * a crash mid-rename) are swept by the next successful acquirer once they
37
+ * are older than the stale threshold — a sidecar that fresh may still be
38
+ * part of a live protocol step and is never touched.
39
+ *
40
+ * Residual, documented: between a stale holder's crash and the STALE_MS
41
+ * threshold the lock blocks (by design); the ultra-narrow window where a
42
+ * third create lands while a wrongly-renamed fresh lock is being restored
43
+ * parks the displaced body as an orphan sidecar that a later stale sweep
44
+ * cleans up — mutual exclusion itself is preserved by the 'wx' create point.
45
+ */
46
+ /** A lock older than this is treated as orphaned (holder crashed) and taken over. */
47
+ export declare const CONTROL_STATE_LOCK_STALE_MS: number;
48
+ /** Bounded acquisition wait; exceeding it returns not-acquired (loud, never silent). */
49
+ export declare const CONTROL_STATE_LOCK_TIMEOUT_MS: number;
50
+ export interface ExclusiveLockHandle {
51
+ lockPath: string;
52
+ /** Random per-acquisition token; identifies THIS holder inside the lock body. */
53
+ token: string;
54
+ /** The exact body we wrote (`<pid> <token> <createdAt>`); release checks it. */
55
+ body: string;
56
+ }
57
+ /** Acquisition outcome: success, bounded-timeout contention, or a filesystem error. */
58
+ export type AcquireExclusiveLockResult = {
59
+ ok: true;
60
+ handle: ExclusiveLockHandle;
61
+ } | {
62
+ ok: false;
63
+ kind: 'timeout';
64
+ } | {
65
+ ok: false;
66
+ kind: 'unwritable';
67
+ detail: string;
68
+ };
69
+ export declare function controlStateLockPath(stateFilePath: string): string;
70
+ /** Whether the lock file at `handle.lockPath` still carries OUR body. */
71
+ export declare function ownsExclusiveLock(handle: ExclusiveLockHandle): boolean;
72
+ /**
73
+ * Ownership-checked release: delete the lock only if its body is still OURS.
74
+ * A holder that was taken over after going stale cannot delete the new
75
+ * holder's lock — the displaced file is restored instead.
76
+ */
77
+ export declare function releaseExclusiveLock(handle: ExclusiveLockHandle): void;
78
+ /**
79
+ * Acquire the cross-process exclusive lock, waiting asynchronously with a
80
+ * bounded deadline. The result distinguishes bounded-timeout CONTENTION from
81
+ * a FILESYSTEM failure (e.g. an unwritable directory) — both are loud, and
82
+ * neither ever degrades into lock-free writing.
83
+ */
84
+ export declare function acquireExclusiveLock(stateFilePath: string, options?: {
85
+ lockPath?: string;
86
+ staleMs?: number;
87
+ timeoutMs?: number;
88
+ }): Promise<AcquireExclusiveLockResult>;
89
+ /**
90
+ * Synchronous one-shot variant for callers that must not await: tries to
91
+ * create the lock once, and takes over a stale lock via the same
92
+ * rename-claim protocol. Returns undefined when the lock is busy or cannot
93
+ * be created (the caller skips loudly — it must never write without the
94
+ * lock).
95
+ */
96
+ export declare function tryAcquireExclusiveLockSync(stateFilePath: string, options?: {
97
+ lockPath?: string;
98
+ staleMs?: number;
99
+ }): ExclusiveLockHandle | undefined;