@pugi/cli 0.1.0-beta.25 → 0.1.0-beta.27

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.
@@ -66,6 +66,7 @@ export const SLASH_COMMAND_HELP = Object.freeze([
66
66
  { name: 'resume', args: '', gloss: 'Pick a stored session to restore', group: 'Session' },
67
67
  { name: 'context', args: '', gloss: 'Show three-tier context summary (Tier 0 skeleton + Tier 1 working set)', group: 'Session' },
68
68
  { name: 'compact', args: '', gloss: 'Summarise older turns into a boundary marker (leak L8)', group: 'Session' },
69
+ { name: 'rewind', args: '[N | --to <id>]', gloss: 'Roll the conversation back to a checkpoint (leak L9)', group: 'Session' },
69
70
  { name: 'memory', args: '', gloss: 'Session memory editor (α6.5b)', group: 'Session', stub: true },
70
71
  { name: 'init', args: '', gloss: 'Scaffold .pugi/ in the current workspace (β1 Sl11)', group: 'Session' },
71
72
  // Pugi tools
@@ -92,6 +93,7 @@ export const SLASH_COMMAND_HELP = Object.freeze([
92
93
  { name: 'help', args: '', gloss: 'Show this help overlay', group: 'Meta' },
93
94
  { name: 'version', args: '', gloss: 'Show CLI version', group: 'Meta' },
94
95
  { name: 'doctor', args: '', gloss: 'Environment health report (auth · API · Node · disk · MCP · …)', group: 'Meta' },
96
+ { name: 'prd-check', args: '<prd-path | --all> [--json]', gloss: 'Verify PRD acceptance criteria against committed code/tests/docs (Wave 6)', group: 'Meta' },
95
97
  { name: 'stickers', args: '', gloss: 'show Pugi brand stickers (gimmick)', group: 'Meta' },
96
98
  { name: 'feedback', args: '', gloss: 'file a bug / feature / general comment without leaving the REPL', group: 'Meta' },
97
99
  { name: 'share', args: '[--gist|--pugi] [--redact] [--preview]', gloss: 'Export session transcript to gist / pugi.io (leak L20)', group: 'Meta' },
@@ -431,6 +433,14 @@ export function parseSlashCommand(input) {
431
433
  // shell surface, not the slash one).
432
434
  return { kind: 'doctor' };
433
435
  }
436
+ case 'prd-check':
437
+ case 'prdcheck': {
438
+ // Wave 6 (2026-05-27): tokenise the tail and forward verbatim
439
+ // so the slash + shell surfaces share one `parsePrdCheckArgs`.
440
+ // Supports `<prd-path>`, `--all`, and `--json`.
441
+ const tokens = tail.length === 0 ? [] : tail.split(/\s+/).filter((s) => s.length > 0);
442
+ return { kind: 'prd-check', args: tokens };
443
+ }
434
444
  case 'compact': {
435
445
  // Leak L8 (2026-05-27): graduated from stub. The session module
436
446
  // owns the summariser round-trip; tail args are ignored today
@@ -439,6 +449,15 @@ export function parseSlashCommand(input) {
439
449
  // fresh shell.
440
450
  return { kind: 'compact' };
441
451
  }
452
+ case 'rewind': {
453
+ // Leak L9 (2026-05-27): `/rewind [N | --to <id>]`. Tokenize the
454
+ // tail unchanged so `runRewindCommand` (in `runtime/commands/
455
+ // rewind.ts`) handles every mode (picker / turns / to-event)
456
+ // through one parser. The slash + top-level CLI surfaces stay
457
+ // single-sourced — same separation as `/compact`.
458
+ const tokens = tail.length === 0 ? [] : tail.split(/\s+/).filter((s) => s.length > 0);
459
+ return { kind: 'rewind', args: tokens };
460
+ }
442
461
  case 'stickers': {
443
462
  // Leak L33 (2026-05-27): brand-personality gimmick. Tail args
444
463
  // are ignored — the surface is intentionally parameterless. The
@@ -361,7 +361,7 @@ export class SqliteSessionStore {
361
361
  // which maps to SQLITE_OPEN_READONLY. The option form is the
362
362
  // documented API; the file-URI form (file:...?mode=ro) also works.
363
363
  const db = new DatabaseSync(dbPath, { readOnly: true });
364
- return new SqliteSessionStoreReadOnlyView(db);
364
+ return new SqliteSessionStoreReadOnlyView(db, projectStoreDir);
365
365
  }
366
366
  /* ------------------------------------------------------------ */
367
367
  /* Internals */
@@ -584,8 +584,37 @@ export class SqliteSessionStore {
584
584
  */
585
585
  export class SqliteSessionStoreReadOnlyView {
586
586
  db;
587
- constructor(db) {
587
+ projectStoreDir;
588
+ constructor(db,
589
+ /**
590
+ * Project store directory — required for the JSONL event read path.
591
+ * L9 (2026-05-27): `/rewind` + `/resume` need to walk events from
592
+ * inside the read-only view so the rewind picker + resume preview
593
+ * never take the writer lockfile.
594
+ */
595
+ projectStoreDir) {
588
596
  this.db = db;
597
+ this.projectStoreDir = projectStoreDir;
598
+ }
599
+ /**
600
+ * Read every event for a session via the durable JSONL log. The
601
+ * SQLite cache is NOT used here — JSONL is the source of truth and
602
+ * the cache only holds counters. The walk stitches across rotation
603
+ * files (`events.<n>.jsonl`) in the same order `JsonlEventLog.read`
604
+ * uses inside the writer path so consumers see one consistent stream
605
+ * whether they came in via the writer store OR the read-only view.
606
+ */
607
+ async events(sessionId, opts) {
608
+ const sessionDir = resolve(this.projectStoreDir, 'sessions', sessionId);
609
+ if (!existsSync(sessionDir))
610
+ return [];
611
+ const log = new JsonlEventLog({ sessionDir });
612
+ try {
613
+ return log.read(opts);
614
+ }
615
+ finally {
616
+ log.close();
617
+ }
589
618
  }
590
619
  async list(opts) {
591
620
  const limit = clampLimit(opts?.limit ?? DEFAULT_LIST_LIMIT, MAX_LIST_LIMIT);
@@ -0,0 +1,229 @@
1
+ /**
2
+ * Telemetry emitter — Wave 6 BIG TRACK 11 (PR-PUGI-OBSERVABILITY-STACK).
3
+ *
4
+ * Single entry point used by the REPL + slash dispatcher + tool runner
5
+ * to record CLI lifecycle events. Honours the L25 telemetry-state
6
+ * consent verdict — events are dropped silently when the operator chose
7
+ * `off` (default) and accepted into the queue when they chose
8
+ * `anonymous` or `community`.
9
+ *
10
+ * Opt-out hatches (any one of them stops the emitter cold):
11
+ *
12
+ * 1. `~/.pugi/.telemetry-disabled` marker file (per-user kill switch
13
+ * the operator can drop with `touch` even when their config got
14
+ * corrupted). Hot-path: we stat() this once at boot AND on every
15
+ * emit so an emergency operator gesture takes effect immediately
16
+ * without a REPL restart.
17
+ * 2. `PUGI_TELEMETRY=0` (env). Honoured at every emit — CI scripts
18
+ * can wrap a one-shot invocation without touching the user's
19
+ * config.
20
+ * 3. L25 `~/.pugi/config.json::telemetry === 'off'`. Default for
21
+ * fresh installs — the onboarding wizard flips it to `anonymous`
22
+ * or `community` when the operator says yes.
23
+ *
24
+ * The emitter is fire-and-forget. Calls never throw, never block the
25
+ * caller, and never await the network. The queue persists events to a
26
+ * JSONL spill so a synchronous CLI process can exit before a network
27
+ * round-trip completes without losing data.
28
+ *
29
+ * Allowlisted meta keys — call sites MUST pass only the canonical keys
30
+ * (see `META_ALLOWLIST` below). Unknown keys are dropped at this layer
31
+ * AND again at the admin-api ingest layer (defence in depth).
32
+ */
33
+ import { statSync } from 'node:fs';
34
+ import { homedir } from 'node:os';
35
+ import { resolve } from 'node:path';
36
+ import { readTelemetryChoice, } from '../onboarding/telemetry-state.js';
37
+ import { PUGI_CLI_VERSION } from '../../runtime/version.js';
38
+ import { newSessionId, spillEvent, } from './queue.js';
39
+ /**
40
+ * Allowed meta keys. Matches the admin-api allowlist verbatim — the two
41
+ * lists MUST stay in sync. The server is the structural wall; this is
42
+ * the defence-in-depth at the source. Anything off-list is dropped
43
+ * before the event lands on disk so a CI grep of the spill file never
44
+ * surfaces a key that was never supposed to leave the process.
45
+ */
46
+ export const META_ALLOWLIST = new Set([
47
+ 'platform',
48
+ 'arch',
49
+ 'nodeVersion',
50
+ 'tier',
51
+ 'consent',
52
+ 'pty',
53
+ 'durationCategory',
54
+ 'exitCode',
55
+ 'parentCommand',
56
+ 'subagent',
57
+ 'modelTier',
58
+ 'cacheHit',
59
+ 'retryCount',
60
+ 'quotaTier',
61
+ 'tunedModel',
62
+ 'flagsHash',
63
+ ]);
64
+ /**
65
+ * Single source-of-truth marker the operator can `touch` to kill all
66
+ * telemetry from a single user account in one gesture. Bypasses the
67
+ * config file — survives a corrupt `config.json` and is documented in
68
+ * `pugi help telemetry`.
69
+ */
70
+ export const KILL_SWITCH_MARKER = '.telemetry-disabled';
71
+ /**
72
+ * Resolve the kill-switch marker path. Pure — exposed for tests.
73
+ */
74
+ export function killSwitchPath(env = process.env) {
75
+ const home = env.PUGI_HOME ?? resolve(homedir(), '.pugi');
76
+ return resolve(home, KILL_SWITCH_MARKER);
77
+ }
78
+ /**
79
+ * Is the kill switch armed? Stat the marker on every emit so an
80
+ * operator gesture (e.g. `touch ~/.pugi/.telemetry-disabled`) takes
81
+ * effect immediately without a REPL restart.
82
+ */
83
+ export function isKillSwitchArmed(env = process.env) {
84
+ const path = killSwitchPath(env);
85
+ try {
86
+ statSync(path);
87
+ return true;
88
+ }
89
+ catch {
90
+ return false;
91
+ }
92
+ }
93
+ /**
94
+ * Is the env-var opt-out set? Honours common falsy literals so a CI
95
+ * matrix that exports `PUGI_TELEMETRY=false` or `=no` does the right
96
+ * thing.
97
+ */
98
+ export function isEnvDisabled(env = process.env) {
99
+ const raw = (env.PUGI_TELEMETRY ?? '').trim().toLowerCase();
100
+ if (raw === '')
101
+ return false;
102
+ return raw === '0' || raw === 'false' || raw === 'off' || raw === 'no';
103
+ }
104
+ /**
105
+ * Resolve the current consent verdict. Cached per-call (no module-level
106
+ * caching) so the onboarding wizard's flip from `off` → `anonymous`
107
+ * takes effect immediately without a REPL restart.
108
+ */
109
+ export function currentConsent(ctx = {}) {
110
+ return readTelemetryChoice({ env: ctx.env });
111
+ }
112
+ /**
113
+ * Strip unknown keys + truncate long string values. Mirrors the server
114
+ * sanitiser. Cap is intentionally smaller here (256) than on the wire
115
+ * (512) — keeps the spill file lean on a long-offline laptop.
116
+ */
117
+ const META_VALUE_CAP = 256;
118
+ export function sanitiseMeta(value) {
119
+ const out = {};
120
+ if (!value || typeof value !== 'object')
121
+ return out;
122
+ let kept = 0;
123
+ for (const [k, v] of Object.entries(value)) {
124
+ if (kept >= 16)
125
+ break;
126
+ if (!META_ALLOWLIST.has(k))
127
+ continue;
128
+ if (v === null || v === undefined)
129
+ continue;
130
+ if (typeof v === 'string') {
131
+ out[k] = v.length > META_VALUE_CAP ? v.slice(0, META_VALUE_CAP) : v;
132
+ }
133
+ else if (typeof v === 'number' && Number.isFinite(v)) {
134
+ out[k] = v;
135
+ }
136
+ else if (typeof v === 'boolean') {
137
+ out[k] = v;
138
+ }
139
+ else {
140
+ continue;
141
+ }
142
+ kept += 1;
143
+ }
144
+ return out;
145
+ }
146
+ /**
147
+ * Per-process session id. Allocated lazily on first `emit(...)` so a
148
+ * CLI invocation that never fires telemetry never burns a UUID.
149
+ */
150
+ let cachedSessionId = null;
151
+ /**
152
+ * Reset the cached session id. Called by tests AND the REPL `/reset`
153
+ * path so a long-running REPL can rotate sessions on demand.
154
+ */
155
+ export function resetSessionId() {
156
+ cachedSessionId = null;
157
+ }
158
+ /**
159
+ * Build the outbound event from `EmitInput` + the resolved consent
160
+ * tier. Pure — exposed for spec parity.
161
+ */
162
+ export function buildEvent(input, consent, sessionId) {
163
+ const kind = input.kind ?? 'command-exec';
164
+ const success = typeof input.success === 'boolean' ? input.success : true;
165
+ // Anonymous tier strips everything but the bare counts. Community
166
+ // tier carries the (sanitised) meta payload. Off tier never reaches
167
+ // this function — the emit() gate rejects before we build.
168
+ const meta = consent === 'community' ? sanitiseMeta(input.meta) : {};
169
+ const out = {
170
+ sessionId,
171
+ cliVersion: PUGI_CLI_VERSION,
172
+ command: input.command,
173
+ kind,
174
+ ts: new Date().toISOString(),
175
+ success,
176
+ };
177
+ if (typeof input.durationMs === 'number' && Number.isFinite(input.durationMs)) {
178
+ out.durationMs = Math.max(0, Math.round(input.durationMs));
179
+ }
180
+ if (input.errorCode)
181
+ out.errorCode = input.errorCode;
182
+ if (input.tool)
183
+ out.tool = input.tool;
184
+ if (input.model)
185
+ out.model = input.model;
186
+ if (typeof input.tokensIn === 'number' && Number.isFinite(input.tokensIn)) {
187
+ out.tokensIn = Math.max(0, Math.round(input.tokensIn));
188
+ }
189
+ if (typeof input.tokensOut === 'number' && Number.isFinite(input.tokensOut)) {
190
+ out.tokensOut = Math.max(0, Math.round(input.tokensOut));
191
+ }
192
+ if (Object.keys(meta).length > 0)
193
+ out.meta = meta;
194
+ return out;
195
+ }
196
+ /**
197
+ * Fire one telemetry event. Never throws. Returns a discriminated
198
+ * verdict so callers (the spec, the diagnostic surface) can assert on
199
+ * the path the emit took.
200
+ *
201
+ * Hot-path: opt-out checks → consent check → buildEvent → spillEvent.
202
+ * The spillEvent step is sync filesystem IO; for CLI surfaces that
203
+ * cannot tolerate a 1ms stat() (e.g. inner REPL tick) the caller
204
+ * should queue via `setImmediate(() => emit(...))`.
205
+ */
206
+ export function emit(input, ctx = {}) {
207
+ const env = ctx.env ?? process.env;
208
+ // The three opt-out hatches, cheapest first.
209
+ if (isEnvDisabled(env))
210
+ return { kind: 'disabled', reason: 'env' };
211
+ if (isKillSwitchArmed(env))
212
+ return { kind: 'disabled', reason: 'marker' };
213
+ const consent = currentConsent({ env });
214
+ if (consent === 'off')
215
+ return { kind: 'disabled', reason: 'consent' };
216
+ if (!cachedSessionId)
217
+ cachedSessionId = ctx.sessionId ?? newSessionId();
218
+ const sessionId = ctx.sessionId ?? cachedSessionId;
219
+ const event = buildEvent(input, consent, sessionId);
220
+ try {
221
+ spillEvent(event, { repoRoot: ctx.repoRoot });
222
+ }
223
+ catch {
224
+ // Spill failure is silent — the emitter is best-effort by contract.
225
+ // A broken spill is a degraded-but-functional CLI, not a failed one.
226
+ }
227
+ return { kind: 'enqueued' };
228
+ }
229
+ //# sourceMappingURL=emitter.js.map
@@ -0,0 +1,251 @@
1
+ /**
2
+ * Telemetry batching queue — Wave 6 BIG TRACK 11 (PR-PUGI-OBSERVABILITY-STACK).
3
+ *
4
+ * The emitter (see `emitter.ts`) appends events to an in-memory buffer
5
+ * and a JSONL spill file. The queue's two-tier strategy:
6
+ *
7
+ * 1. In-memory buffer (`MAX_BUFFER`) → flushed every `FLUSH_INTERVAL_MS`
8
+ * OR on REPL exit OR when the buffer hits the cap.
9
+ * 2. JSONL spill (`<repoRoot>/.pugi/telemetry-queue.jsonl`) → drained
10
+ * on every flush attempt. Used when the in-memory buffer cannot
11
+ * reach the network (offline laptop, admin-api down).
12
+ *
13
+ * Failure semantics mirror the `feedback/queue.ts` pattern that landed
14
+ * in L21:
15
+ *
16
+ * - 200/201/204 → success, drop from spill
17
+ * - 404 → endpoint not deployed yet — keep
18
+ * - 5xx / network / abort → transient — keep + exponential backoff
19
+ * - other 4xx → permanent — drop (otherwise loop forever)
20
+ *
21
+ * The queue is intentionally simple: there are no concurrency primitives
22
+ * beyond filesystem `O_APPEND`. The CLI is single-process per REPL
23
+ * session; the JSONL spill survives a crash because every append is
24
+ * atomic at the OS level for line-sized writes on POSIX (Linux & macOS).
25
+ *
26
+ * Privacy:
27
+ *
28
+ * - Events drop into the queue only when telemetry consent ≠ `off`.
29
+ * The emitter consults `readTelemetryChoice()` before calling
30
+ * `enqueueTelemetry(...)`. This module does NOT re-check — keeping
31
+ * the consent gate at the emitter avoids double-decoding and
32
+ * centralises the audit point.
33
+ *
34
+ * - The spill file lives under `<repoRoot>/.pugi/` (workspace tier)
35
+ * so an operator who deletes the repo also wipes any unfortunate
36
+ * events that never made it to the server.
37
+ */
38
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync, } from 'node:fs';
39
+ import { dirname, resolve } from 'node:path';
40
+ import { randomUUID } from 'node:crypto';
41
+ import { PUGI_CLI_VERSION } from '../../runtime/version.js';
42
+ /** Defaults — tunable via env without redeploy. */
43
+ export const MAX_BUFFER = 50;
44
+ export const FLUSH_INTERVAL_MS = 15_000;
45
+ export const SPILL_FILE_NAME = 'telemetry-queue.jsonl';
46
+ /** Hard cap on the spill file (events, not bytes). Prevents pathologic
47
+ * growth on a laptop that is offline for weeks. */
48
+ export const SPILL_MAX_LINES = 5_000;
49
+ /**
50
+ * Resolve the absolute spill file path. Pure — exposed for spec parity.
51
+ */
52
+ export function telemetryQueuePath(opts = {}) {
53
+ const root = opts.repoRoot ?? process.cwd();
54
+ const name = opts.spillFileName ?? SPILL_FILE_NAME;
55
+ return resolve(root, '.pugi', name);
56
+ }
57
+ /**
58
+ * Append one event to the on-disk spill. Atomic at the OS level for
59
+ * line-sized writes — multiple concurrent appenders never interleave
60
+ * half-records on POSIX. Caps the file at `SPILL_MAX_LINES` by silently
61
+ * dropping the OLDEST events (FIFO) on the rare overflow path.
62
+ */
63
+ export function spillEvent(ev, opts = {}) {
64
+ const path = telemetryQueuePath(opts);
65
+ mkdirSync(dirname(path), { recursive: true });
66
+ const line = `${JSON.stringify(ev)}\n`;
67
+ // Fast path: append-only. We only check the line count when the file
68
+ // already exists AND we suspect overflow. Reading + rewriting every
69
+ // append would dominate the cost.
70
+ if (existsSync(path)) {
71
+ const current = readFileSync(path, 'utf8');
72
+ const lineCount = countLines(current);
73
+ if (lineCount >= SPILL_MAX_LINES) {
74
+ // FIFO trim: keep the most-recent SPILL_MAX_LINES/2 events. The
75
+ // factor 2 amortises the rewrite across many appends.
76
+ const lines = current.split('\n').filter((l) => l.length > 0);
77
+ const keep = lines.slice(lines.length - Math.floor(SPILL_MAX_LINES / 2));
78
+ writeFileSync(path, `${keep.join('\n')}\n${line}`, 'utf8');
79
+ return;
80
+ }
81
+ }
82
+ appendFileSync(path, line, { encoding: 'utf8', mode: 0o600 });
83
+ }
84
+ /**
85
+ * Read + parse every spilled event. Returns the events plus a list of
86
+ * malformed lines (which are dropped silently — we never reject a
87
+ * parseable line just because an adjacent one is corrupt).
88
+ */
89
+ export function readSpill(opts = {}) {
90
+ const path = telemetryQueuePath(opts);
91
+ if (!existsSync(path))
92
+ return { events: [], malformed: 0 };
93
+ const raw = readFileSync(path, 'utf8');
94
+ if (raw.length === 0)
95
+ return { events: [], malformed: 0 };
96
+ const events = [];
97
+ let malformed = 0;
98
+ for (const line of raw.split('\n')) {
99
+ if (line.length === 0)
100
+ continue;
101
+ try {
102
+ const parsed = JSON.parse(line);
103
+ if (isTelemetryEvent(parsed)) {
104
+ events.push(parsed);
105
+ }
106
+ else {
107
+ malformed += 1;
108
+ }
109
+ }
110
+ catch {
111
+ malformed += 1;
112
+ }
113
+ }
114
+ return { events, malformed };
115
+ }
116
+ /**
117
+ * Atomically rewrite the spill with the given events (the unsubmitted
118
+ * remainder after a partial-success flush). Writing through a sibling
119
+ * tempfile + rename keeps the spill consistent across a crash mid-flush.
120
+ */
121
+ export function rewriteSpill(events, opts = {}) {
122
+ const path = telemetryQueuePath(opts);
123
+ mkdirSync(dirname(path), { recursive: true });
124
+ if (events.length === 0) {
125
+ // Empty spill — write an empty file so the next read short-circuits.
126
+ writeFileSync(path, '', { encoding: 'utf8', mode: 0o600 });
127
+ return;
128
+ }
129
+ const body = events.map((e) => JSON.stringify(e)).join('\n');
130
+ writeFileSync(path, `${body}\n`, { encoding: 'utf8', mode: 0o600 });
131
+ }
132
+ /**
133
+ * Type guard for inbound spill lines. Keeps the queue robust against a
134
+ * forward-incompatible event shape (e.g. a future version added a
135
+ * required field) — anything that fails the guard is treated as
136
+ * malformed and dropped on parse.
137
+ */
138
+ export function isTelemetryEvent(value) {
139
+ if (!value || typeof value !== 'object')
140
+ return false;
141
+ const v = value;
142
+ return (typeof v.sessionId === 'string'
143
+ && typeof v.cliVersion === 'string'
144
+ && typeof v.command === 'string'
145
+ && typeof v.kind === 'string'
146
+ && typeof v.ts === 'string');
147
+ }
148
+ /**
149
+ * Exponential-backoff schedule. Returns the next delay (in ms) given an
150
+ * attempt counter, capped at `MAX_BACKOFF_MS`. Pure — exposed for tests.
151
+ *
152
+ * attempt 0 → 1s
153
+ * attempt 1 → 2s
154
+ * attempt 2 → 4s
155
+ * attempt 5 → 32s
156
+ * attempt 7+ → 60s (cap)
157
+ */
158
+ export const BACKOFF_BASE_MS = 1000;
159
+ export const MAX_BACKOFF_MS = 60_000;
160
+ export function backoffDelay(attempt) {
161
+ if (!Number.isFinite(attempt) || attempt < 0)
162
+ return BACKOFF_BASE_MS;
163
+ const exp = BACKOFF_BASE_MS * Math.pow(2, Math.floor(attempt));
164
+ return Math.min(MAX_BACKOFF_MS, exp);
165
+ }
166
+ const DEFAULT_FLUSH_TIMEOUT_MS = 8_000;
167
+ export function telemetryIngestUrl(apiUrl) {
168
+ const base = apiUrl.replace(/\/+$/u, '');
169
+ return `${base}/api/pugi/telemetry/event`;
170
+ }
171
+ /**
172
+ * POST one batch. Same result-variant contract as
173
+ * `feedback/submitter.submitFeedback`. Never throws.
174
+ */
175
+ export async function postTelemetryBatch(events, config) {
176
+ if (events.length === 0) {
177
+ return { kind: 'ok', httpStatus: 204, accepted: 0, dropped: 0 };
178
+ }
179
+ const url = telemetryIngestUrl(config.apiUrl);
180
+ const fetchImpl = config.fetchImpl ?? fetch;
181
+ const timeoutMs = config.timeoutMs ?? DEFAULT_FLUSH_TIMEOUT_MS;
182
+ const controller = new AbortController();
183
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
184
+ try {
185
+ const headers = {
186
+ 'content-type': 'application/json',
187
+ 'user-agent': `pugi-cli/${PUGI_CLI_VERSION}`,
188
+ };
189
+ if (config.apiKey)
190
+ headers['authorization'] = `Bearer ${config.apiKey}`;
191
+ const res = await fetchImpl(url, {
192
+ method: 'POST',
193
+ headers,
194
+ body: JSON.stringify({ events }),
195
+ signal: controller.signal,
196
+ });
197
+ const status = res.status;
198
+ if (status >= 200 && status < 300) {
199
+ let accepted = events.length;
200
+ let dropped = 0;
201
+ try {
202
+ const body = (await res.json());
203
+ if (typeof body.accepted === 'number')
204
+ accepted = body.accepted;
205
+ if (typeof body.dropped === 'number')
206
+ dropped = body.dropped;
207
+ }
208
+ catch {
209
+ // Body absent / not JSON — server still acked 2xx, treat as full success.
210
+ }
211
+ return { kind: 'ok', httpStatus: status, accepted, dropped };
212
+ }
213
+ if (status === 404) {
214
+ return {
215
+ kind: 'transient',
216
+ reason: 'admin-api /api/pugi/telemetry/event not deployed yet',
217
+ httpStatus: status,
218
+ };
219
+ }
220
+ if (status >= 500) {
221
+ return { kind: 'transient', reason: `server error ${status}`, httpStatus: status };
222
+ }
223
+ return { kind: 'permanent', reason: `client error ${status}`, httpStatus: status };
224
+ }
225
+ catch (err) {
226
+ const message = err instanceof Error ? err.message : String(err);
227
+ return { kind: 'transient', reason: `network: ${message}` };
228
+ }
229
+ finally {
230
+ clearTimeout(timer);
231
+ }
232
+ }
233
+ // ---------------------------------------------------------------------
234
+ // Helpers
235
+ // ---------------------------------------------------------------------
236
+ function countLines(s) {
237
+ let n = 0;
238
+ for (let i = 0; i < s.length; i += 1) {
239
+ if (s.charCodeAt(i) === 10)
240
+ n += 1;
241
+ }
242
+ return n;
243
+ }
244
+ /**
245
+ * Generate a session id for the REPL boot. UUID v4 — short enough to
246
+ * grep, long enough to be globally unique across concurrent processes.
247
+ */
248
+ export function newSessionId() {
249
+ return randomUUID();
250
+ }
251
+ //# sourceMappingURL=queue.js.map