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

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 (63) hide show
  1. package/dist/core/auth/env-provider.js +238 -0
  2. package/dist/core/bare-mode/index.js +107 -0
  3. package/dist/core/diagnostics/probes/bare-mode.js +42 -0
  4. package/dist/core/diagnostics/probes/pugi-md.js +89 -0
  5. package/dist/core/engine/native-pugi.js +55 -11
  6. package/dist/core/engine/prompts.js +30 -2
  7. package/dist/core/engine/tool-bridge.js +32 -0
  8. package/dist/core/feedback/queue.js +177 -0
  9. package/dist/core/feedback/submitter.js +145 -0
  10. package/dist/core/onboarding/marker.js +111 -0
  11. package/dist/core/onboarding/telemetry-state.js +108 -0
  12. package/dist/core/output-style/presets.js +176 -0
  13. package/dist/core/output-style/state.js +185 -0
  14. package/dist/core/permissions/index.js +1 -1
  15. package/dist/core/permissions/state.js +55 -0
  16. package/dist/core/pugi-md/context-injector.js +76 -0
  17. package/dist/core/pugi-md/walk-up.js +207 -0
  18. package/dist/core/release-notes/parser.js +241 -0
  19. package/dist/core/release-notes/state.js +116 -0
  20. package/dist/core/repl/session.js +482 -12
  21. package/dist/core/repl/slash-commands.js +134 -1
  22. package/dist/core/repl/workspace-context.js +22 -0
  23. package/dist/core/share/formatter.js +271 -0
  24. package/dist/core/share/redactor.js +221 -0
  25. package/dist/core/share/uploader.js +267 -0
  26. package/dist/core/theme/context.js +91 -0
  27. package/dist/core/theme/presets.js +228 -0
  28. package/dist/core/theme/state.js +181 -0
  29. package/dist/core/todos/invariant.js +10 -0
  30. package/dist/core/todos/state.js +177 -0
  31. package/dist/core/vim/keymap.js +288 -0
  32. package/dist/core/vim/state.js +92 -0
  33. package/dist/runtime/cli.js +603 -15
  34. package/dist/runtime/commands/doctor.js +21 -0
  35. package/dist/runtime/commands/feedback.js +184 -0
  36. package/dist/runtime/commands/onboarding.js +275 -0
  37. package/dist/runtime/commands/plan.js +143 -0
  38. package/dist/runtime/commands/release-notes.js +229 -0
  39. package/dist/runtime/commands/share.js +316 -0
  40. package/dist/runtime/commands/stickers.js +82 -0
  41. package/dist/runtime/commands/style.js +194 -0
  42. package/dist/runtime/commands/theme.js +196 -0
  43. package/dist/runtime/commands/vim.js +140 -0
  44. package/dist/runtime/version.js +1 -1
  45. package/dist/tools/registry.js +8 -0
  46. package/dist/tools/todo-write.js +184 -0
  47. package/dist/tui/compact-banner.js +28 -1
  48. package/dist/tui/conversation-pane.js +13 -0
  49. package/dist/tui/doctor-table.js +32 -17
  50. package/dist/tui/feedback-prompt.js +156 -0
  51. package/dist/tui/onboarding-wizard.js +240 -0
  52. package/dist/tui/repl-render.js +26 -3
  53. package/dist/tui/repl.js +9 -1
  54. package/dist/tui/stickers-art.js +136 -0
  55. package/dist/tui/style-table.js +28 -0
  56. package/dist/tui/theme-table.js +29 -0
  57. package/dist/tui/vim-input.js +267 -0
  58. package/package.json +2 -2
  59. package/dist/core/engine/compaction-hook.js +0 -154
  60. package/dist/core/init/scaffold.js +0 -195
  61. package/dist/core/repl/codebase-survey.js +0 -308
  62. package/dist/core/repl/init-interview.js +0 -457
  63. package/dist/core/repl/onboarding-state.js +0 -297
