@pugi/cli 0.1.0-beta.21 → 0.1.0-beta.22

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 (40) hide show
  1. package/dist/core/bare-mode/index.js +107 -0
  2. package/dist/core/diagnostics/probes/bare-mode.js +42 -0
  3. package/dist/core/engine/native-pugi.js +21 -10
  4. package/dist/core/engine/prompts.js +30 -2
  5. package/dist/core/engine/tool-bridge.js +32 -0
  6. package/dist/core/feedback/queue.js +177 -0
  7. package/dist/core/feedback/submitter.js +145 -0
  8. package/dist/core/onboarding/marker.js +111 -0
  9. package/dist/core/onboarding/telemetry-state.js +108 -0
  10. package/dist/core/output-style/presets.js +176 -0
  11. package/dist/core/output-style/state.js +185 -0
  12. package/dist/core/permissions/index.js +1 -1
  13. package/dist/core/permissions/state.js +55 -0
  14. package/dist/core/repl/session.js +375 -12
  15. package/dist/core/repl/slash-commands.js +99 -1
  16. package/dist/core/repl/workspace-context.js +22 -0
  17. package/dist/core/share/formatter.js +271 -0
  18. package/dist/core/share/redactor.js +221 -0
  19. package/dist/core/share/uploader.js +267 -0
  20. package/dist/core/todos/invariant.js +10 -0
  21. package/dist/core/todos/state.js +177 -0
  22. package/dist/runtime/cli.js +386 -1
  23. package/dist/runtime/commands/doctor.js +8 -0
  24. package/dist/runtime/commands/feedback.js +184 -0
  25. package/dist/runtime/commands/onboarding.js +275 -0
  26. package/dist/runtime/commands/plan.js +143 -0
  27. package/dist/runtime/commands/share.js +316 -0
  28. package/dist/runtime/commands/stickers.js +82 -0
  29. package/dist/runtime/commands/style.js +194 -0
  30. package/dist/runtime/version.js +1 -1
  31. package/dist/tools/registry.js +8 -0
  32. package/dist/tools/todo-write.js +184 -0
  33. package/dist/tui/compact-banner.js +28 -1
  34. package/dist/tui/conversation-pane.js +13 -0
  35. package/dist/tui/feedback-prompt.js +156 -0
  36. package/dist/tui/onboarding-wizard.js +240 -0
  37. package/dist/tui/repl-render.js +9 -1
  38. package/dist/tui/stickers-art.js +136 -0
  39. package/dist/tui/style-table.js +22 -0
  40. package/package.json +2 -2
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Leak L22 (2026-05-27) — `--bare` mode predicate.
3
+ *
4
+ * Mirror of Claude Code's `--bare` flag: when active the CLI behaves
5
+ * like a plain LLM frontend with NO project auto-discovery. Useful for:
6
+ *
7
+ * - headless scripting where the operator wants deterministic, repo-
8
+ * independent behavior (`pugi --bare --print "..."`),
9
+ * - dropping into a workspace without auto-creating `.pugi/`,
10
+ * - REPL sessions that should NOT inject ambient `PUGI.md` / `CLAUDE.md`
11
+ * into the model prompt,
12
+ * - support / triage flows where the engineer needs the CLI to act
13
+ * like a fresh install regardless of where it's invoked.
14
+ *
15
+ * Discovery surfaces gated by `isBareMode()`:
16
+ *
17
+ * 1. `PUGI.md` / `AGENTS.md` / `CLAUDE.md` / `GEMINI.md` parent-dir
18
+ * walk-up (`loadTraversedMarkdown` in `core/context/markdown-traverse.ts`).
19
+ * 2. Workspace-root markdown context (`loadMarkdownContext` consumers).
20
+ * 3. Auto-init `.pugi/` scaffold on REPL boot in untouched dirs.
21
+ * 4. Persona / skill auto-load from `.pugi/skills/`.
22
+ * 5. Workspace summary (`readPugiSummary`) read on REPL session start.
23
+ *
24
+ * Activation precedence — the bare bit is "sticky" once set so any
25
+ * subprocess the CLI spawns inherits it without re-passing the flag:
26
+ *
27
+ * 1. Top-level `--bare` arg parsed by `parseArgs` in `runtime/cli.ts`.
28
+ * The parser sets `process.env.PUGI_BARE='1'` BEFORE the dispatch
29
+ * flows so callsites checking the env see the activated state.
30
+ * 2. `PUGI_BARE=1` env var (any value matching `/^(1|true|yes|on)$/i`).
31
+ * 3. Default: bare mode OFF — full auto-discovery as before.
32
+ *
33
+ * This mirrors the existing `PUGI_SKIP_SPLASH` / `PUGI_NO_AUTO_INIT`
34
+ * env-flag pattern so the bare module fits the rest of the runtime
35
+ * configuration grammar without inventing a new wire.
36
+ *
37
+ * Test surface: `apps/pugi-cli/test/bare-mode.spec.ts` exercises the
38
+ * env precedence, value parsing, and the explicit-set / clear helpers.
39
+ */
40
+ /**
41
+ * Env var consulted by `isBareMode()`. Kept as an export so the spec
42
+ * + the runtime CLI can use the same constant — no string-typing of
43
+ * the wire name across modules.
44
+ */
45
+ export const PUGI_BARE_ENV = 'PUGI_BARE';
46
+ /**
47
+ * Truthy values recognised on the `PUGI_BARE` env. Anything else
48
+ * (empty string, `0`, `false`, `no`, `off`, `disabled`, undefined) is
49
+ * treated as bare-mode OFF. The list is intentionally short — the
50
+ * value is set by the CLI parser and is not customer-typed prose, so
51
+ * we do not need a permissive boolean coercion.
52
+ */
53
+ const TRUTHY = new Set(['1', 'true', 'yes', 'on']);
54
+ /**
55
+ * Return true when bare mode is active for the current process. Reads
56
+ * `process.env[PUGI_BARE_ENV]` and applies the truthy-value match.
57
+ *
58
+ * Safe to call from any module (no FS, no side-effects). The runtime
59
+ * cost is a single env-var lookup + lower-case + set membership, so
60
+ * gating hot-path callsites with `if (isBareMode()) return ...` adds
61
+ * effectively zero overhead in the default (non-bare) case.
62
+ */
63
+ export function isBareMode(env = process.env) {
64
+ const raw = env[PUGI_BARE_ENV];
65
+ if (typeof raw !== 'string' || raw.length === 0)
66
+ return false;
67
+ return TRUTHY.has(raw.toLowerCase());
68
+ }
69
+ /**
70
+ * Explicitly activate bare mode for the current process. Called by
71
+ * `parseArgs` in `runtime/cli.ts` when `--bare` is seen on the command
72
+ * line so downstream modules (engine, REPL bootstrap, doctor probe)
73
+ * see a consistent activated state via `isBareMode()` regardless of
74
+ * whether the operator set the env var manually or used the flag.
75
+ *
76
+ * Subprocess inheritance is the reason we mutate `process.env` rather
77
+ * than threading a `bare: boolean` field through every call signature
78
+ * — every Node child_process spawn inherits `process.env` by default,
79
+ * so the bare bit propagates to MCP servers / hook scripts / git
80
+ * subprocesses without ceremony.
81
+ */
82
+ export function setBareMode(env = process.env) {
83
+ env[PUGI_BARE_ENV] = '1';
84
+ }
85
+ /**
86
+ * Clear bare mode for the current process. Provided primarily for the
87
+ * spec so adjacent tests do not leak state between cases. Production
88
+ * code does NOT call this — bare mode is a one-shot per process.
89
+ */
90
+ export function clearBareMode(env = process.env) {
91
+ delete env[PUGI_BARE_ENV];
92
+ }
93
+ /**
94
+ * Human-readable one-line banner printed by the dispatcher when bare
95
+ * mode is active and the invocation is NOT JSON-only. Kept as a single
96
+ * constant so the spec can assert the exact wording and downstream
97
+ * tools (status bars, doctor row, REPL header) stay in lockstep.
98
+ */
99
+ export const BARE_MODE_BANNER = 'Pugi --bare mode: project auto-discovery disabled.';
100
+ /**
101
+ * Short label rendered inside the `pugi doctor` table when bare mode
102
+ * is active. The doctor probe surfaces `BARE MODE` as a separate row
103
+ * so operators triaging "why is Pugi ignoring my PUGI.md" see the
104
+ * cause without grep'ing the env.
105
+ */
106
+ export const BARE_MODE_DOCTOR_LABEL = 'BARE MODE';
107
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,42 @@
1
+ /**
2
+ * BARE MODE probe — Leak L22 (2026-05-27).
3
+ *
4
+ * Surfaces the `--bare` activation state inside `pugi doctor`. The row is
5
+ * informational: bare mode is an opt-in operator choice, never an error.
6
+ * Operators triaging "why is Pugi ignoring my PUGI.md / why was the
7
+ * `.pugi/` scaffold skipped" see the cause without grep'ing the env.
8
+ *
9
+ * Status semantics:
10
+ * - `skipped` when bare mode is OFF (default). The probe stays silent
11
+ * in the table since there is nothing to report; the row still
12
+ * renders so the JSON consumer can read a stable schema.
13
+ * - `ok` when bare mode is ON via `--bare` or `PUGI_BARE=1`. The detail
14
+ * enumerates the surfaces that are currently bypassed.
15
+ *
16
+ * No I/O — pure env probe. Wired into `buildDefaultProbes` in
17
+ * `runtime/commands/doctor.ts`.
18
+ */
19
+ import { isBareMode, BARE_MODE_DOCTOR_LABEL } from '../../bare-mode/index.js';
20
+ /**
21
+ * One-line summary printed in the `--bare` row when bare mode is on.
22
+ * Exported so the spec can assert the exact wording — operators reading
23
+ * `pugi doctor` should see the list of surfaces that the flag disables.
24
+ */
25
+ export const BARE_MODE_ACTIVE_DETAIL = 'bare mode active: PUGI.md walk-up + auto-init + persona auto-load disabled';
26
+ export const BARE_MODE_INACTIVE_DETAIL = 'bare mode off (default auto-discovery)';
27
+ export function probeBareMode(input = {}) {
28
+ const env = input.env ?? process.env;
29
+ if (isBareMode(env)) {
30
+ return {
31
+ name: BARE_MODE_DOCTOR_LABEL,
32
+ status: 'ok',
33
+ detail: BARE_MODE_ACTIVE_DETAIL,
34
+ };
35
+ }
36
+ return {
37
+ name: BARE_MODE_DOCTOR_LABEL,
38
+ status: 'skipped',
39
+ detail: BARE_MODE_INACTIVE_DETAIL,
40
+ };
41
+ }
42
+ //# sourceMappingURL=bare-mode.js.map
@@ -17,6 +17,7 @@ import { CancellationToken } from '../repl/cancellation.js';
17
17
  import { buildContextPrefix, spliceContextPrefix } from './context-prefix.js';
