@tokenroll/llmdoc 3.5.3 → 3.9.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.
- package/assets/viewer-app.js +11 -11
- package/assets/viewer-detail.js +4 -4
- package/assets/viewer-graph.js +3 -3
- package/assets/viewer.html +19 -19
- package/dist/cli.js +147 -71
- package/dist/commands/adopt.js +10 -6
- package/dist/commands/commit.js +232 -80
- package/dist/commands/context.js +85 -45
- package/dist/commands/dream.js +608 -0
- package/dist/commands/eval.js +379 -0
- package/dist/commands/fingerprint.js +9 -3
- package/dist/commands/hook.js +135 -28
- package/dist/commands/index.js +52 -7
- package/dist/commands/init-state.js +5 -5
- package/dist/commands/mv.js +33 -12
- package/dist/commands/new.js +12 -5
- package/dist/commands/prune.js +14 -3
- package/dist/commands/search.js +67 -4
- package/dist/commands/serve.js +1 -1
- package/dist/commands/show.js +40 -6
- package/dist/commands/status.js +46 -18
- package/dist/commands/tree.js +94 -6
- package/dist/commands/upgrade.js +15 -15
- package/dist/lib/config.js +502 -0
- package/dist/lib/constants.js +23 -0
- package/dist/lib/doc-shape.js +5 -5
- package/dist/lib/frontmatter.js +47 -0
- package/dist/lib/fs.js +8 -8
- package/dist/lib/git.js +147 -42
- package/dist/lib/markdown.js +8 -7
- package/dist/lib/output-schema.js +3 -3
- package/dist/lib/package-root.js +1 -1
- package/dist/lib/pagination.js +2 -2
- package/dist/lib/rewrite.js +9 -3
- package/dist/lib/routing.js +152 -0
- package/dist/lib/schema.js +16 -0
- package/dist/lib/search.js +35 -16
- package/dist/lib/source-id.js +49 -0
- package/dist/lib/sources.js +760 -0
- package/dist/lib/state.js +74 -25
- package/dist/lib/telemetry.js +726 -0
- package/dist/lib/viewer-http.js +2 -2
- package/dist/lib/workspace.js +187 -43
- package/package.json +1 -1
- package/schemas/config.schema.json +116 -0
- package/schemas/meta.schema.json +5 -1
- package/schemas/output.schema.json +442 -0
- package/schemas/probes.schema.json +90 -0
|
@@ -0,0 +1,726 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { DEFAULT_DREAM_WINDOW_DAYS, TELEMETRY_ACCESS_FILE, TELEMETRY_DIR, TELEMETRY_KEEP_RECORDS, TELEMETRY_MAX_BYTES } from "./constants.js";
|
|
5
|
+
import { isWithinRoot } from "./fs.js";
|
|
6
|
+
import { isGitFileTracked, isGitPathIgnored, isGitRepository } from "./git.js";
|
|
7
|
+
import { isSourceRef } from "./source-id.js";
|
|
8
|
+
const TELEMETRY_MAX_RECORD_BYTES = 2048;
|
|
9
|
+
const TELEMETRY_TARGET_ROTATED_BYTES = Math.floor(TELEMETRY_MAX_BYTES * 0.75);
|
|
10
|
+
const TELEMETRY_MAX_READ_BYTES = TELEMETRY_MAX_BYTES * 4;
|
|
11
|
+
const TELEMETRY_LOCK_STALE_MS = 5_000;
|
|
12
|
+
const TELEMETRY_LOCK_MAX_ATTEMPTS = 25;
|
|
13
|
+
const TELEMETRY_LOCK_WAIT_MS = 8;
|
|
14
|
+
const TELEMETRY_FUTURE_TOLERANCE_MS = 5 * 60 * 1000;
|
|
15
|
+
const SOURCE_REF_TOKEN_PATTERN = /(?:^|[\s'"`(])@[a-z0-9][a-z0-9._-]{0,63}\/[^\s'"`),]*/gi;
|
|
16
|
+
const WINDOWS_DRIVE_PATTERN = /^[A-Za-z]:/;
|
|
17
|
+
function stripControlChars(input, replacement) {
|
|
18
|
+
let result = "";
|
|
19
|
+
for (let index = 0; index < input.length; index += 1) {
|
|
20
|
+
const code = input.charCodeAt(index);
|
|
21
|
+
if (code < 0x20 || code === 0x7f) {
|
|
22
|
+
result += replacement;
|
|
23
|
+
}
|
|
24
|
+
else {
|
|
25
|
+
result += input[index];
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return result;
|
|
29
|
+
}
|
|
30
|
+
export function telemetryFilePath(rootDir) {
|
|
31
|
+
return path.join(rootDir, TELEMETRY_DIR, TELEMETRY_ACCESS_FILE);
|
|
32
|
+
}
|
|
33
|
+
export function getTelemetryPersistenceStatus(rootDir) {
|
|
34
|
+
if (!isGitRepository(rootDir)) {
|
|
35
|
+
return { enabled: true, reason: null };
|
|
36
|
+
}
|
|
37
|
+
const relPath = `${TELEMETRY_DIR}/${TELEMETRY_ACCESS_FILE}`;
|
|
38
|
+
if (isGitFileTracked(rootDir, relPath)) {
|
|
39
|
+
return { enabled: false, reason: "tracked_by_git" };
|
|
40
|
+
}
|
|
41
|
+
if (!isGitPathIgnored(rootDir, relPath)) {
|
|
42
|
+
return { enabled: false, reason: "not_gitignored" };
|
|
43
|
+
}
|
|
44
|
+
return { enabled: true, reason: null };
|
|
45
|
+
}
|
|
46
|
+
export function resolveSafeSubdirectory(rootDir, segments, options) {
|
|
47
|
+
let rootRealPath;
|
|
48
|
+
try {
|
|
49
|
+
rootRealPath = fs.realpathSync(rootDir);
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
let current = rootRealPath;
|
|
55
|
+
for (const segment of segments) {
|
|
56
|
+
if (!segment || segment === "." || segment === ".." || segment.includes("/") || segment.includes("\\")) {
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
const candidate = path.join(current, segment);
|
|
60
|
+
let stat = null;
|
|
61
|
+
try {
|
|
62
|
+
stat = fs.lstatSync(candidate);
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
if (error.code !== "ENOENT") {
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
if (!options.create) {
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
try {
|
|
72
|
+
fs.mkdirSync(candidate, { mode: 0o700 });
|
|
73
|
+
stat = fs.lstatSync(candidate);
|
|
74
|
+
}
|
|
75
|
+
catch (mkdirError) {
|
|
76
|
+
if (mkdirError.code === "EEXIST") {
|
|
77
|
+
try {
|
|
78
|
+
stat = fs.lstatSync(candidate);
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
else {
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
if (!stat || stat.isSymbolicLink() || !stat.isDirectory()) {
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
let candidateRealPath;
|
|
93
|
+
try {
|
|
94
|
+
candidateRealPath = fs.realpathSync(candidate);
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
if (!isWithinRoot(rootRealPath, candidateRealPath)) {
|
|
100
|
+
return null;
|
|
101
|
+
}
|
|
102
|
+
current = candidateRealPath;
|
|
103
|
+
}
|
|
104
|
+
return current;
|
|
105
|
+
}
|
|
106
|
+
export function readRegularFileSafely(filePath, maxBytes) {
|
|
107
|
+
const opened = openVerifiedRegularFile(filePath, fs.constants.O_RDONLY, false);
|
|
108
|
+
if (!opened) {
|
|
109
|
+
return null;
|
|
110
|
+
}
|
|
111
|
+
try {
|
|
112
|
+
const readSize = Math.min(opened.stat.size, maxBytes);
|
|
113
|
+
if (readSize <= 0) {
|
|
114
|
+
return "";
|
|
115
|
+
}
|
|
116
|
+
const buffer = Buffer.alloc(readSize);
|
|
117
|
+
let totalRead = 0;
|
|
118
|
+
while (totalRead < readSize) {
|
|
119
|
+
const bytes = fs.readSync(opened.fd, buffer, totalRead, readSize - totalRead, totalRead);
|
|
120
|
+
if (bytes <= 0) {
|
|
121
|
+
break;
|
|
122
|
+
}
|
|
123
|
+
totalRead += bytes;
|
|
124
|
+
}
|
|
125
|
+
return buffer.subarray(0, totalRead).toString("utf8");
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
return null;
|
|
129
|
+
}
|
|
130
|
+
finally {
|
|
131
|
+
try {
|
|
132
|
+
fs.closeSync(opened.fd);
|
|
133
|
+
}
|
|
134
|
+
catch {
|
|
135
|
+
// Ignore close failure on fail-open read.
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
// Fail-open local retrieval telemetry under .llmdoc-tmp/telemetry/access.jsonl.
|
|
140
|
+
// Records only local llmdoc document IDs, search modes/hit counts, and unmapped file probes —
|
|
141
|
+
// never external @source/ paths, document bodies, source text, or conversation transcripts.
|
|
142
|
+
export function recordTelemetryEvent(rootDir, input) {
|
|
143
|
+
try {
|
|
144
|
+
const normalized = normalizeEvent(input);
|
|
145
|
+
if (!normalized) {
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
const serialized = serializeBoundedEvent(normalized);
|
|
149
|
+
if (!serialized) {
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
if (!getTelemetryPersistenceStatus(rootDir).enabled) {
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
const telemetryDir = resolveSafeSubdirectory(rootDir, TELEMETRY_DIR.split("/"), { create: true });
|
|
156
|
+
if (!telemetryDir) {
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
const filePath = path.join(telemetryDir, TELEMETRY_ACCESS_FILE);
|
|
160
|
+
const lockDir = path.join(telemetryDir, ".access.lock");
|
|
161
|
+
if (!acquireLock(lockDir)) {
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
try {
|
|
165
|
+
appendOrRotateLocked(telemetryDir, filePath, serialized);
|
|
166
|
+
}
|
|
167
|
+
finally {
|
|
168
|
+
releaseLock(lockDir);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
// Telemetry is strictly fail-open and must never interrupt read commands or hooks.
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
export function readTelemetryEvents(rootDir, options) {
|
|
176
|
+
const telemetryDir = resolveSafeSubdirectory(rootDir, TELEMETRY_DIR.split("/"), { create: false });
|
|
177
|
+
if (!telemetryDir) {
|
|
178
|
+
return [];
|
|
179
|
+
}
|
|
180
|
+
const filePath = path.join(telemetryDir, TELEMETRY_ACCESS_FILE);
|
|
181
|
+
const raw = readRegularFileSafely(filePath, TELEMETRY_MAX_READ_BYTES);
|
|
182
|
+
if (raw === null) {
|
|
183
|
+
return [];
|
|
184
|
+
}
|
|
185
|
+
const windowDays = options?.windowDays ?? DEFAULT_DREAM_WINDOW_DAYS;
|
|
186
|
+
const nowMs = options?.nowMs ?? Date.now();
|
|
187
|
+
const cutoffMs = nowMs - windowDays * 24 * 60 * 60 * 1000;
|
|
188
|
+
const futureLimitMs = nowMs + TELEMETRY_FUTURE_TOLERANCE_MS;
|
|
189
|
+
const events = [];
|
|
190
|
+
for (const line of raw.split(/\r?\n/)) {
|
|
191
|
+
const trimmed = line.trim();
|
|
192
|
+
if (!trimmed) {
|
|
193
|
+
continue;
|
|
194
|
+
}
|
|
195
|
+
const parsed = parseStoredTelemetryLine(trimmed, cutoffMs, futureLimitMs);
|
|
196
|
+
if (parsed) {
|
|
197
|
+
events.push(parsed);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
return events;
|
|
201
|
+
}
|
|
202
|
+
export function summarizeTelemetry(rootDir, options) {
|
|
203
|
+
const windowDays = options?.windowDays ?? DEFAULT_DREAM_WINDOW_DAYS;
|
|
204
|
+
const events = readTelemetryEvents(rootDir, { windowDays, nowMs: options?.nowMs });
|
|
205
|
+
const byDocument = new Map();
|
|
206
|
+
const blindSpotsByQuery = new Map();
|
|
207
|
+
const unmappedByFile = new Map();
|
|
208
|
+
const ensureDoc = (docPath) => {
|
|
209
|
+
const existing = byDocument.get(docPath);
|
|
210
|
+
if (existing) {
|
|
211
|
+
return existing;
|
|
212
|
+
}
|
|
213
|
+
const created = {
|
|
214
|
+
docPath,
|
|
215
|
+
showCount: 0,
|
|
216
|
+
preloadCount: 0,
|
|
217
|
+
contextHitCount: 0,
|
|
218
|
+
searchHitCount: 0,
|
|
219
|
+
activeReads: 0,
|
|
220
|
+
totalTouches: 0,
|
|
221
|
+
lastAccessedAt: null
|
|
222
|
+
};
|
|
223
|
+
byDocument.set(docPath, created);
|
|
224
|
+
return created;
|
|
225
|
+
};
|
|
226
|
+
const updateLatest = (current, next) => !current || next > current ? next : current;
|
|
227
|
+
for (const event of events) {
|
|
228
|
+
if (event.type === "show") {
|
|
229
|
+
for (const docPath of event.docs) {
|
|
230
|
+
const stats = ensureDoc(docPath);
|
|
231
|
+
stats.showCount += 1;
|
|
232
|
+
stats.activeReads += 1;
|
|
233
|
+
stats.totalTouches += 1;
|
|
234
|
+
stats.lastAccessedAt = updateLatest(stats.lastAccessedAt, event.ts);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
else if (event.type === "preload") {
|
|
238
|
+
for (const docPath of event.docs) {
|
|
239
|
+
const stats = ensureDoc(docPath);
|
|
240
|
+
stats.preloadCount += 1;
|
|
241
|
+
stats.totalTouches += 1;
|
|
242
|
+
stats.lastAccessedAt = updateLatest(stats.lastAccessedAt, event.ts);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
else if (event.type === "context") {
|
|
246
|
+
for (const docPath of event.docs) {
|
|
247
|
+
const stats = ensureDoc(docPath);
|
|
248
|
+
stats.contextHitCount += 1;
|
|
249
|
+
stats.activeReads += 1;
|
|
250
|
+
stats.totalTouches += 1;
|
|
251
|
+
stats.lastAccessedAt = updateLatest(stats.lastAccessedAt, event.ts);
|
|
252
|
+
}
|
|
253
|
+
for (const filePath of event.unmapped) {
|
|
254
|
+
const existing = unmappedByFile.get(filePath);
|
|
255
|
+
if (existing) {
|
|
256
|
+
existing.occurrences += 1;
|
|
257
|
+
existing.lastSeenAt = updateLatest(existing.lastSeenAt, event.ts);
|
|
258
|
+
}
|
|
259
|
+
else {
|
|
260
|
+
unmappedByFile.set(filePath, {
|
|
261
|
+
filePath,
|
|
262
|
+
occurrences: 1,
|
|
263
|
+
lastSeenAt: event.ts
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
else if (event.type === "search") {
|
|
269
|
+
for (const docPath of event.docs) {
|
|
270
|
+
const stats = ensureDoc(docPath);
|
|
271
|
+
stats.searchHitCount += 1;
|
|
272
|
+
stats.totalTouches += 1;
|
|
273
|
+
stats.lastAccessedAt = updateLatest(stats.lastAccessedAt, event.ts);
|
|
274
|
+
}
|
|
275
|
+
const isBlind = event.hitCount === 0 || event.mode === "cjk-bigram-fallback";
|
|
276
|
+
if (isBlind && event.query) {
|
|
277
|
+
const normalizedQuery = event.query.trim();
|
|
278
|
+
const key = normalizedQuery.toLowerCase();
|
|
279
|
+
const existing = blindSpotsByQuery.get(key);
|
|
280
|
+
if (existing) {
|
|
281
|
+
existing.occurrences += 1;
|
|
282
|
+
if (event.hitCount === 0) {
|
|
283
|
+
existing.zeroHitCount += 1;
|
|
284
|
+
}
|
|
285
|
+
if (event.mode === "cjk-bigram-fallback") {
|
|
286
|
+
existing.bigramFallbackCount += 1;
|
|
287
|
+
}
|
|
288
|
+
existing.lastSeenAt = updateLatest(existing.lastSeenAt, event.ts);
|
|
289
|
+
}
|
|
290
|
+
else {
|
|
291
|
+
blindSpotsByQuery.set(key, {
|
|
292
|
+
query: normalizedQuery,
|
|
293
|
+
occurrences: 1,
|
|
294
|
+
zeroHitCount: event.hitCount === 0 ? 1 : 0,
|
|
295
|
+
bigramFallbackCount: event.mode === "cjk-bigram-fallback" ? 1 : 0,
|
|
296
|
+
lastSeenAt: event.ts
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
const searchBlindSpots = [...blindSpotsByQuery.values()].sort((left, right) => right.occurrences - left.occurrences || right.lastSeenAt.localeCompare(left.lastSeenAt));
|
|
303
|
+
const unmappedProbes = [...unmappedByFile.values()].sort((left, right) => right.occurrences - left.occurrences || left.filePath.localeCompare(right.filePath));
|
|
304
|
+
return {
|
|
305
|
+
windowDays,
|
|
306
|
+
eventCount: events.length,
|
|
307
|
+
byDocument,
|
|
308
|
+
searchBlindSpots,
|
|
309
|
+
unmappedProbes
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
function parseStoredTelemetryLine(line, cutoffMs, futureLimitMs) {
|
|
313
|
+
let parsed;
|
|
314
|
+
try {
|
|
315
|
+
parsed = JSON.parse(line);
|
|
316
|
+
}
|
|
317
|
+
catch {
|
|
318
|
+
return null;
|
|
319
|
+
}
|
|
320
|
+
if (!parsed || typeof parsed !== "object" || typeof parsed.ts !== "string" || typeof parsed.type !== "string") {
|
|
321
|
+
return null;
|
|
322
|
+
}
|
|
323
|
+
const eventMs = Date.parse(parsed.ts);
|
|
324
|
+
if (Number.isNaN(eventMs) || eventMs < cutoffMs || eventMs > futureLimitMs) {
|
|
325
|
+
return null;
|
|
326
|
+
}
|
|
327
|
+
if (parsed.type === "show" || parsed.type === "preload") {
|
|
328
|
+
if (!Array.isArray(parsed.docs)) {
|
|
329
|
+
return null;
|
|
330
|
+
}
|
|
331
|
+
const docs = sanitizeLocalDocs(parsed.docs);
|
|
332
|
+
if (docs.length === 0) {
|
|
333
|
+
return null;
|
|
334
|
+
}
|
|
335
|
+
return {
|
|
336
|
+
ts: parsed.ts,
|
|
337
|
+
type: parsed.type,
|
|
338
|
+
docs
|
|
339
|
+
};
|
|
340
|
+
}
|
|
341
|
+
if (parsed.type === "search") {
|
|
342
|
+
if (typeof parsed.query !== "string" ||
|
|
343
|
+
(parsed.mode !== "lexical" && parsed.mode !== "cjk-bigram-fallback") ||
|
|
344
|
+
typeof parsed.hitCount !== "number" ||
|
|
345
|
+
!Number.isFinite(parsed.hitCount)) {
|
|
346
|
+
return null;
|
|
347
|
+
}
|
|
348
|
+
const query = sanitizeQuery(parsed.query);
|
|
349
|
+
if (!query) {
|
|
350
|
+
return null;
|
|
351
|
+
}
|
|
352
|
+
return {
|
|
353
|
+
ts: parsed.ts,
|
|
354
|
+
type: "search",
|
|
355
|
+
query,
|
|
356
|
+
mode: parsed.mode,
|
|
357
|
+
hitCount: Math.max(0, Math.floor(parsed.hitCount)),
|
|
358
|
+
docs: Array.isArray(parsed.docs) ? sanitizeLocalDocs(parsed.docs) : []
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
if (parsed.type === "context") {
|
|
362
|
+
const docs = Array.isArray(parsed.docs) ? sanitizeLocalDocs(parsed.docs) : [];
|
|
363
|
+
const unmapped = Array.isArray(parsed.unmapped) ? sanitizeLocalUnmapped(parsed.unmapped) : [];
|
|
364
|
+
if (docs.length === 0 && unmapped.length === 0) {
|
|
365
|
+
return null;
|
|
366
|
+
}
|
|
367
|
+
return {
|
|
368
|
+
ts: parsed.ts,
|
|
369
|
+
type: "context",
|
|
370
|
+
docs,
|
|
371
|
+
unmapped
|
|
372
|
+
};
|
|
373
|
+
}
|
|
374
|
+
return null;
|
|
375
|
+
}
|
|
376
|
+
function normalizeEvent(input) {
|
|
377
|
+
const ts = input.ts ?? new Date().toISOString();
|
|
378
|
+
if (Number.isNaN(Date.parse(ts))) {
|
|
379
|
+
return null;
|
|
380
|
+
}
|
|
381
|
+
if (input.type === "show" || input.type === "preload") {
|
|
382
|
+
const docs = sanitizeLocalDocs(input.docs);
|
|
383
|
+
if (docs.length === 0) {
|
|
384
|
+
return null;
|
|
385
|
+
}
|
|
386
|
+
return { ts, type: input.type, docs };
|
|
387
|
+
}
|
|
388
|
+
if (input.type === "search") {
|
|
389
|
+
const query = sanitizeQuery(input.query);
|
|
390
|
+
if (!query) {
|
|
391
|
+
return null;
|
|
392
|
+
}
|
|
393
|
+
return {
|
|
394
|
+
ts,
|
|
395
|
+
type: "search",
|
|
396
|
+
query,
|
|
397
|
+
mode: input.mode,
|
|
398
|
+
hitCount: Math.max(0, Math.floor(input.hitCount)),
|
|
399
|
+
docs: sanitizeLocalDocs(input.docs).slice(0, 10)
|
|
400
|
+
};
|
|
401
|
+
}
|
|
402
|
+
const docs = sanitizeLocalDocs(input.docs);
|
|
403
|
+
const unmapped = sanitizeLocalUnmapped(input.unmapped);
|
|
404
|
+
if (docs.length === 0 && unmapped.length === 0) {
|
|
405
|
+
return null;
|
|
406
|
+
}
|
|
407
|
+
return { ts, type: "context", docs, unmapped };
|
|
408
|
+
}
|
|
409
|
+
function serializeBoundedEvent(event) {
|
|
410
|
+
let candidate = event;
|
|
411
|
+
let line = `${JSON.stringify(candidate)}\n`;
|
|
412
|
+
if (Buffer.byteLength(line, "utf8") <= TELEMETRY_MAX_RECORD_BYTES) {
|
|
413
|
+
return line;
|
|
414
|
+
}
|
|
415
|
+
if (candidate.type === "show" || candidate.type === "preload") {
|
|
416
|
+
const docs = candidate.docs.slice();
|
|
417
|
+
while (docs.length > 0) {
|
|
418
|
+
docs.pop();
|
|
419
|
+
candidate = { ...candidate, docs };
|
|
420
|
+
line = `${JSON.stringify(candidate)}\n`;
|
|
421
|
+
if (Buffer.byteLength(line, "utf8") <= TELEMETRY_MAX_RECORD_BYTES) {
|
|
422
|
+
return docs.length > 0 ? line : null;
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
return null;
|
|
426
|
+
}
|
|
427
|
+
if (candidate.type === "search") {
|
|
428
|
+
const docs = candidate.docs.slice();
|
|
429
|
+
let query = candidate.query;
|
|
430
|
+
while (Buffer.byteLength(line, "utf8") > TELEMETRY_MAX_RECORD_BYTES) {
|
|
431
|
+
if (docs.length > 0) {
|
|
432
|
+
docs.pop();
|
|
433
|
+
}
|
|
434
|
+
else if (query.length > 16) {
|
|
435
|
+
query = query.slice(0, Math.floor(query.length / 2)).trim();
|
|
436
|
+
}
|
|
437
|
+
else {
|
|
438
|
+
return null;
|
|
439
|
+
}
|
|
440
|
+
candidate = { ...candidate, query, docs };
|
|
441
|
+
line = `${JSON.stringify(candidate)}\n`;
|
|
442
|
+
}
|
|
443
|
+
return query ? line : null;
|
|
444
|
+
}
|
|
445
|
+
const docs = candidate.docs.slice();
|
|
446
|
+
const unmapped = candidate.unmapped.slice();
|
|
447
|
+
while (Buffer.byteLength(line, "utf8") > TELEMETRY_MAX_RECORD_BYTES) {
|
|
448
|
+
if (unmapped.length > 0) {
|
|
449
|
+
unmapped.pop();
|
|
450
|
+
}
|
|
451
|
+
else if (docs.length > 0) {
|
|
452
|
+
docs.pop();
|
|
453
|
+
}
|
|
454
|
+
else {
|
|
455
|
+
return null;
|
|
456
|
+
}
|
|
457
|
+
candidate = { ...candidate, docs, unmapped };
|
|
458
|
+
line = `${JSON.stringify(candidate)}\n`;
|
|
459
|
+
}
|
|
460
|
+
return docs.length > 0 || unmapped.length > 0 ? line : null;
|
|
461
|
+
}
|
|
462
|
+
function sanitizeQuery(raw) {
|
|
463
|
+
const cleaned = stripControlChars(raw, " ")
|
|
464
|
+
.replace(SOURCE_REF_TOKEN_PATTERN, " ")
|
|
465
|
+
.replace(/\s+/g, " ")
|
|
466
|
+
.trim()
|
|
467
|
+
.replace(/^['"`]+|['"`]+$/g, "")
|
|
468
|
+
.trim();
|
|
469
|
+
if (!cleaned || isSourceRef(cleaned)) {
|
|
470
|
+
return null;
|
|
471
|
+
}
|
|
472
|
+
return cleaned.slice(0, 120);
|
|
473
|
+
}
|
|
474
|
+
function sanitizeLocalDocs(docs) {
|
|
475
|
+
const result = new Set();
|
|
476
|
+
for (const item of docs) {
|
|
477
|
+
if (typeof item !== "string") {
|
|
478
|
+
continue;
|
|
479
|
+
}
|
|
480
|
+
const trimmed = stripControlChars(item, "").trim().replaceAll("\\", "/");
|
|
481
|
+
if (!trimmed || isSourceRef(trimmed) || trimmed.startsWith("/") || WINDOWS_DRIVE_PATTERN.test(trimmed)) {
|
|
482
|
+
continue;
|
|
483
|
+
}
|
|
484
|
+
const normalized = trimmed.startsWith("llmdoc/") ? trimmed.slice("llmdoc/".length) : trimmed;
|
|
485
|
+
const segments = normalized.split("/");
|
|
486
|
+
if (segments.some((seg) => !seg || seg === "." || seg === "..")) {
|
|
487
|
+
continue;
|
|
488
|
+
}
|
|
489
|
+
if (normalized.endsWith(".mdx") && normalized.length <= 240) {
|
|
490
|
+
result.add(normalized);
|
|
491
|
+
if (result.size >= 20) {
|
|
492
|
+
break;
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
return [...result].sort();
|
|
497
|
+
}
|
|
498
|
+
function sanitizeLocalUnmapped(items) {
|
|
499
|
+
const result = new Set();
|
|
500
|
+
for (const item of items) {
|
|
501
|
+
if (typeof item !== "string") {
|
|
502
|
+
continue;
|
|
503
|
+
}
|
|
504
|
+
const trimmed = stripControlChars(item, "").trim().replaceAll("\\", "/");
|
|
505
|
+
if (!trimmed ||
|
|
506
|
+
trimmed.length > 240 ||
|
|
507
|
+
isSourceRef(trimmed) ||
|
|
508
|
+
trimmed.startsWith("/") ||
|
|
509
|
+
WINDOWS_DRIVE_PATTERN.test(trimmed)) {
|
|
510
|
+
continue;
|
|
511
|
+
}
|
|
512
|
+
const segments = trimmed.split("/");
|
|
513
|
+
if (segments.some((seg) => !seg || seg === "." || seg === "..")) {
|
|
514
|
+
continue;
|
|
515
|
+
}
|
|
516
|
+
result.add(trimmed);
|
|
517
|
+
if (result.size >= 20) {
|
|
518
|
+
break;
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
return [...result];
|
|
522
|
+
}
|
|
523
|
+
function openVerifiedRegularFile(filePath, baseFlags, create) {
|
|
524
|
+
let preStat = null;
|
|
525
|
+
try {
|
|
526
|
+
preStat = fs.lstatSync(filePath);
|
|
527
|
+
if (preStat.isSymbolicLink() || !preStat.isFile()) {
|
|
528
|
+
return null;
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
catch (error) {
|
|
532
|
+
if (error.code !== "ENOENT" || !create) {
|
|
533
|
+
return null;
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
const noFollow = fs.constants.O_NOFOLLOW ?? 0;
|
|
537
|
+
const nonBlock = fs.constants.O_NONBLOCK ?? 0;
|
|
538
|
+
const flags = baseFlags | noFollow | nonBlock;
|
|
539
|
+
let fd;
|
|
540
|
+
try {
|
|
541
|
+
fd = create ? fs.openSync(filePath, flags, 0o600) : fs.openSync(filePath, flags);
|
|
542
|
+
}
|
|
543
|
+
catch {
|
|
544
|
+
return null;
|
|
545
|
+
}
|
|
546
|
+
try {
|
|
547
|
+
const fstat = fs.fstatSync(fd);
|
|
548
|
+
if (!fstat.isFile()) {
|
|
549
|
+
fs.closeSync(fd);
|
|
550
|
+
return null;
|
|
551
|
+
}
|
|
552
|
+
const postStat = fs.lstatSync(filePath);
|
|
553
|
+
if (postStat.isSymbolicLink() || !postStat.isFile() || postStat.ino !== fstat.ino || postStat.dev !== fstat.dev) {
|
|
554
|
+
fs.closeSync(fd);
|
|
555
|
+
return null;
|
|
556
|
+
}
|
|
557
|
+
return { fd, stat: fstat };
|
|
558
|
+
}
|
|
559
|
+
catch {
|
|
560
|
+
try {
|
|
561
|
+
fs.closeSync(fd);
|
|
562
|
+
}
|
|
563
|
+
catch {
|
|
564
|
+
// Ignore close failure.
|
|
565
|
+
}
|
|
566
|
+
return null;
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
function appendOrRotateLocked(telemetryDir, filePath, newLine) {
|
|
570
|
+
const newLineBytes = Buffer.byteLength(newLine, "utf8");
|
|
571
|
+
const opened = openVerifiedRegularFile(filePath, fs.constants.O_RDWR | fs.constants.O_CREAT, true);
|
|
572
|
+
if (!opened) {
|
|
573
|
+
return;
|
|
574
|
+
}
|
|
575
|
+
const currentSize = opened.stat.size;
|
|
576
|
+
if (currentSize + newLineBytes + 1 > TELEMETRY_MAX_BYTES) {
|
|
577
|
+
let existingRaw = "";
|
|
578
|
+
try {
|
|
579
|
+
const readSize = Math.min(currentSize, TELEMETRY_MAX_READ_BYTES);
|
|
580
|
+
if (readSize > 0) {
|
|
581
|
+
const buffer = Buffer.alloc(readSize);
|
|
582
|
+
let total = 0;
|
|
583
|
+
while (total < readSize) {
|
|
584
|
+
const bytes = fs.readSync(opened.fd, buffer, total, readSize - total, total);
|
|
585
|
+
if (bytes <= 0) {
|
|
586
|
+
break;
|
|
587
|
+
}
|
|
588
|
+
total += bytes;
|
|
589
|
+
}
|
|
590
|
+
existingRaw = buffer.subarray(0, total).toString("utf8");
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
finally {
|
|
594
|
+
fs.closeSync(opened.fd);
|
|
595
|
+
}
|
|
596
|
+
const rotatedContent = buildRotatedContent(existingRaw, newLine, newLineBytes);
|
|
597
|
+
atomicWriteTelemetryFile(telemetryDir, filePath, rotatedContent);
|
|
598
|
+
return;
|
|
599
|
+
}
|
|
600
|
+
try {
|
|
601
|
+
let needsLeadingNewline = false;
|
|
602
|
+
if (currentSize > 0) {
|
|
603
|
+
const lastByte = Buffer.alloc(1);
|
|
604
|
+
const read = fs.readSync(opened.fd, lastByte, 0, 1, currentSize - 1);
|
|
605
|
+
if (read === 1 && lastByte[0] !== 0x0a) {
|
|
606
|
+
needsLeadingNewline = true;
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
const payload = Buffer.from(needsLeadingNewline ? `\n${newLine}` : newLine, "utf8");
|
|
610
|
+
fs.writeSync(opened.fd, payload, 0, payload.length, currentSize);
|
|
611
|
+
}
|
|
612
|
+
finally {
|
|
613
|
+
fs.closeSync(opened.fd);
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
function buildRotatedContent(existingRaw, newLine, newLineBytes) {
|
|
617
|
+
const rawLines = existingRaw
|
|
618
|
+
.split(/\r?\n/)
|
|
619
|
+
.map((line) => line.trim())
|
|
620
|
+
.filter((line) => line.length > 0);
|
|
621
|
+
const retainedReversed = [];
|
|
622
|
+
let retainedBytes = newLineBytes;
|
|
623
|
+
const maxPriorLines = Math.max(0, TELEMETRY_KEEP_RECORDS - 1);
|
|
624
|
+
for (let idx = rawLines.length - 1; idx >= 0 && retainedReversed.length < maxPriorLines; idx -= 1) {
|
|
625
|
+
const candidate = rawLines[idx];
|
|
626
|
+
try {
|
|
627
|
+
const parsed = JSON.parse(candidate);
|
|
628
|
+
if (!parsed || typeof parsed !== "object" || typeof parsed.ts !== "string" || typeof parsed.type !== "string") {
|
|
629
|
+
continue;
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
catch {
|
|
633
|
+
continue;
|
|
634
|
+
}
|
|
635
|
+
const lineBytes = Buffer.byteLength(candidate, "utf8") + 1;
|
|
636
|
+
if (retainedBytes + lineBytes > TELEMETRY_TARGET_ROTATED_BYTES) {
|
|
637
|
+
break;
|
|
638
|
+
}
|
|
639
|
+
retainedReversed.push(candidate);
|
|
640
|
+
retainedBytes += lineBytes;
|
|
641
|
+
}
|
|
642
|
+
retainedReversed.reverse();
|
|
643
|
+
return `${retainedReversed.length > 0 ? `${retainedReversed.join("\n")}\n` : ""}${newLine}`;
|
|
644
|
+
}
|
|
645
|
+
function atomicWriteTelemetryFile(telemetryDir, targetPath, content) {
|
|
646
|
+
const tempName = `.access.${process.pid}.${Date.now()}.${crypto.randomBytes(6).toString("hex")}.tmp`;
|
|
647
|
+
const tempPath = path.join(telemetryDir, tempName);
|
|
648
|
+
const noFollow = fs.constants.O_NOFOLLOW ?? 0;
|
|
649
|
+
const fd = fs.openSync(tempPath, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | noFollow, 0o600);
|
|
650
|
+
try {
|
|
651
|
+
fs.writeSync(fd, content, undefined, "utf8");
|
|
652
|
+
}
|
|
653
|
+
finally {
|
|
654
|
+
fs.closeSync(fd);
|
|
655
|
+
}
|
|
656
|
+
try {
|
|
657
|
+
// Re-verify target is absent or a regular non-symlink file before replacing.
|
|
658
|
+
try {
|
|
659
|
+
const stat = fs.lstatSync(targetPath);
|
|
660
|
+
if (stat.isSymbolicLink() || !stat.isFile()) {
|
|
661
|
+
fs.unlinkSync(tempPath);
|
|
662
|
+
return;
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
catch (error) {
|
|
666
|
+
if (error.code !== "ENOENT") {
|
|
667
|
+
fs.unlinkSync(tempPath);
|
|
668
|
+
return;
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
fs.renameSync(tempPath, targetPath);
|
|
672
|
+
}
|
|
673
|
+
catch {
|
|
674
|
+
try {
|
|
675
|
+
fs.unlinkSync(tempPath);
|
|
676
|
+
}
|
|
677
|
+
catch {
|
|
678
|
+
// Ignore cleanup failure.
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
function acquireLock(lockDir) {
|
|
683
|
+
const sleepBuffer = new Int32Array(new SharedArrayBuffer(4));
|
|
684
|
+
for (let attempt = 0; attempt < TELEMETRY_LOCK_MAX_ATTEMPTS; attempt += 1) {
|
|
685
|
+
try {
|
|
686
|
+
fs.mkdirSync(lockDir, { mode: 0o700 });
|
|
687
|
+
return true;
|
|
688
|
+
}
|
|
689
|
+
catch (error) {
|
|
690
|
+
if (error.code !== "EEXIST") {
|
|
691
|
+
return false;
|
|
692
|
+
}
|
|
693
|
+
try {
|
|
694
|
+
const stat = fs.lstatSync(lockDir);
|
|
695
|
+
if (stat.isSymbolicLink() || !stat.isDirectory()) {
|
|
696
|
+
return false;
|
|
697
|
+
}
|
|
698
|
+
if (Date.now() - stat.mtimeMs > TELEMETRY_LOCK_STALE_MS) {
|
|
699
|
+
try {
|
|
700
|
+
fs.rmdirSync(lockDir);
|
|
701
|
+
continue;
|
|
702
|
+
}
|
|
703
|
+
catch {
|
|
704
|
+
// Another process beat us to reclaim or recreated it.
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
catch {
|
|
709
|
+
continue;
|
|
710
|
+
}
|
|
711
|
+
Atomics.wait(sleepBuffer, 0, 0, TELEMETRY_LOCK_WAIT_MS);
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
return false;
|
|
715
|
+
}
|
|
716
|
+
function releaseLock(lockDir) {
|
|
717
|
+
try {
|
|
718
|
+
const stat = fs.lstatSync(lockDir);
|
|
719
|
+
if (!stat.isSymbolicLink() && stat.isDirectory()) {
|
|
720
|
+
fs.rmdirSync(lockDir);
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
catch {
|
|
724
|
+
// Ignore lock cleanup errors.
|
|
725
|
+
}
|
|
726
|
+
}
|