@@ -0,0 +1,184 @@
1
+ /**
2
+ * todo_write tool — Leak L16 (TodoWrite single-in-progress invariant).
3
+ *
4
+ * Mirrors Claude Code's `TodoWrite` tool 1:1 so a model trained on the
5
+ * upstream grammar speaks Pugi's variant verbatim. The tool dispatches
6
+ * a BATCH replace of the workspace todo board (not an incremental
7
+ * mutation — the model emits the FULL list every call). At most ONE
8
+ * todo may carry `status: 'in_progress'` at any time; violations
9
+ * reject with the `TODO_INVARIANT_VIOLATED` sentinel and the board on
10
+ * disk is left unchanged.
11
+ *
12
+ * Relationship to `task_*` (β1 T1/T6, tools/tasks.ts):
13
+ * - `task_*` is GRANULAR (create/get/list/update one task at a
14
+ * time) with an append-only JSONL journal scoped to the SESSION.
15
+ * - `todo_write` is BATCH (snapshot the whole board) with an atomic
16
+ * JSON snapshot scoped to the WORKSPACE.
17
+ * They are complementary surfaces: agents that prefer the upstream
18
+ * TodoWrite grammar use `todo_write`; agents that want a fine-grained
19
+ * audit trail use `task_*`.
20
+ *
21
+ * Hard rules (enforced by Zod + dispatcher):
22
+ * - `todos.length` ≤ 50 (board overload guard).
23
+ * - Every item: id (≥1 char, ≤128), content (≥1 char), status enum.
24
+ * - At most ONE item with `status === 'in_progress'`.
25
+ * - All ids unique within the batch.
26
+ *
27
+ * Dispatch returns the persisted board as JSON; callers can read
28
+ * `todos: [...]` directly. Errors return the sentinel-prefixed message
29
+ * so the engine adapter can pattern-match.
30
+ */
31
+ import { z } from 'zod';
32
+ import { saveTodoBoard } from '../core/todos/state.js';
33
+ /** Cap matches the `task_*` family's title cap for parity. */
34
+ export const TODO_CONTENT_MAX = 2_000;
35
+ /** id is opaque to us but must be slug-safe so file paths could embed it. */
36
+ export const TODO_ID_MIN = 1;
37
+ export const TODO_ID_MAX = 128;
38
+ /** Hard cap on board size. Beyond this the operator should split work. */
39
+ export const TODO_BATCH_MAX = 50;
40
+ export const todoItemSchema = z
41
+ .strictObject({
42
+ id: z
43
+ .string()
44
+ .min(TODO_ID_MIN)
45
+ .max(TODO_ID_MAX)
46
+ .describe('Stable id for this todo. Opaque, ≤128 chars.'),
47
+ content: z
48
+ .string()
49
+ .min(1)
50
+ .max(TODO_CONTENT_MAX)
51
+ .describe('Imperative task description. E.g. "Add invariant check".'),
52
+ status: z
53
+ .enum(['pending', 'in_progress', 'completed'])
54
+ .describe('Lifecycle status. At most ONE in_progress per board.'),
55
+ activeForm: z
56
+ .string()
57
+ .min(1)
58
+ .max(TODO_CONTENT_MAX)
59
+ .optional()
60
+ .describe('Present-continuous form. E.g. "Adding invariant check".'),
61
+ });
62
+ export const todoWriteArgsSchema = z.strictObject({
63
+ todos: z
64
+ .array(todoItemSchema)
65
+ .max(TODO_BATCH_MAX)
66
+ .describe(`Full todo board (batch replace, not incremental). Max ${TODO_BATCH_MAX} items. ` +
67
+ `At most ONE item may carry status="in_progress".`),
68
+ });
69
+ /**
70
+ * JSON-Schema fragment surfaced to the model via the tool-bridge
71
+ * `parameters` field. Mirrors the Zod schema 1:1 — kept hand-written
72
+ * (same convention as ask_user_question) because the runtime engine
73
+ * wires OpenAI-compatible JSON Schema and we have not greenlit the
74
+ * zod-to-json-schema transitive dep. Keep both in lockstep.
75
+ */
76
+ export const todoWriteJsonSchema = {
77
+ type: 'object',
78
+ additionalProperties: false,
79
+ required: ['todos'],
80
+ properties: {
81
+ todos: {
82
+ type: 'array',
83
+ maxItems: TODO_BATCH_MAX,
84
+ description: `Full todo board (batch replace, not incremental). Max ${TODO_BATCH_MAX} items. ` +
85
+ `At most ONE item may carry status="in_progress".`,
86
+ items: {
87
+ type: 'object',
88
+ additionalProperties: false,
89
+ required: ['id', 'content', 'status'],
90
+ properties: {
91
+ id: {
92
+ type: 'string',
93
+ minLength: TODO_ID_MIN,
94
+ maxLength: TODO_ID_MAX,
95
+ description: 'Stable id for this todo. Opaque, ≤128 chars.',
96
+ },
97
+ content: {
98
+ type: 'string',
99
+ minLength: 1,
100
+ maxLength: TODO_CONTENT_MAX,
101
+ description: 'Imperative task description.',
102
+ },
103
+ status: {
104
+ type: 'string',
105
+ enum: ['pending', 'in_progress', 'completed'],
106
+ description: 'Lifecycle status. At most ONE in_progress per board.',
107
+ },
108
+ activeForm: {
109
+ type: 'string',
110
+ minLength: 1,
111
+ maxLength: TODO_CONTENT_MAX,
112
+ description: 'Present-continuous form.',
113
+ },
114
+ },
115
+ },
116
+ },
117
+ },
118
+ };
119
+ /**
120
+ * Sentinel prefix the dispatcher returns when Zod schema validation
121
+ * rejects the raw arguments. Distinct from `TODO_INVARIANT_VIOLATED`
122
+ * (>1 in_progress) and `TODO_DUPLICATE_ID` (collision within batch),
123
+ * which are emitted from `saveTodoBoard` AFTER schema parsing.
124
+ *
125
+ * Surfaced as a return string (not a throw) so the engine adapter sees
126
+ * a recoverable tool error and the model can self-correct its args,
127
+ * instead of the engine loop tearing down on an uncaught ZodError.
128
+ */
129
+ export const TODO_INVALID_ARGS = 'INVALID_ARGS';
130
+ /**
131
+ * Render a ZodError into a deterministic `INVALID_ARGS: ...` sentinel
132
+ * the model can pattern-match. Each issue contributes one
133
+ * `path: message` clause; clauses are joined with `; ` so the model
134
+ * sees every offence in a single line. Path with the root scope is
135
+ * rendered as `<root>` to avoid an empty colon.
136
+ */
137
+ function renderZodIssues(error) {
138
+ const parts = error.issues.map((issue) => {
139
+ const path = issue.path.length === 0 ? '<root>' : issue.path.join('.');
140
+ return `${path}: ${issue.message}`;
141
+ });
142
+ return `${TODO_INVALID_ARGS}: ${parts.join('; ')}`;
143
+ }
144
+ /**
145
+ * Validate via Zod + persist atomically. Surfaces three sentinel
146
+ * families the dispatcher pattern-matches on:
147
+ * - `INVALID_ARGS: <path>: <issue>; ...` — Zod schema rejected
148
+ * the raw arguments (returned as STRING, not thrown).
149
+ * - `TODO_INVARIANT_VIOLATED: ...` — >1 in_progress
150
+ * (thrown by `saveTodoBoard`).
151
+ * - `TODO_DUPLICATE_ID: ...` — collision within batch
152
+ * (thrown by `saveTodoBoard`).
153
+ *
154
+ * Why the asymmetry: schema rejection means the model emitted malformed
155
+ * structure (missing field, wrong type) and CAN self-correct given a
156
+ * clear breakdown of the offending path. The invariant + duplicate-id
157
+ * paths mean the model emitted structurally-valid but semantically
158
+ * conflicting state — those still throw so the engine loop's tool-error
159
+ * hook can surface them through `PostToolUseFailure` for observability,
160
+ * mirroring how the file-tools layer surfaces `STALE_READ` / `PermissionDenied`.
161
+ */
162
+ export function dispatchTodoWrite(ctx, rawArgs) {
163
+ // L16 P1 fix (2026-05-27): `.parse` throws a `ZodError` on validation
164
+ // failure. The previous implementation let that throw bubble through
165
+ // the engine adapter's catch arm as a free-form `error.message`,
166
+ // which (a) loses the issue-by-issue structure the model needs to
167
+ // self-correct, and (b) tears down the tool-call as a hard failure
168
+ // rather than a recoverable tool result. Switch to `safeParse` and
169
+ // emit a structured `INVALID_ARGS: <path>: <issue>; ...` sentinel
170
+ // string instead — the engine sees a successful tool call, the model
171
+ // sees the offending paths, and the dispatcher's catch arm reserves
172
+ // throws for the genuine semantic conflicts emitted by `saveTodoBoard`.
173
+ const parsed = todoWriteArgsSchema.safeParse(rawArgs);
174
+ if (!parsed.success) {
175
+ return renderZodIssues(parsed.error);
176
+ }
177
+ const stateCtx = {
178
+ workspaceRoot: ctx.workspaceRoot,
179
+ ...(ctx.now ? { now: ctx.now } : {}),
180
+ };
181
+ const board = saveTodoBoard(stateCtx, parsed.data.todos);
182
+ return JSON.stringify(board);
183
+ }
184
+ //# sourceMappingURL=todo-write.js.map
@@ -36,14 +36,27 @@ export function CompactBanner(props) {
36
36
  * Build the centred label. Examples:
37
37
  * "context compacted (12 turns → 1 summary, auto)"
38
38
  * "context compacted (4 turns → 1 summary, manual · ~3.2k tokens)"
39
+ * "context compacted (12 turns → summary at 14:32, auto)"
40
+ * "context compacted (12 turns → 1 summary, manual) · 6 turns ago"
39
41
  */
40
42
  export function buildLabel(props) {
41
43
  const trigger = props.trigger === 'auto' ? 'auto' : 'manual';
42
44
  const turns = `${props.turnsBefore} ${props.turnsBefore === 1 ? 'turn' : 'turns'}`;
45
+ const summarySlot = typeof props.summaryAtEpochMs === 'number' && props.summaryAtEpochMs > 0
46
+ ? `summary at ${formatClock(props.summaryAtEpochMs)}`
47
+ : '1 summary';
43
48
  const tokens = props.summaryTokenCount && props.summaryTokenCount > 0
44
49
  ? ` · ~${formatTokens(props.summaryTokenCount)} tokens`
45
50
  : '';
46
- return `context compacted (${turns} → 1 summary, ${trigger}${tokens})`;
51
+ const base = `context compacted (${turns} → ${summarySlot}, ${trigger}${tokens})`;
52
+ // L29 history-replay suffix. Only render when the boundary has live
53
+ // turns following it — a fresh in-REPL `/compact` lands with
54
+ // `turnsAgo === 0` and we keep the label compact.
55
+ if (typeof props.turnsAgo === 'number' && props.turnsAgo > 0) {
56
+ const ago = `${props.turnsAgo} ${props.turnsAgo === 1 ? 'turn' : 'turns'} ago`;
57
+ return `${base} · ${ago}`;
58
+ }
59
+ return base;
47
60
  }
48
61
  /** Format token counts like 1234 → 1.2k, 950 → 950. */
49
62
  function formatTokens(n) {
@@ -51,4 +64,18 @@ function formatTokens(n) {
51
64
  return `${n}`;
52
65
  return `${(n / 1000).toFixed(1)}k`;
53
66
  }
67
+ /**
68
+ * Render an epoch-ms instant as a deterministic `HH:MM` clock in the
69
+ * operator's local timezone. Used only inside the centred label so a
70
+ * boundary that landed mid-session reads `summary at 14:32` instead of
71
+ * the generic `1 summary`. Pure (no side effects), constant-time.
72
+ */
73
+ function formatClock(epochMs) {
74
+ const d = new Date(epochMs);
75
+ if (Number.isNaN(d.getTime()))
76
+ return '--:--';
77
+ const hh = d.getHours().toString().padStart(2, '0');
78
+ const mm = d.getMinutes().toString().padStart(2, '0');
79
+ return `${hh}:${mm}`;
80
+ }
54
81
  //# sourceMappingURL=compact-banner.js.map
@@ -1,6 +1,7 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { Box, Text } from 'ink';
3
3
  import { MarkdownRender } from './markdown-render.js';
4
+ import { CompactBanner } from './compact-banner.js';
4
5
  const HUE_COLOR_BY_SLUG = {
5
6
  // Mira (Pug) - coordinator
6
7
  main: 'cyan',
@@ -39,6 +40,18 @@ function ConversationRow({ row, personaNames, }) {
39
40
  return (_jsxs(Box, { children: [_jsx(Text, { bold: true, color: "#3da9fc", children: '› ' }), _jsx(Text, { children: row.text })] }));
40
41
  case 'system':
41
42
  return (_jsxs(Box, { children: [_jsx(Text, { dimColor: true, children: '· ' }), _jsx(Text, { dimColor: true, children: row.text })] }));
43
+ case 'compact-boundary': {
44
+ // L29 (2026-05-27): structured render. When the row carries the
45
+ // `compaction` payload, drive the Ink banner directly so the
46
+ // operator sees a width-aware gray separator with the canonical
47
+ // label. Fallback: a legacy boundary missing the structured
48
+ // payload (older replay events, hand-built rows) renders through
49
+ // the dim text path so the operator still sees the marker.
50
+ if (row.compaction) {
51
+ return (_jsx(CompactBanner, { turnsBefore: row.compaction.turnsBefore, trigger: row.compaction.trigger, summaryTokenCount: row.compaction.summaryTokenCount, turnsAgo: row.compaction.turnsAgo, summaryAtEpochMs: row.timestampEpochMs, columns: process.stdout?.columns }));
52
+ }
53
+ return (_jsx(Box, { children: _jsx(Text, { dimColor: true, children: row.text }) }));
54
+ }
42
55
  case 'persona': {
43
56
  const slug = row.personaSlug ?? '';
44
57
  const color = HUE_COLOR_BY_SLUG[slug] ?? 'white';
@@ -1,31 +1,46 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { Box, Text } from 'ink';
3
- /** Brand-voice palette for status cells. Mirrors the table chrome
4
- * used by `<AgentProgressCard>` so the operator's eye trains on a
5
- * consistent OK/WARN/ERROR/SKIPPED colour grammar. */
6
- const STATUS_COLOR = {
7
- ok: 'green',
8
- warn: 'yellow',
9
- error: 'red',
10
- skipped: 'gray',
11
- };
12
- const OVERALL_COLOR = {
13
- healthy: 'green',
14
- warning: 'yellow',
15
- error: 'red',
16
- };
3
+ import { useTheme } from '../core/theme/context.js';
4
+ /**
5
+ * Leak L30 (2026-05-27): status colors flow through the active theme
6
+ * instead of being hard-coded Ink color names. The `colorblind`
7
+ * preset re-maps OK/WARN/ERROR to a blue-yellow-magenta axis so
8
+ * deuteranopia operators can still distinguish the three states; the
9
+ * `default` / `dark` / `light` themes route to green/yellow/red
10
+ * variants tuned for each background. `skipped` keeps a muted color
11
+ * (theme-controlled muted token) so dimmed rows still pick up the
12
+ * theme tint.
13
+ */
14
+ function buildStatusColor(theme) {
15
+ return {
16
+ ok: theme.success,
17
+ warn: theme.warning,
18
+ error: theme.error,
19
+ skipped: theme.muted,
20
+ };
21
+ }
22
+ function buildOverallColor(theme) {
23
+ return {
24
+ healthy: theme.success,
25
+ warning: theme.warning,
26
+ error: theme.error,
27
+ };
28
+ }
17
29
  export function DoctorTable({ envelope }) {
30
+ const theme = useTheme();
31
+ const statusColor = buildStatusColor(theme);
32
+ const overallColor = buildOverallColor(theme);
18
33
  const nameWidth = Math.max('NAME'.length, ...envelope.probes.map((row) => row.name.length));
19
34
  const statusWidth = Math.max('STATUS'.length, ...envelope.probes.map((row) => row.status.length));
20
- return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Box, { marginBottom: 1, children: _jsx(Text, { bold: true, children: "Pugi Doctor" }) }), envelope.probes.map((row) => (_jsx(DoctorRow, { row: row, nameWidth: nameWidth, statusWidth: statusWidth }, row.name))), _jsx(Box, { marginTop: 1, children: _jsxs(Text, { children: [envelope.counts.error, " error(s), ", envelope.counts.warn, " warning(s), ", envelope.counts.ok, " ok,", ' ', envelope.counts.skipped, " skipped. Overall:", ' ', _jsx(Text, { color: OVERALL_COLOR[envelope.overall], bold: true, children: envelope.overall.toUpperCase() })] }) }), _jsx(Box, { children: _jsxs(Text, { dimColor: true, children: ["CLI ", envelope.meta.cliVersion, " Node ", envelope.meta.nodeVersion, " cwd ", envelope.meta.cwd] }) })] }));
35
+ return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Box, { marginBottom: 1, children: _jsx(Text, { bold: true, children: "Pugi Doctor" }) }), envelope.probes.map((row) => (_jsx(DoctorRow, { row: row, nameWidth: nameWidth, statusWidth: statusWidth, statusColor: statusColor }, row.name))), _jsx(Box, { marginTop: 1, children: _jsxs(Text, { children: [envelope.counts.error, " error(s), ", envelope.counts.warn, " warning(s), ", envelope.counts.ok, " ok,", ' ', envelope.counts.skipped, " skipped. Overall:", ' ', _jsx(Text, { color: overallColor[envelope.overall], bold: true, children: envelope.overall.toUpperCase() })] }) }), _jsx(Box, { children: _jsxs(Text, { dimColor: true, children: ["CLI ", envelope.meta.cliVersion, " Node ", envelope.meta.nodeVersion, " cwd ", envelope.meta.cwd] }) })] }));
21
36
  }
