create-principles-disciple 1.147.16 → 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 (37) hide show
  1. package/_release/product-identity.json +2 -2
  2. package/core/dist/runtime/index.d.ts +2 -2
  3. package/core/dist/runtime/index.d.ts.map +1 -1
  4. package/core/dist/runtime/index.js +1 -1
  5. package/core/dist/runtime/index.js.map +1 -1
  6. package/core/dist/runtime/types/event-types.d.ts +62 -3
  7. package/core/dist/runtime/types/event-types.d.ts.map +1 -1
  8. package/core/dist/runtime/types/event-types.js +43 -0
  9. package/core/dist/runtime/types/event-types.js.map +1 -1
  10. package/core/package.json +1 -1
  11. package/host-runtime/dist/active-principle-prompt.d.ts +24 -0
  12. package/host-runtime/dist/active-principle-prompt.js +36 -0
  13. package/host-runtime/dist/product-telemetry/consent-store.d.ts +112 -14
  14. package/host-runtime/dist/product-telemetry/consent-store.js +343 -132
  15. package/host-runtime/dist/product-telemetry/control-state-lock.d.ts +99 -0
  16. package/host-runtime/dist/product-telemetry/control-state-lock.js +320 -0
  17. package/host-runtime/dist/product-telemetry/service.d.ts +26 -9
  18. package/host-runtime/dist/product-telemetry/service.js +90 -150
  19. package/host-runtime/dist/signal-stage2-cycle.js +8 -1
  20. package/host-runtime/package.json +1 -1
  21. package/package.json +2 -2
  22. package/pd-cli/dist/commands/telemetry.d.ts.map +1 -1
  23. package/pd-cli/dist/commands/telemetry.js +3 -1
  24. package/pd-cli/dist/commands/telemetry.js.map +1 -1
  25. package/pd-cli/package.json +1 -1
  26. package/plugin/dist/bundle.js +429 -428
  27. package/plugin/dist/core/event-log.d.ts +8 -1
  28. package/plugin/dist/governance-audit.js +2 -2
  29. package/plugin/dist/hooks/llm-input-presence.d.ts +42 -0
  30. package/plugin/dist/hooks/prompt-presence-expectations.d.ts +6 -1
  31. package/plugin/dist/hooks/prompt-presence-lite.d.ts +53 -0
  32. package/plugin/dist/hooks/prompt-presence-measure.d.mts +1 -0
  33. package/plugin/dist/hooks/prompt-presence-registry.d.ts +150 -0
  34. package/plugin/dist/openclaw-sdk.d.ts +17 -0
  35. package/plugin/dist/openclaw.plugin.json +1 -1
  36. package/plugin/dist/types/event-types.d.ts +1 -1
  37. package/release-manager/package.json +1 -1