18
18
  import { applyIntentMarker, classifyIntent } from './intent.js';
19
19
  import { loadTraversedMarkdown } from '../context/markdown-traverse.js';
20
+ import { isBareMode } from '../bare-mode/index.js';
20
21
  // α7 L11 (2026-05-27): per-session DenialTrackingState. One instance
21
22
  // per `run()` so denials cluster by (tool, args) within the same
22
23
  // command but do NOT leak across CLI invocations.
@@ -234,18 +235,28 @@ export class NativePugiEngineAdapter {
234
235
  // lifetime of the session which is what the operator expects.
235
236
  const cwdForTraverse = process.cwd();
236
237
  let traverseResult;
237
- try {
238
- traverseResult = await loadTraversedMarkdown({
239
- cwd: cwdForTraverse,
240
- workspaceRoot: root,
241
- });
242
- }
243
- catch {
244
- // Per-dir markdown is a NICE-TO-HAVE; a fs error here must
245
- // never break the engine loop. Fall back to an empty result
246
- // so the prefix block still surfaces cwd + working set.
238
+ // Leak L22 (2026-05-27): `--bare` skips the parent-dir PUGI.md /
239
+ // AGENTS.md / CLAUDE.md / GEMINI.md walk-up. The engine sees only
240
+ // the operator's prompt + working-set + intent marker, with no
241
+ // ambient project context injection. Mirrors Claude Code's
242
+ // --bare semantics.
243
+ if (isBareMode()) {
247
244
  traverseResult = { loaded: [], warnings: [], totalBytes: 0 };
248
245
  }
246
+ else {
247
+ try {
248
+ traverseResult = await loadTraversedMarkdown({
249
+ cwd: cwdForTraverse,
250
+ workspaceRoot: root,
251
+ });
252
+ }
253
+ catch {
254
+ // Per-dir markdown is a NICE-TO-HAVE; a fs error here must
255
+ // never break the engine loop. Fall back to an empty result
256
+ // so the prefix block still surfaces cwd + working set.
257
+ traverseResult = { loaded: [], warnings: [], totalBytes: 0 };
258
+ }
259
+ }
249
260
  const intentClassification = classifyIntent(task.prompt);
250
261
  const intentHint = intentClassification.intent !== 'ambiguous' ? intentClassification.intent : undefined;
251
262
  const cwdRelative = relativeOrAbsolute(root, cwdForTraverse);
@@ -1,4 +1,6 @@
1
1
  import { getJobRegistry, summarizeJobsForPrompt, } from '../jobs/registry.js';
2
+ import { compileStyleBlock } from '../output-style/presets.js';
3
+ import { resolveOutputStyle } from '../output-style/state.js';
2
4
  /**
3
5
  * System prompts for each engine command. Each prompt:
4
6
  * - Anchors the model in Pugi's local-first contract (ADR-0037).
@@ -92,10 +94,36 @@ export function systemPromptFor(kind) {
92
94
  // voice gate are command-agnostic — a definitional question lands
93
95
  // the same way under `pugi explain` and `pugi code`.
94
96
  const withV2 = `${base}\n\n${PROMPT_V2_APPENDIX}`;
97
+ // Leak L18 (2026-05-27): output-style preset block. Compiled from
98
+ // workspace > user > default precedence. The `default` preset
99
+ // returns an empty block (no override over the base voice), so the
100
+ // injection is a no-op for the most-common case. Wrapped in
101
+ // try/catch — every IO failure inside `resolveOutputStyle` already
102
+ // degrades to the default slug, but defence in depth keeps the
103
+ // engine prompt assembly from ever crashing on a hand-edited
104
+ // config.json.
105
+ const styleBlock = formatOutputStyleBlock();
106
+ const withStyle = styleBlock ? `${withV2}\n\n${styleBlock}` : withV2;
95
107
  const snapshot = formatBackgroundJobsSnapshot(getJobRegistrySafely());
96
108
  if (!snapshot)
97
- return withV2;
98
- return `${withV2}\n\n${snapshot}`;
109
+ return withStyle;
110
+ return `${withStyle}\n\n${snapshot}`;
111
+ }
112
+ /**
113
+ * Resolve the active output-style preset for the current process
114
+ * and compile it into a prompt block. Returns empty string for the
115
+ * default preset OR for any unexpected IO failure so the engine
116
+ * prompt assembly path is unaffected by a missing / malformed
117
+ * config.json.
118
+ */
119
+ function formatOutputStyleBlock() {
120
+ try {
121
+ const resolved = resolveOutputStyle({ workspaceRoot: process.cwd() });
122
+ return compileStyleBlock(resolved.slug);
123
+ }
124
+ catch {
125
+ return '';
126
+ }
99
127
  }
100
128
  function baseSystemPromptFor(kind) {
101
129
  switch (kind) {
@@ -4,6 +4,7 @@ import { askUser } from '../../tools/ask-user.js';
4
4
  import { askUserQuestionJsonSchema, dispatchAskUserQuestion, } from '../../tools/ask-user-question.js';
5
5
  import { skillInvoke, skillList } from '../../tools/skill-tool.js';
6
6
  import { taskCreate, taskGet, taskList, taskUpdate, } from '../../tools/tasks.js';
7
+ import { dispatchTodoWrite, todoWriteJsonSchema, } from '../../tools/todo-write.js';
7
8
  import { webFetchTool } from '../../tools/web-fetch.js';
8
9
  import { webSearchTool } from '../../tools/web-search.js';
9
10
  import { agentTool } from '../../tools/agent-tool.js';
@@ -53,6 +54,12 @@ const READ_ONLY_TOOLS = new Set([
53
54
  'task_get',
54
55
  'task_list',
55
56
  'task_update',
57
+ // Leak L16 (2026-05-27): `todo_write` writes to `.pugi/todos.json`
58
+ // — metadata, not source. From the workspace's perspective it is
59
+ // read-only (no source mutation), so plan-mode keeps the tool
60
+ // available: planning a refactor frequently means writing the
61
+ // todo board BEFORE picking which file to touch.
62
+ 'todo_write',
56
63
  'web_fetch',
57
64
  // β1b T4 (2026-05-26): web_search is read-only from the workspace's
58
65
  // perspective (no file writes, no shell). Egress goes through the
@@ -82,6 +89,8 @@ const WIRED_TOOLS = new Set([
82
89
  'task_get',
83
90
  'task_list',
84
91
  'task_update',
92
+ // Leak L16: see READ_ONLY_TOOLS above for the rationale.
93
+ 'todo_write',
85
94
  'web_fetch',
86
95
  // β1b T4: see READ_ONLY_TOOLS above.
87
96
  'web_search',
@@ -190,6 +199,21 @@ export function buildToolsSchema(kind, options = { allowFetch: false, allowSearc
190
199
  },
191
200
  },
192
201
  });
202
+ // Leak L16 (2026-05-27): `todo_write` — batch TodoWrite mirror of
203
+ // Claude Code's upstream tool. Whereas `task_*` above is granular
204
+ // (one mutation per call, JSONL append, session-scoped),
205
+ // `todo_write` snapshots the FULL board in one call, JSON snapshot
206
+ // at `.pugi/todos.json`, workspace-scoped. Enforces the single-
207
+ // in-progress invariant at dispatch time: a batch with >1
208
+ // `in_progress` rejects with `TODO_INVARIANT_VIOLATED` and the
209
+ // on-disk board is left unchanged.
210
+ toolDefs.push({
211
+ name: 'todo_write',
212
+ description: 'Replace the workspace todo board (batch snapshot, not incremental). Emit the FULL todo list every call. ' +
213
+ 'At most ONE item may carry status="in_progress" — violations reject with TODO_INVARIANT_VIOLATED. ' +
214
+ 'Persisted atomically to .pugi/todos.json. Mirrors Claude Code TodoWrite verbatim.',
215
+ parameters: todoWriteJsonSchema,
216
+ });
193
217
  // β1 T2 → leak L5 (2026-05-27): structured AskUserQuestion bridge.
194
218
  // Schema upgraded to openclaude's multi-choice form: header chip +
195
219
  // {label, description} per option. Dispatcher accepts the structured
@@ -684,6 +708,14 @@ export function buildExecutor(input) {
684
708
  if (name === 'task_create' || name === 'task_get' || name === 'task_list' || name === 'task_update') {
685
709
  return dispatchTaskTool(name, args, { workspaceRoot, sessionId });
686
710
  }
711
+ if (name === 'todo_write') {
712
+ // Leak L16: batch TodoWrite. The dispatcher delegates the
713
+ // Zod validation + atomic persist to the tool module — any
714
+ // ZodError or `TODO_INVARIANT_VIOLATED` sentinel surfaces here
715
+ // as a thrown Error and lands on the catch arm below, which
716
+ // re-emits it through the PostToolUseFailure hook.
717
+ return dispatchTodoWrite({ workspaceRoot }, args);
718
+ }
687
719
  if (name === 'ask_user_question') {
688
720
  return dispatchAskUser(args, { interactive: Boolean(interactive), bridge: askUserBridge });
689
721
  }
@@ -0,0 +1,177 @@
1
+ /**
2
+ * Local feedback queue — Leak L21 (2026-05-27).
3
+ *
4
+ * `pugi feedback` POSTs collected operator feedback to the admin-api
5
+ * `/api/pugi/feedback` route. When that round-trip fails (endpoint
6
+ * missing, network down, server 5xx), the submitter falls back to
7
+ * appending the envelope to `<cwd>/.pugi/feedback-queue.jsonl`. On the
8
+ * next online session the flusher drains the queue silently in the
9
+ * background.
10
+ *
11
+ * # Module contract
12
+ *
13
+ * - Per-workspace storage. The queue file lives at
14
+ * `<cwd>/.pugi/feedback-queue.jsonl` so the operator-visible state
15
+ * stays alongside the project's other Pugi metadata. Multi-repo
16
+ * operators get one queue per repo — matches the rest of `.pugi/`.
17
+ *
18
+ * - JSONL append-only format. One envelope per line. Newlines inside
19
+ * the comment field are escaped as `\n` by `JSON.stringify`. The
20
+ * enqueue path uses an atomic `O_APPEND` write so concurrent
21
+ * `pugi feedback` invocations from a split-screen REPL + shell do
22
+ * not interleave half-records.
23
+ *
24
+ * - The flusher is best-effort. It returns counts but never throws —
25
+ * a failed flush leaves the queue untouched and a successful flush
26
+ * atomically rewrites the file with the remaining (unsubmitted)
27
+ * envelopes. Partial-success is the normal path when the server
28
+ * accepts the first N but 5xx's the (N+1)th.
29
+ *
30
+ * - The queue file is intentionally NOT readable by anything beyond
31
+ * the flusher. The operator's free-text comments are confidential
32
+ * — we do not surface them in `/status` / `/doctor` / telemetry.
33
+ *
34
+ * - All filesystem writes go through `mkdirSync({recursive: true})`
35
+ * so the first-ever enqueue on a fresh workspace lazily creates
36
+ * `.pugi/` without depending on an earlier `pugi init`.
37
+ */
38
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync, } from 'node:fs';
39
+ import { dirname, resolve } from 'node:path';
40
+ /**
41
+ * Resolve the queue file path for a workspace. Centralised so the
42
+ * submitter + flusher + tests agree on a single canonical location.
43
+ */
44
+ export function feedbackQueuePath(cwd) {
45
+ return resolve(cwd, '.pugi', 'feedback-queue.jsonl');
46
+ }
47
+ /**
48
+ * Append one envelope atomically. Uses `O_APPEND` semantics via
49
+ * `appendFileSync` so concurrent invocations from a split-screen
50
+ * REPL + shell cannot interleave bytes mid-line.
51
+ *
52
+ * Returns the absolute path written so callers can surface it in the
53
+ * "Feedback queued locally" toast.
54
+ */
55
+ export function enqueueFeedback(env, cwd) {
56
+ const path = feedbackQueuePath(cwd);
57
+ mkdirSync(dirname(path), { recursive: true });
58
+ // JSON.stringify of an object never emits raw newlines; the trailing
59
+ // '\n' is the line separator. JSONL parsers split on '\n' so the
60
+ // separator survives round-trips.
61
+ const line = `${JSON.stringify(env)}\n`;
62
+ appendFileSync(path, line, { encoding: 'utf8' });
63
+ return path;
64
+ }
65
+ export function readFeedbackQueue(cwd) {
66
+ const path = feedbackQueuePath(cwd);
67
+ if (!existsSync(path)) {
68
+ return { envelopes: [], parseErrors: [] };
69
+ }
70
+ const contents = readFileSync(path, 'utf8');
71
+ const lines = contents.split('\n');
72
+ const envelopes = [];
73
+ const parseErrors = [];
74
+ for (let i = 0; i < lines.length; i += 1) {
75
+ const raw = lines[i]?.trim();
76
+ if (!raw)
77
+ continue;
78
+ try {
79
+ const parsed = JSON.parse(raw);
80
+ // Minimal shape check — we don't full-validate here because the
81
+ // server is the trust boundary. Just guard against obvious
82
+ // corruption that would make the line un-submittable.
83
+ if (typeof parsed.category === 'string'
84
+ && typeof parsed.rating === 'number'
85
+ && typeof parsed.comment === 'string'
86
+ && typeof parsed.ts === 'string'
87
+ && typeof parsed.cliVersion === 'string') {
88
+ envelopes.push(parsed);
89
+ }
90
+ else {
91
+ parseErrors.push(i + 1);
92
+ }
93
+ }
94
+ catch {
95
+ parseErrors.push(i + 1);
96
+ }
97
+ }
98
+ return { envelopes, parseErrors };
99
+ }
100
+ /**
101
+ * Rewrite the queue file atomically with the remaining (unsubmitted)
102
+ * envelopes. Called by the flusher after a partial-success drain.
103
+ *
104
+ * Atomicity: write to a sibling `.tmp` then rename. On a crash mid-
105
+ * rewrite the original file is preserved (rename is atomic on POSIX
106
+ * + on NTFS via `MoveFileEx`).
107
+ */
108
+ export function rewriteFeedbackQueue(remaining, cwd) {
109
+ const path = feedbackQueuePath(cwd);
110
+ if (remaining.length === 0) {
111
+ // Clear the file by truncating to empty. Done in-place — we still
112
+ // want the file to exist (presence signals an active workspace)
113
+ // but with zero bytes so the next read returns no envelopes.
114
+ if (existsSync(path)) {
115
+ writeFileSync(path, '', { encoding: 'utf8' });
116
+ }
117
+ return;
118
+ }
119
+ mkdirSync(dirname(path), { recursive: true });
120
+ const tmp = `${path}.tmp`;
121
+ const body = remaining.map((env) => JSON.stringify(env)).join('\n') + '\n';
122
+ writeFileSync(tmp, body, { encoding: 'utf8' });
123
+ // Use writeFileSync's atomic-replace semantics by going through
124
+ // tmp + rename. Node's `fs.renameSync` is the atomic primitive
125
+ // on POSIX. We avoid `fs.writeFileSync` directly on `path`
126
+ // because writeFileSync truncates first which leaves a brief
127
+ // window of zero-byte state if the process is killed mid-write.
128
+ renameSync(tmp, path);
129
+ }
130
+ /**
131
+ * Drain the queue. Best-effort: each envelope is submitted in order;
132
+ * a `false` return keeps it in the queue for the next attempt; a
133
+ * `true` return removes it. After all envelopes are processed the
134
+ * queue file is rewritten with the unsubmitted ones.
135
+ *
136
+ * The function NEVER throws — it returns a structured result and
137
+ * the caller decides whether to log / surface failures. This keeps
138
+ * the silent-background-drain path on session-start safe.
139
+ */
140
+ export async function flushFeedbackQueue(cwd, submit) {
141
+ const { envelopes, parseErrors } = readFeedbackQueue(cwd);
142
+ if (envelopes.length === 0) {
143
+ return {
144
+ attempted: 0,
145
+ succeeded: 0,
146
+ failed: 0,
147
+ failedEnvelopes: [],
148
+ parseErrors,
149
+ };
150
+ }
151
+ let succeeded = 0;
152
+ const failedEnvelopes = [];
153
+ for (const env of envelopes) {
154
+ let ok = false;
155
+ try {
156
+ ok = await submit(env);
157
+ }
158
+ catch {
159
+ ok = false;
160
+ }
161
+ if (ok) {
162
+ succeeded += 1;
163
+ }
164
+ else {
165
+ failedEnvelopes.push(env);
166
+ }
167
+ }
168
+ rewriteFeedbackQueue(failedEnvelopes, cwd);
169
+ return {
170
+ attempted: envelopes.length,
171
+ succeeded,
172
+ failed: failedEnvelopes.length,
173
+ failedEnvelopes,
174
+ parseErrors,
175
+ };
176
+ }
177
+ //# sourceMappingURL=queue.js.map
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Feedback POST submitter — Leak L21 (2026-05-27).
3
+ *
4
+ * Submits one `FeedbackEnvelope` to the admin-api `/api/pugi/feedback`
5
+ * route. Designed for graceful degradation:
6
+ *
7
+ * - 200/201/204 → success
8
+ * - 404 / route not found → "endpoint missing, fall back to queue"
9
+ * - 4xx (other) → permanent — discard (do NOT requeue)
10
+ * - 5xx / network error / abort → transient — caller should enqueue
11
+ *
12
+ * The submitter does NOT touch the local queue. The caller wires the
13
+ * submitter to `enqueueFeedback` on a `transient` result, and to a
14
+ * silent log on a `permanent` failure. This split keeps the submitter
15
+ * a pure HTTP wrapper that the flusher (`flushFeedbackQueue`) can
16
+ * reuse without filesystem side effects.
17
+ */
18
+ const DEFAULT_TIMEOUT_MS = 8000;
19
+ /**
20
+ * Build the absolute submit URL from the base API URL. Centralised so
21
+ * the spec can reference one canonical place when asserting the
22
+ * outgoing path. The leading slash is normalised so a base URL with
23
+ * or without trailing slash both produce a well-formed URL.
24
+ */
25
+ export function feedbackSubmitUrl(apiUrl) {
26
+ const base = apiUrl.replace(/\/+$/u, '');
27
+ return `${base}/api/pugi/feedback`;
28
+ }
29
+ /**
30
+ * Submit one envelope. See `FeedbackSubmitResult` for the contract.
31
+ *
32
+ * Never throws — every failure path is mapped to a result variant so
33
+ * callers do not need a try/catch boundary.
34
+ */
35
+ export async function submitFeedback(env, config) {
36
+ const url = feedbackSubmitUrl(config.apiUrl);
37
+ const fetchImpl = config.fetchImpl ?? fetch;
38
+ const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
39
+ const controller = new AbortController();
40
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
41
+ try {
42
+ const headers = {
43
+ 'content-type': 'application/json',
44
+ 'user-agent': `pugi-cli/${env.cliVersion}`,
45
+ };
46
+ if (config.apiKey) {
47
+ headers['authorization'] = `Bearer ${config.apiKey}`;
48
+ }
49
+ const res = await fetchImpl(url, {
50
+ method: 'POST',
51
+ headers,
52
+ body: JSON.stringify(env),
53
+ signal: controller.signal,
54
+ });
55
+ const status = res.status;
56
+ if (status >= 200 && status < 300) {
57
+ return { kind: 'ok', httpStatus: status };
58
+ }
59
+ if (status === 404) {
60
+ // The most common transient cause: admin-api hasn't shipped the
61
+ // route yet. Treat as retry-worthy so once the controller lands
62
+ // a future flush picks it up.
63
+ return {
64
+ kind: 'transient',
65
+ reason: 'admin-api /api/pugi/feedback not deployed yet',
66
+ httpStatus: status,
67
+ };
68
+ }
69
+ if (status >= 500) {
70
+ return {
71
+ kind: 'transient',
72
+ reason: `server error ${status}`,
73
+ httpStatus: status,
74
+ };
75
+ }
76
+ // Any other 4xx — auth failure, payload rejected, rate-limit
77
+ // exceeded. None of those will fix themselves on a silent retry,
78
+ // so we mark them permanent. The operator sees a one-line error
79
+ // and the envelope is dropped (not queued).
80
+ return {
81
+ kind: 'permanent',
82
+ reason: `client error ${status}`,
83
+ httpStatus: status,
84
+ };
85
+ }
86
+ catch (err) {
87
+ const message = err instanceof Error ? err.message : String(err);
88
+ // AbortController.abort fires when the timeout elapses. We treat
89
+ // it as transient so the queue picks it up on the next online
90
+ // session. Same for plain network errors (`fetch failed`, ECONNREFUSED).
91
+ return { kind: 'transient', reason: `network: ${message}` };
92
+ }
93
+ finally {
94
+ clearTimeout(timer);
95
+ }
96
+ }
97
+ /**
98
+ * Bundle the last N turns of the conversation into a redacted
99
+ * `FeedbackSessionContext`. The redactor:
100
+ *
101
+ * - Caps at 5 turns (most recent). Older context is dropped — the
102
+ * submitter never sees it.
103
+ * - Truncates each turn to 240 chars + ellipsis. Operator comments
104
+ * are the primary signal; raw transcript is just disambiguation.
105
+ * - Strips bearer tokens, JWT-like blobs, and `PUGI_API_KEY=`-style
106
+ * env-var prefixes. Conservative — we'd rather drop a few
107
+ * non-secret characters than leak a key.
108
+ *
109
+ * The function is pure + sync so tests can pin its output without a
110
+ * worktree harness.
111
+ */
112
+ export function redactSessionContext(turns, options = {}) {
113
+ const lastFive = turns.slice(-5);
114
+ const previewed = lastFive.map((turn) => ({
115
+ role: turn.role,
116
+ preview: redactPreview(truncate(turn.text, 240)),
117
+ }));
118
+ return {
119
+ turnCount: previewed.length,
120
+ turns: previewed,
121
+ ...(options.gitBranch ? { gitBranch: options.gitBranch } : {}),
122
+ };
123
+ }
124
+ function truncate(s, max) {
125
+ if (s.length <= max)
126
+ return s;
127
+ return `${s.slice(0, max - 1)}…`;
128
+ }
129
+ /**
130
+ * Conservative secret-blanking. The rules:
131
+ * - Bearer tokens: `Bearer <token>` → `Bearer ***REDACTED***`
132
+ * - Long base64/JWT-ish blobs (≥ 40 chars of [A-Za-z0-9_-/=+]):
133
+ * replace the inner middle with `***`. Keeps a head + tail so the
134
+ * operator can still spot which kind of secret it was.
135
+ * - `PUGI_API_KEY=...` and similar `*_KEY=`/`*_TOKEN=` lookalikes:
136
+ * replace the value with `***REDACTED***`.
137
+ */
138
+ function redactPreview(s) {
139
+ let out = s;
140
+ out = out.replace(/bearer\s+[A-Za-z0-9._-]{20,}/giu, 'Bearer ***REDACTED***');
141
+ out = out.replace(/([A-Z][A-Z0-9_]*?(?:KEY|TOKEN|SECRET|PASSWORD))\s*=\s*\S+/gu, '$1=***REDACTED***');
142
+ out = out.replace(/\b([A-Za-z0-9_-]{6})[A-Za-z0-9_/+=-]{30,}([A-Za-z0-9_-]{4})\b/gu, '$1***$2');
143
+ return out;
144
+ }
145
+ //# sourceMappingURL=submitter.js.map