22
- function DoctorRow({ row, nameWidth, statusWidth }) {
37
+ function DoctorRow({ row, nameWidth, statusWidth, statusColor }) {
23
38
  const namePart = row.name.padEnd(nameWidth, ' ');
24
39
  const statusPart = row.status.toUpperCase().padEnd(statusWidth, ' ');
25
40
  const latencyPart = typeof row.latencyMs === 'number' ? ` (${row.latencyMs}ms)` : '';
26
41
  const showRemediation = typeof row.remediation === 'string' &&
27
42
  row.remediation.length > 0 &&
28
43
  (row.status === 'warn' || row.status === 'error');
29
- return (_jsxs(Box, { flexDirection: "column", children: [_jsxs(Box, { children: [_jsxs(Text, { children: [namePart, " "] }), _jsx(Text, { color: STATUS_COLOR[row.status], bold: true, children: statusPart }), _jsxs(Text, { children: [' ', row.detail, latencyPart] })] }), showRemediation && (_jsx(Box, { marginLeft: nameWidth + statusWidth + 4, children: _jsxs(Text, { dimColor: true, children: ["\u2192 ", row.remediation] }) }))] }));
44
+ return (_jsxs(Box, { flexDirection: "column", children: [_jsxs(Box, { children: [_jsxs(Text, { children: [namePart, " "] }), _jsx(Text, { color: statusColor[row.status], bold: true, children: statusPart }), _jsxs(Text, { children: [' ', row.detail, latencyPart] })] }), showRemediation && (_jsx(Box, { marginLeft: nameWidth + statusWidth + 4, children: _jsxs(Text, { dimColor: true, children: ["\u2192 ", row.remediation] }) }))] }));
30
45
  }
31
46
  //# sourceMappingURL=doctor-table.js.map
@@ -0,0 +1,156 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ /**
3
+ * `/feedback` interactive prompt — Leak L21 (2026-05-27).
4
+ *
5
+ * Five-step wizard mounted from both the top-level `pugi feedback`
6
+ * shell handler and the in-REPL `/feedback` slash. Steps:
7
+ *
8
+ * 1. category — bug / feature / general / praise (numeric pick 1-4)
9
+ * 2. rating — 1-5 stars (numeric pick 1-5)
10
+ * 3. comment — free-text, multi-line, Ctrl-D submits, Esc cancels
11
+ * 4. context — y/n include last 5 turns (redacted)? default no
12
+ * 5. confirm — y/n submit?
13
+ *
14
+ * Brand voice gate: ASCII glyphs only, no em-dashes, no banned brand
15
+ * words. Copy is intentionally power-word neutral so the future i18n
16
+ * landing localises cleanly.
17
+ *
18
+ * The component is PURE in the Ink sense — props in, one terminal
19
+ * `onResolve` event out. The caller owns the submit + queue logic.
20
+ *
21
+ * The verdict the operator submits is:
22
+ * - `{ cancelled: true }` when the operator presses Esc at any step
23
+ * - `{ cancelled: false, draft }` when the wizard completes
24
+ *
25
+ * `draft` is the assembled `FeedbackDraft` — NOT yet a full envelope
26
+ * (the caller still injects `ts` + `cliVersion` + maybe `tier`).
27
+ */
28
+ import { useState } from 'react';
29
+ import { Box, Text, render, useApp, useInput } from 'ink';
30
+ const CATEGORIES = [
31
+ { value: 'bug', label: 'bug', gloss: 'something broke or behaves unexpectedly' },
32
+ { value: 'feature', label: 'feature', gloss: 'request a new capability' },
33
+ { value: 'general', label: 'general', gloss: 'observation, idea, comment' },
34
+ { value: 'praise', label: 'praise', gloss: 'positive note for the team' },
35
+ ];
36
+ export function FeedbackPrompt(props) {
37
+ const [step, setStep] = useState('category');
38
+ const [category, setCategory] = useState(null);
39
+ const [rating, setRating] = useState(null);
40
+ const [commentBuffer, setCommentBuffer] = useState('');
41
+ const [includeContext, setIncludeContext] = useState(false);
42
+ useInput((input, key) => {
43
+ if (key.escape) {
44
+ props.onResolve({ cancelled: true });
45
+ return;
46
+ }
47
+ if (step === 'category') {
48
+ const n = Number.parseInt(input, 10);
49
+ if (!Number.isNaN(n) && n >= 1 && n <= CATEGORIES.length) {
50
+ const picked = CATEGORIES[n - 1];
51
+ if (picked) {
52
+ setCategory(picked.value);
53
+ setStep('rating');
54
+ }
55
+ }
56
+ return;
57
+ }
58
+ if (step === 'rating') {
59
+ const n = Number.parseInt(input, 10);
60
+ if (!Number.isNaN(n) && n >= 1 && n <= 5) {
61
+ setRating(n);
62
+ setStep('comment');
63
+ }
64
+ return;
65
+ }
66
+ if (step === 'comment') {
67
+ // Ctrl-D submits the comment (even when empty — rating-only
68
+ // feedback is allowed). Enter inserts a newline so the
69
+ // operator can write multi-line bug repros without the wizard
70
+ // ending the buffer prematurely.
71
+ if (key.ctrl && (input === 'd' || input === '')) {
72
+ setStep('context');
73
+ return;
74
+ }
75
+ if (key.return) {
76
+ setCommentBuffer((prev) => prev + '\n');
77
+ return;
78
+ }
79
+ if (key.backspace || key.delete) {
80
+ setCommentBuffer((prev) => prev.slice(0, -1));
81
+ return;
82
+ }
83
+ // Printable characters land in the buffer. We accept anything
84
+ // non-empty + non-control. Ink's useInput sometimes delivers
85
+ // multi-char paste bursts as one `input` — we append the whole
86
+ // burst so paste lands intact.
87
+ if (input && !key.ctrl && !key.meta) {
88
+ setCommentBuffer((prev) => prev + input);
89
+ }
90
+ return;
91
+ }
92
+ if (step === 'context') {
93
+ if (input === 'y' || input === 'Y') {
94
+ setIncludeContext(true);
95
+ setStep('confirm');
96
+ return;
97
+ }
98
+ if (input === 'n' || input === 'N' || key.return) {
99
+ // Default no — Enter at the context prompt picks "no" so
100
+ // the operator can blast through with all defaults.
101
+ setIncludeContext(false);
102
+ setStep('confirm');
103
+ return;
104
+ }
105
+ return;
106
+ }
107
+ if (step === 'confirm') {
108
+ if (input === 'y' || input === 'Y' || key.return) {
109
+ if (category != null && rating != null) {
110
+ props.onResolve({
111
+ cancelled: false,
112
+ draft: {
113
+ category,
114
+ rating,
115
+ comment: commentBuffer,
116
+ includeSessionContext: includeContext,
117
+ },
118
+ });
119
+ }
120
+ return;
121
+ }
122
+ if (input === 'n' || input === 'N') {
123
+ props.onResolve({ cancelled: true });
124
+ return;
125
+ }
126
+ return;
127
+ }
128
+ }, { isActive: !props.inert });
129
+ return (_jsxs(Box, { flexDirection: "column", borderStyle: "round", borderColor: "cyan", paddingX: 1, children: [_jsxs(Box, { marginBottom: 1, children: [_jsx(Text, { bold: true, color: "cyan", children: "Pugi /feedback" }), _jsx(Text, { children: " \u2014 share what you saw. Esc cancels at any step." })] }), step === 'category' && (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { bold: true, children: "1. Category" }), CATEGORIES.map((c, idx) => (_jsx(Text, { children: ` ${idx + 1}. ${c.label.padEnd(8)} ${c.gloss}` }, c.value))), _jsx(Box, { marginTop: 1, children: _jsx(Text, { dimColor: true, children: "Pick 1-4." }) })] })), step === 'rating' && (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { bold: true, children: "2. Rating" }), _jsx(Text, { children: ` 1=poor, 5=excellent. Picked category: ${category ?? '?'}` }), _jsx(Box, { marginTop: 1, children: _jsx(Text, { dimColor: true, children: "Pick 1-5." }) })] })), step === 'comment' && (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { bold: true, children: "3. Comment" }), _jsx(Text, { dimColor: true, children: "Multi-line. Enter inserts a newline. Ctrl-D submits." }), _jsx(Box, { marginTop: 1, flexDirection: "column", children: commentBuffer.length === 0 ? (_jsx(Text, { dimColor: true, children: "(empty \u2014 Ctrl-D submits without a comment)" })) : (commentBuffer.split('\n').map((line, idx) => (_jsx(Text, { children: `> ${line}` }, idx)))) })] })), step === 'context' && (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { bold: true, children: "4. Include session context?" }), _jsx(Text, { children: ' Last 5 turns, redacted (tokens / *_KEY=* values stripped).' }), _jsx(Box, { marginTop: 1, children: _jsx(Text, { dimColor: true, children: "y / n \u2014 default n (Enter)." }) })] })), step === 'confirm' && (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { bold: true, children: "5. Submit?" }), _jsx(Text, { children: ` category=${category ?? '?'} rating=${rating ?? '?'} context=${includeContext ? 'yes' : 'no'}` }), _jsx(Text, { children: ` comment=${commentBuffer.length} chars` }), _jsx(Box, { marginTop: 1, children: _jsx(Text, { dimColor: true, children: "y / n \u2014 default y (Enter)." }) })] }))] }));
130
+ }
131
+ export async function renderFeedbackPrompt() {
132
+ let resolveOuter;
133
+ const outerPromise = new Promise((resolve) => {
134
+ resolveOuter = resolve;
135
+ });
136
+ function App() {
137
+ const { exit } = useApp();
138
+ return (_jsx(FeedbackPrompt, { onResolve: (verdict) => {
139
+ resolveOuter(verdict);
140
+ // Mirror renderAskCli: tiny delay so Ink flushes unmount
141
+ // before the caller prints the toast line.
142
+ setTimeout(() => exit(), 16);
143
+ } }));
144
+ }
145
+ const instance = render(_jsx(App, {}));
146
+ const verdict = await outerPromise;
147
+ try {
148
+ await instance.waitUntilExit();
149
+ }
150
+ catch {
151
+ // Ink can throw when exit() races with a re-render — the verdict
152
+ // is already captured so we ignore.
153
+ }
154
+ return verdict;
155
+ }
156
+ //# sourceMappingURL=feedback-prompt.js.map