@@ -0,0 +1,320 @@
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
+ import fs from 'node:fs';
47
+ import path from 'node:path';
48
+ import { randomUUID } from 'node:crypto';
49
+ /** A lock older than this is treated as orphaned (holder crashed) and taken over. */
50
+ export const CONTROL_STATE_LOCK_STALE_MS = 5 * 1000;
51
+ /** Bounded acquisition wait; exceeding it returns not-acquired (loud, never silent). */
52
+ export const CONTROL_STATE_LOCK_TIMEOUT_MS = 3 * 1000;
53
+ const CONTROL_STATE_LOCK_POLL_MS = 15;
54
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
55
+ export function controlStateLockPath(stateFilePath) {
56
+ return `${stateFilePath}.state-lock`;
57
+ }
58
+ function lockBody(token) {
59
+ return `${process.pid} ${token} ${new Date().toISOString()}\n`;
60
+ }
61
+ function newToken() {
62
+ return randomUUID().replace(/-/g, '').slice(0, 16);
63
+ }
64
+ function readLockBody(filePath) {
65
+ try {
66
+ return fs.readFileSync(filePath, 'utf8');
67
+ }
68
+ catch {
69
+ return undefined;
70
+ }
71
+ }
72
+ /** Whether the lock file at `handle.lockPath` still carries OUR body. */
73
+ export function ownsExclusiveLock(handle) {
74
+ return readLockBody(handle.lockPath) === handle.body;
75
+ }
76
+ /**
77
+ * Atomic claim attempt: exactly one contender can create the file. EEXIST is
78
+ * contention ('busy'); any other failure (EACCES, ENOSPC, …) is an error. A
79
+ * failure of the body write/close AFTER a successful create removes the
80
+ * freshly created file — safe because it is younger than the stale
81
+ * threshold, so no other process can have taken it over yet.
82
+ */
83
+ function tryCreateExclusiveLock(lockPath, body) {
84
+ let fd;
85
+ try {
86
+ fd = fs.openSync(lockPath, 'wx');
87
+ fs.writeSync(fd, body);
88
+ fs.closeSync(fd);
89
+ fd = undefined;
90
+ return 'created';
91
+ }
92
+ catch (error) {
93
+ const code = typeof error === 'object' && error !== null && Object.hasOwn(error, 'code')
94
+ ? error.code
95
+ : undefined;
96
+ if (fd !== undefined) {
97
+ try {
98
+ fs.closeSync(fd);
99
+ }
100
+ catch {
101
+ // fd already closed or invalid
102
+ }
103
+ try {
104
+ fs.rmSync(lockPath, { force: true });
105
+ }
106
+ catch {
107
+ // orphan with our token; stale takeover cleans it later
108
+ }
109
+ }
110
+ if (code === 'EEXIST')
111
+ return 'busy';
112
+ const message = error instanceof Error ? error.message : String(error);
113
+ return { error: `${typeof code === 'string' ? code : ''} ${message}`.trim() };
114
+ }
115
+ }
116
+ /**
117
+ * Best-effort sweep of orphaned takeover/release sidecars, run by the
118
+ * SUCCESSFUL acquirer (it owns the directory's lock protocol for this
119
+ * instant). Only sidecars older than the stale threshold are removed — one
120
+ * that fresh may still belong to a live protocol step in another process.
121
+ */
122
+ function sweepOrphanSidecars(lockPath, staleMs) {
123
+ const dir = path.dirname(lockPath);
124
+ const base = path.basename(lockPath);
125
+ let entries;
126
+ try {
127
+ entries = fs.readdirSync(dir);
128
+ }
129
+ catch {
130
+ return;
131
+ }
132
+ for (const entry of entries) {
133
+ if (!entry.startsWith(`${base}.take-`) && !entry.startsWith(`${base}.rel-`))
134
+ continue;
135
+ const sidecar = path.join(dir, entry);
136
+ try {
137
+ if (fs.statSync(sidecar).mtimeMs >= Date.now() - staleMs)
138
+ continue;
139
+ fs.rmSync(sidecar, { force: true });
140
+ }
141
+ catch {
142
+ // best effort; a failed sweep never blocks locking
143
+ }
144
+ }
145
+ }
146
+ /**
147
+ * Take over a stale lock via atomic rename-claim. Valid only when the
148
+ * renamed file's mtime is stale AND its body is the one we observed — a
149
+ * lock replaced meanwhile (fresh mtime, different owner) is restored, never
150
+ * deleted. Returns true when the stale lock was removed and the caller
151
+ * should retry creation.
152
+ */
153
+ function takeOverStaleExclusiveLock(args) {
154
+ const { lockPath, staleBody, sidecarToken, staleMs } = args;
155
+ const takePath = `${lockPath}.take-${sidecarToken}`;
156
+ try {
157
+ fs.renameSync(lockPath, takePath);
158
+ }
159
+ catch {
160
+ return false; // vanished or raced; the normal create/retry path decides
161
+ }
162
+ let takeStat;
163
+ try {
164
+ takeStat = fs.statSync(takePath);
165
+ }
166
+ catch {
167
+ return false;
168
+ }
169
+ const takeBody = readLockBody(takePath);
170
+ if (takeStat.mtimeMs < Date.now() - staleMs && takeBody === staleBody) {
171
+ // Exactly the stale lock we intended to remove.
172
+ try {
173
+ fs.rmSync(takePath, { force: true });
174
+ }
175
+ catch {
176
+ // orphan sidecar; harmless (a later stale sweep cleans it)
177
+ }
178
+ return true;
179
+ }
180
+ // We grabbed a lock that was replaced meanwhile (a live holder). Restore
181
+ // it so mutual exclusion is preserved; never delete a lock we do not own.
182
+ try {
183
+ if (!fs.existsSync(lockPath))
184
+ fs.renameSync(takePath, lockPath);
185
+ // else: a new create already landed; leave the displaced body parked at
186
+ // takePath (orphan sidecar). The newly created lock governs.
187
+ }
188
+ catch {
189
+ // restore best-effort; the parked file becomes a stale-cleanable orphan
190
+ }
191
+ return false;
192
+ }
193
+ /**
194
+ * Ownership-checked release: delete the lock only if its body is still OURS.
195
+ * A holder that was taken over after going stale cannot delete the new
196
+ * holder's lock — the displaced file is restored instead.
197
+ */
198
+ export function releaseExclusiveLock(handle) {
199
+ const relPath = `${handle.lockPath}.rel-${handle.token}`;
200
+ try {
201
+ fs.renameSync(handle.lockPath, relPath);
202
+ }
203
+ catch {
204
+ return; // already gone; nothing to release
205
+ }
206
+ if (readLockBody(relPath) === handle.body) {
207
+ try {
208
+ fs.rmSync(relPath, { force: true });
209
+ }
210
+ catch {
211
+ // orphan sidecar; harmless
212
+ }
213
+ return;
214
+ }
215
+ // Not ours (we were taken over after going stale). Restore it — never
216
+ // delete a lock another process owns.
217
+ try {
218
+ if (!fs.existsSync(handle.lockPath))
219
+ fs.renameSync(relPath, handle.lockPath);
220
+ }
221
+ catch {
222
+ // best-effort restore
223
+ }
224
+ }
225
+ /**
226
+ * Acquire the cross-process exclusive lock, waiting asynchronously with a
227
+ * bounded deadline. The result distinguishes bounded-timeout CONTENTION from
228
+ * a FILESYSTEM failure (e.g. an unwritable directory) — both are loud, and
229
+ * neither ever degrades into lock-free writing.
230
+ */
231
+ export async function acquireExclusiveLock(stateFilePath, options) {
232
+ const lockPath = options?.lockPath ?? controlStateLockPath(stateFilePath);
233
+ const staleMs = options?.staleMs ?? CONTROL_STATE_LOCK_STALE_MS;
234
+ const deadline = Date.now() + (options?.timeoutMs ?? CONTROL_STATE_LOCK_TIMEOUT_MS);
235
+ const token = newToken();
236
+ const body = lockBody(token);
237
+ // A first-ever transaction on a fresh install has no ~/.pd directory yet —
238
+ // create it (same recursive mkdir the state write itself uses) so lock
239
+ // creation cannot fail on ENOENT. A real failure here surfaces as
240
+ // 'unwritable' below.
241
+ try {
242
+ fs.mkdirSync(path.dirname(lockPath), { recursive: true });
243
+ }
244
+ catch (error) {
245
+ const message = error instanceof Error ? error.message : String(error);
246
+ return { ok: false, kind: 'unwritable', detail: `mkdir failed: ${message}` };
247
+ }
248
+ for (;;) {
249
+ const created = tryCreateExclusiveLock(lockPath, body);
250
+ if (created === 'created') {
251
+ sweepOrphanSidecars(lockPath, staleMs);
252
+ return { ok: true, handle: { lockPath, token, body } };
253
+ }
254
+ if (typeof created === 'object') {
255
+ return { ok: false, kind: 'unwritable', detail: created.error };
256
+ }
257
+ let stale = false;
258
+ let staleBody;
259
+ try {
260
+ const stat = fs.statSync(lockPath);
261
+ if (stat.mtimeMs < Date.now() - staleMs) {
262
+ staleBody = readLockBody(lockPath);
263
+ stale = staleBody !== undefined;
264
+ }
265
+ }
266
+ catch {
267
+ // vanished between create-attempt and stat; next loop's create decides
268
+ }
269
+ if (stale && staleBody !== undefined) {
270
+ if (takeOverStaleExclusiveLock({ lockPath, staleBody, sidecarToken: token, staleMs }))
271
+ continue;
272
+ }
273
+ if (Date.now() >= deadline)
274
+ return { ok: false, kind: 'timeout' };
275
+ await sleep(CONTROL_STATE_LOCK_POLL_MS);
276
+ }
277
+ }
278
+ /**
279
+ * Synchronous one-shot variant for callers that must not await: tries to
280
+ * create the lock once, and takes over a stale lock via the same
281
+ * rename-claim protocol. Returns undefined when the lock is busy or cannot
282
+ * be created (the caller skips loudly — it must never write without the
283
+ * lock).
284
+ */
285
+ export function tryAcquireExclusiveLockSync(stateFilePath, options) {
286
+ const lockPath = options?.lockPath ?? controlStateLockPath(stateFilePath);
287
+ const staleMs = options?.staleMs ?? CONTROL_STATE_LOCK_STALE_MS;
288
+ const token = newToken();
289
+ const body = lockBody(token);
290
+ try {
291
+ fs.mkdirSync(path.dirname(lockPath), { recursive: true });
292
+ }
293
+ catch {
294
+ return undefined;
295
+ }
296
+ const created = tryCreateExclusiveLock(lockPath, body);
297
+ if (created === 'created') {
298
+ sweepOrphanSidecars(lockPath, staleMs);
299
+ return { lockPath, token, body };
300
+ }
301
+ if (typeof created === 'object')
302
+ return undefined;
303
+ let staleBody;
304
+ try {
305
+ const stat = fs.statSync(lockPath);
306
+ if (stat.mtimeMs < Date.now() - staleMs)
307
+ staleBody = readLockBody(lockPath);
308
+ }
309
+ catch {
310
+ return undefined;
311
+ }
312
+ if (staleBody !== undefined && takeOverStaleExclusiveLock({ lockPath, staleBody, sidecarToken: token, staleMs })) {
313
+ const retried = tryCreateExclusiveLock(lockPath, body);
314
+ if (retried === 'created') {
315
+ sweepOrphanSidecars(lockPath, staleMs);
316
+ return { lockPath, token, body };
317
+ }
318
+ }
319
+ return undefined;
320
+ }
@@ -90,33 +90,50 @@ export declare function createProductTelemetryService(deps?: ProductTelemetrySer
90
90
  };
91
91
  /** Exact outbound payload for `pd telemetry preview`. Never sends. */
92
92
  preview(workspaceDir: string): ProductTelemetryPreview;
93
- /** `pd telemetry enable --confirm`: explicit granted consent (+ secret). */
94
- enable(): {
93
+ /**
94
+ * `pd telemetry enable --confirm`: explicit granted consent (+ secret).
95
+ * One locked transaction (PRI-1151): the latest disk state is read UNDER
96
+ * the same cross-process lock that serializes every other control-state
97
+ * writer, so the grant is computed from — and applied to — the current
98
+ * state; a concurrent disable/migration/reset cannot be overwritten by a
99
+ * stale one.
100
+ */
101
+ enable(): Promise<{
95
102
  ok: true;
96
103
  consent: 'granted';
97
104
  } | {
98
105
  ok: false;
99
106
  reason: string;
100
107
  nextAction: string;
101
- };
102
- /** `pd telemetry disable --confirm`: deny consent and delete export identity. */
103
- disable(): {
108
+ }>;
109
+ /**
110
+ * `pd telemetry disable --confirm`: deny consent and delete export
111
+ * identity — one locked transaction (PRI-1151). Once this returns ok,
112
+ * no concurrent migration, enable, reset, or bookkeeping merge can
113
+ * restore the previous granted consent or secret: they serialize on the
114
+ * same lock and re-read the denied state.
115
+ */
116
+ disable(): Promise<{
104
117
  ok: true;
105
118
  consent: 'denied';
106
119
  } | {
107
120
  ok: false;
108
121
  reason: string;
109
122
  nextAction: string;
110
- };
111
- /** `pd telemetry reset --confirm`: delete identity; fresh secret only if still enabled. */
112
- reset(): {
123
+ }>;
124
+ /**
125
+ * `pd telemetry reset --confirm`: delete identity; fresh secret only if
126
+ * still enabled — one locked transaction (PRI-1151) over the LATEST disk
127
+ * state (never a stale cached identity).
128
+ */
129
+ reset(): Promise<{
113
130
  ok: true;
114
131
  consent: ProductTelemetryConsent;
115
132
  } | {
116
133
  ok: false;
117
134
  reason: string;
118
135
  nextAction: string;
119
- };
136
+ }>;
120
137
  /**
121
138
  * One gate-checked export attempt for a normal-activity trigger.
122
139
  * Never throws; every path returns a structured outcome.